Saturday, August 9, 2008

JavaScript: Closing all child windows when parent window is closed

Consider that if you have opened multiple new windows thru window.open() method of JS and if you want all of the child windows to be closed here is the sample code for that -

Here, when you open a new window assume that you are opening it thru NewWin(..) function.

var childWin=new Array();
var childCnt = 0;
function NewWin(obj,name)
{
childWin[childCnt++] = window.open(obj,name,’height=200,width=400′);
}

function CloseAllChildWin()
{
for( cnt=0; cnt < childWin.length;cnt++)
{
if(childWin[cnt])
childWin[cnt].close();
}
}


Now register the onunload event to the BODY tag with the function CloseAllChildWin(). So, if you have opened any windows thru the NewWin() function, all the opened windows will be closed when you press the F5 key / Refresh button / Close button.

There is another way to handle, the child windows should be closed only when the 'X' / Close button is clicked. To achieve this just modify the CloseAllChildWin() as follows -


function CloseAllChildWin()
{
if( event.clientX < 0 && event.clientY < 0 )
{
for( cnt=0; cnt < childWin.length;cnt++)
{
if(childWin[cnt])
childWin[cnt].close();
}
}
}

No comments: