Open a popup window in Javascript with window.open – crossbrowser solution

The javascript function window.open() seems to be not that advanced, you send the url as a parameter, set the name – width and height of the popup and off you go. But no, the world has never been this easy.

Suddenly you start to get errors because of illegal characters in the name (for some browsers whitespaces are not allowed), or the url contains parameters that have special characters that are not encoded. And you don’t even get proper error messages, the “missing ) after argument list” seems (stupidly enough) to be a common message to give in the console if the javascript you have tried to execute is not valid in some way.

On top of this you have different browser behaviour, and you should also handle different cases like if the window is already open (but you want to use another url), if it has focus and so on.

Spending my time trying to make a popup window behave properly in both IE and Firefox, I came up with the following solution, which seems to cover all cases:


var myPopupWindow = '';
function openPopupWindow(url, name, width, height)
{
    //Remove special characters from name
    name = name.replace(/\/|\-|\./gi, "");

    //Remove whitespaces from name
    var whitespace = new RegExp("\\s","g");
    name = name.replace(whitespace,"");

    //If it is already open
    if (!myPopupWindow.closed && myPopupWindow.location)
    {
        myPopupWindow.location.href = encodeUrl(url);
    }
    else
    {
        myPopupWindow= window.open(encodeUrl(url),name, "location=no, scrollbars=yes, resizable=yes, toolbar=no, menubar=no, width=" + width + ", height=" + height );
        if (!myPopupWindow.opener) myPopupWindow.opener = self;
    }

     //If my main window has focus - set it to the popup
    if (window.focus) {myPopupWindow.focus()}
}

This way of doing it has always worked for me at least. So, from your html you would use the function like this on an onclick event:

 onclick="openPopupWindow('http://www.wordpress.com','WP', 450, 600); return false;"

If you set the function on a link, you should include the “return false” as I’ve done here, as this prevents the main page from submitting. You don’t want it to refresh/reload just because you clicked a link that opens a popup.In my openPopupWindow()-function I also use an encodeUrl()-function I created.I’ve talked about it in another post on this blog (How to do proper url encoding), but list it here for reference:

function encodeUrl(url)
{
 	if (url.indexOf("?")>0)
 	{
		encodedParams = "?";
 		parts = url.split("?");
 		params = parts[1].split("&");
 		for(i = 0; i < params.length; i++)
 		{
			if (i > 0)
	 		{
				encodedParams += "&";
			}
			if (params[i].indexOf("=")>0) //Avoid null values
			{
				p = params[i].split("=");
				encodedParams += (p[0] + "=" + escape(encodeURI(p[1])));
			}
			else
			{
				encodedParams += params[i];
			}
		}
		url = parts[0] + encodedParams;
	}
	return url;
}