0

I have an ajax call through jQuery; when it completes I need to open an URL in a new tab.

I wrote this simple function:

var openWin = function() {
    window.open('/UrlToOpen', '_blank');
    win.focus();
}

If I call this function directly from JS code, it opens without triggering the pop-up blocker.

If I call it from $.ajax().done(), like this:

$.ajax({
        url: 'ajaxUrl',
        type: 'POST'
    }).done(function (result) {
        openWin();
}); 

The pop-up blocker is triggered.

Demonstration here: https://jsfiddle.net/dggwL5uj/

Why? How can I avoid this?

Andrea Colleoni
  • 5,623
  • 3
  • 27
  • 47
  • 2
    You can't avoid this, this is how popup blockers work, they block everything that isn't directly initiated by the user. – adeneo Mar 31 '15 at 12:57
  • See here: http://stackoverflow.com/questions/9514698/bypass-popup-blocker-on-window-open-when-jquery-event-preventdefault-is-set – Red2678 Mar 31 '15 at 12:58
  • Thank you; "that isn't directly initiated by the user" was the missing bit..., so "async: false" was the response. :-) – Andrea Colleoni Mar 31 '15 at 13:02
  • 1
    Synchronous requests are a bad idea. So are pop up windows. – epascarello Mar 31 '15 at 13:05

1 Answers1

1

If change your ajax request to synchronous this might be working.

$.ajax({
        url: 'ajaxUrl',
        type: 'POST',
        async: false,
    }).done(function (result) {
        openWin();
}); 

As explained in the comment, A browser will only open a tab/popup without the popup blocker warning, if the command to open the tab/popup comes from a trusted event.

Ravi Kant Mishra
  • 738
  • 7
  • 13