Thursday, 9 February 2012

How to close child windows when closing parent window in javascript?

In many instances we want to close all child windows when main parent window is closed. This can be easily achieved using javascript.

To achieve this we need to do three thing

1) Create an array. This array is required for storing references of all child windows.


var childwindows = new Array();

2) Open child window using window.open and then store references of child window into an array

function openPopup(){
 try{
  var d = new Date();
  var win = window.open("Test.html",'test'+d.getMilliseconds(),'width=200,height=100')
  childwindows[childwindows.length] = win;
  win.focus();
 }catch(e){
  alert(e);
 }
}

3) Finally close all child windows on window.onunload event.

window.onunload = function closeChildWin(){
 for(var i=0; i<childwindows.length; i++){
  try{
     childwindows[i].close()
  }catch(e){
   alert(e);
  }
 }
}



To test this you can copy and paste following code into the file and save it as a Test.html. Let me know if it has helped you.

<html>
 <body>
        <input type="submit" onclick="openPopup()" value="Open new Window">
 </body>
</html>

<script>

var childwindows = new Array();

function openPopup(){
 try{
  var d = new Date();
  var win = window.open("Test.html",'test'+d.getMilliseconds(),'width=200,height=100')
  childwindows[childwindows.length] = win;
  win.focus();
 }catch(e){
  alert(e);
 }
}

window.onunload = function closeChildWin(){
 for(var i=0; i<childwindows.length; i++){
  try{
     childwindows[i].close()
  }catch(e){
   alert(e);
  }
 }
}

</script>

5 comments:

  1. nice article, it helped me a lot

    ReplyDelete
  2. Thanks a lot for the detailed example! Very helpful

    ReplyDelete
  3. And what happens when you refresh the parent window? Unload event will be triggered even when you refresh the parent window.

    ReplyDelete

There was an error in this gadget