How to avoid browser pop-up blockers on window.open

It is very common to open popup window in browser to show some extra information to user or in my case is to open print-friendly version of the page. But you need to be careful when implementing such feature, because if you do it incorrectly your browser can block popup window.

All browsers support window.open() to show popups, but there are some rules there. The window should be open as a result of user action, for example button click, but if you add ajax call inside of button click event and try to open popup window inside of callback, it is no longer considered as user action and such popup will be blocked. For example, the following code opens new window as a result of ajax call and user will see "Pop-up blocked" message


printButtonClicked: function(){
            $.post("/ajax/friendlyPrintPage", postData)
                .done(function(htmlContent) {
                    var id = (new Date()).getTime();
                    var myWindow = window.open(window.location.href + '?printerFriendly=true', id, "toolbar=1,scrollbars=1,location=0,statusbar=0,menubar=1,resizable=1,width=800,height=600,left = 240,top = 212");
                    myWindow.document.write(htmlContent);
                    myWindow.focus();
                });
}

Google Chrome blocks popup window

User can unblock such pop-up windows, but it's not the best way to solve such issue.

Google Chrome unblock popup window

The better way to completely avoid pop-up blocking in browsers is to open new window as a result of user action, but fill it with content later when ajax request completes.

The following code shows how to correctly call window.open() to show popup which will not be blocked by browser.


printButtonClicked: function(){
	// immediately open a new pop up window, but fill it with content later, when ajax request will be completed             
	var id = (new Date()).getTime();
	var myWindow = window.open(window.location.href + '?printerFriendly=true', id, "toolbar=1,scrollbars=1,location=0,statusbar=0,menubar=1,resizable=1,width=800,height=600,left = 240,top = 212");

    $.post("/ajax/friendlyPrintPage", postData)
        .done(function(htmlContent) {
            myWindow.document.write(htmlContent);
            myWindow.focus();
        });
}

As you see the first thing you have to do, is to open new window and save its ID, so later after ajax call will be done, you can update content of pop-up to whatever was returned to you from server.



Comments

Social media

Search

Latest Tweets