How to bypass popup-blockers in async code

2016-08-05 | #javascript, #solution, #webdev

If a new window is not directly opened in the handler of a conscious user interaction such as a click the browser's popup blocker will most likely suppress any try try to open an new window.

This is especially frustrating if you ARE in a click handler, but have to do async stuff like an ajax request, which, for example, returns the url you want to redirect to.

You can circumvent this problem with a little trick:

Since you have a handler for user interaction you can open the window there already, using the window's reference later again, when you have received the URL.

$('button').on('click', function(){

var fooWindow = window.open('about:blank', '_blank');

$.getJSON('/my/ajax/url/')

.done(function(json){

fooWindow.location.href = json.fooUrl;

})

;

});