0

I'm trying to write a bookmarklet that takes the site the user is on, does some parsing and an ajax request, and opens a new window with that info as a param.

Here's what I've got:

<a href="javascript:
(function($) 
{
  var a, http, options, request, st, u;

  u = document.location.hostname;

  a = u.split('.');

  st = a[a.length - 2];
  path = 'http://ajax.googleapis.com/ajax/services/feed/find?callback=?&v=1.0&q=' + st;
  $.ajax
  ({
    type: 'GET',
    url: path,
    async: false,
dataType: 'json',
success: function(data)
{   
  var targ  = data['responseData']['entries'][0]['url'];
  window.open ('http://localhost:3000/bmfeed?targ='+targ,'menubar=1,resizable=1,width=350,height=250');
}
  });
})(jQuery)

"> newwindow </a>

It finds the right url, but the new window is blocked by the popup blocker.

If instead I just have

<a href='javascript: window.open ("http://localhost:3000?targ=asdfasdf","mywindow","menubar=1,resizable=1,width=350,height=250");'> oneline </a>

it opens a new tab uninhibited. I assume that the difference is that i'm doing some parsing in the first example, which the browser doesn't like.

Is there a way to have my cake and eat it too? Thanks a bunch!

xavdid
  • 5,092
  • 3
  • 20
  • 32
  • 1
    window.open must be called from clicking a button or link, the bookmarklet just magically happens as far as JS is concerned. You can append a link to the doc to call the last line onclick, use an iframe, or set location.href instead of using a popup. – dandavis Jun 20 '13 at 17:40

1 Answers1

0

I assume that the difference is that i'm doing some parsing in the first example

No, the problem is the asynchronous AJAX. The browser tries to determine if a user action initiated a new window or not before deciding to block it or not. For the new window to open without blocking, there must be a "direct line of action" between the user click and the window opening. The async AJAX breaks that direct line. (Synchronous AJAX might work, I'm not sure.)

Is there a way to have my cake and eat it too?

There is no perfect solution, but an improvement over what you have now is to create a pop-over div on the page with a link similar to <a href="http://localhost:3000/bmfeed?targ=..." target="_blank">click here to open the new window</a>.

DG.
  • 3,417
  • 2
  • 23
  • 28