Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome window.open after ajax request acts like popup

I have a situation where, when a user pushes a button I perform an ajax request, and then use the result of the ajax request to generate a URL which I want to open in a new tab. However, in chrome when I call window.open in the success handler for the ajax request, it opens in a new window like a popup (and is blocked by popup-blockers). My guess is that since the the success code is asynchronous from the click handling code that chrome thinks it wasn't triggered by a click, even though it is causally related to a click. Is there any way to prevent this without making the ajax request synchronous?

EDIT Here is some minimal code that demonstrates this behaviour:

$('#myButton').click(function() {
    $.ajax({
        type: 'POST',
        url: '/echo/json/',
        data: {'json': JSON.stringify({
            url:'http://google.com'})},
        success: function(data) {
            window.open(data.url,'_blank');
        }
    });
});

http://jsfiddle.net/ESMUA/2/

One note of clarification: I am more conerned about it opening in a separate window rather than a tab, than I am about it being blocked by a popup blocker.

like image 551
Thayne Avatar asked Feb 25 '14 07:02

Thayne


1 Answers

Try to add

window.open(url,'_blank');

Edit

Well, I don't think you can get around popup-blockers when opening a page that's not the immediate result of a user action (i.e. not async).

You could try something like this though, it should look like a user action to a popup-blocker:

var $a = $('<a>', {
        href: url,
        target: '_blank' 
    });

$(document.body).append($a);
$a.click();

Edit 2

Looks like you're better of keeping things sync.

As long as the new window is "same origin" you have some power to manipulate it with JS.

$('#a').on('click', function(e){
    e.preventDefault();
    var wi = window.open('about:blank', '_blank');

    setTimeout(function(){ // async
        wi.location.href = 'http://google.com';
    }, 500);
});
like image 182
pstenstrm Avatar answered Sep 18 '22 17:09

pstenstrm