Select Page

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

Using windows.open() function to show pop-up in browser

All browsers support window.open() to show popups, but there are some rules there. The window should be open as a result of a user action, for example, button click. Still, if you add an ajax call inside of the button click event and try to open the popup window inside of callback, it is no longer considered as a user action, and such popup will be blocked. For example, the following code opens a new window as a result of an ajax call and the user will see a “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();
}) 
} 

Users can unblock such pop-up windows, but there is a better way to solve this issue without the user doing extra work.

The correct way of opening a new pop-up window in JavaScript

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

The following code shows how to correctly call window.open() to show a pop-up, which will not be blocked by the browser.

// immediately open a new pop up window, but fill it with content later, 
// when ajax request will be completed
printButtonClicked: function(){              
	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 a new window and save its ID, so later after the ajax call will be done, you can update the content of the pop-up to whatever was returned to you from the server.