KoffeeKoder


  • Closing Child Windows When the Parent is Closed
    published on 7/5/2008 8:56:06 PM
  • Recently, a friend of mine emailed me and asked how to close the child windows when the parent is closed. This is kind of a strange requirement since if I am the user on a site I would not want the parent window to automatically close all the child windows when the parent is closed. But anyways, the client gets what the client wants.

    So, here is the code. I am making sure that I keep track of all the opened child windows and then when the parent is closed simply use a loop to iterate through the child windows and close them.

    The "onunload" event is attached to the body of the parent window. Please note that this event is also fired when the page is refreshed.



    <body onunload="closeChildWindows()">

     <a href="#" onclick="openWindow('Pop1.aspx','Pop1')">Open Window 1</a>
       
        <a href="#" onclick="openWindow('Pop2.aspx','Pop2')">Open Window 2</a>

    <script language="javascript" type="text/javascript">

    // create an array of child windows
    var childWindows = new Array();

    function openWindow(url,name)
    {
       newWindow = window.open(url,name,'width=100,height=100;dependent=yes');
       // add the new child window in the collection
       childWindows.push(newWindow);
        
    }

    function closeChildWindows()
    {
       
        if(!sure) return;

       // iterate through the collection and close all the windows 
      
       for(i=0; i<childWindows.length; i++)
       {
           childWindows[i].close();
       }
    }

    </script>



    You can also use a confirm box when closing the child. This will alarm the user that all the child windows will be closed and he/she can chose not to close the child windows.  

    That's it!