Google Chrome seems to be blocking a popup I am creating via jQuery. After some investigation, it appears to be an issue with calling window.open
in the success event of an ajax call. Is there a way around this? My jQuery ajax call returns the URL to be opened. So I am bit stuck.
It works if I place the window.open
outside the ajax call; but, inside (i.e. in the success event) it is blocked. I think it is something to do with CONTEXT but I am unsure.
Here is what I have:
window.open("https://www.myurl.com"); // OUTSIDE OF AJAX - no problems
// with popup
$.ajax({
type: "POST",
url: "MyService.aspx/ConstructUrl",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Normally loads msg.d which is the url returned from service
// static url below is for testing
window.open("https://www.myurl.com"); // THIS IS BLOCKED
},
error: function(msg) {
// alert(error);
}
});
What is AJAX success? AJAX success is a global event. Global events are triggered on the document to call any handlers who may be listening. The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds.
The parameter is not being deprecated, the success method is. You can continue using success: function re-read it carefully.
success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine. However, . complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - . complete() will still get called.
jQuery - ajaxSuccess( callback ) Method The ajaxSuccess( callback ) method attaches a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With