Skip to content
Advertisement

Close all popup windows with Javascript

Does anyone know how can I close all popup windows (window popup by javascript) in Javascript?

Example:

  1. Open 3 new windows by clicked on a button, and using window.open() to open all 3 new windows.
  2. Clicked on a button and close all 3 popup windows togather.

Advertisement

Answer

var childWindowHandles = new Array();

function openNewWindow(url, params) {
    childWindowHandles[childWindowHandles.length] = window.open(url, '', params);
}    

function closeChildWindows() {
    for (var loop=0; loop<childWindowHandles.length; loop++) 
    {
        if (!childWindowHandles[loop].closed)
        {
            childWindowHandles[loop].close();
        }
    }
}

Second result on Google. Closes ALL Windows after storing them in an array.

Here is a more OOP way, if you don’t like the global variables. (I’m not 100% sure that it works, just modified the above code.

popups = new popups();
function popups()
{
    this.childs = new array();

    this.open = function(url, params)
    {
        this.child.push(window.open(url, '', params)); 
    }

    this.closeAll()
    {
        for(var loop=0; loop<this.childs.length; loop++)
        {
            if (!this.childs[loop].closed)
            {
                this.childs[loop].close();
            }
        }
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement