tags:

views:

185

answers:

2

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.
+4  A: 
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();
      }
     }
    }
}
Chacha102
Lest we forget about `push`. It's cleaner and faster (generally): `this.child.push(window.open(url, '', params);`
Justin Johnson
There you go. Not a Javascript expert, thanks for the help.
Chacha102
+1  A: 

Keep track of the windows that are opened by storing their handles, then use the close() method on the window handles from the button's click handler.

Personally, I find popup windows to be a really annoying feature when used in a web interface. If you can possibly avoid them by using DOM-based dialogs, please do. The jQuery dialog plugin is very handy for this.

tvanfosson