Popup blocked when created in jQuery ajax success callback

Firefox does popup blocking based on the event that causes the javascript code to run; e.g., it will allow a popup to open that was triggered from an onclick, but not one that was triggered by a setTimeout. It has gotten a little bit complicated over the years as advertisers have tried to circumvent firefox's popup blocker.


Simply open the new window in the success callback:

 $.ajax({
    type: "POST",
    url: "MyService.aspx/ConstructUrl",
    data: jsonData,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        window.open("https://www.myurl.com"); 
    },
    error: function(msg) {
        //alert(error);
    }
});

Note you might have to set $.ajax's async option to false for that, otherwise the code following the $.ajax call could be evaluated before the response is received.


Your code returns these in firefox and chrome:

Firefox: "Firefox prevented this site from opening a pop-up window." Chrome: "Pop-up blocked"

To fix this issue just add async:false to your ajax call.

$.ajax({
type: "POST",
async: false,
url: "MyService.aspx/ConstructUrl",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(url) {
    window.open(url); 
},
error: function(msg) {
    //alert(error);
}

});

Just be careful that async:false will force javascript to wait for jQuery ajax result. It means it freezes javascript until ajax call is completed.


As several people have pointed out, the accepted answer no longer works. Based on the comment by aidiakapi, I used a workaround by first opening the window.

window.open("about:blank", "myNewPage");

Then doing the ajax business and in the done() function, open the page with that name.

window.open("/foo.html", "myNewPage");

This also doesn't matter if you do it async or not.

Tags:

Ajax

Popup

Jquery