Java Script: Closing child window or tab on parent window closing or refreshing

I have a web page which loads a window or tab on clicking a button using java script. Later on, I figured out that the popup window was not closing on closing the parent window. After some digging on the web, I found the below method for closing the child  window when the parent window closes or refresh.

There should be two java script functions. One for opening the child window. Another for closing the child window. Make sure the window.open object is stored in the variable (var mtbChildWin in the sample source code below) which can be used by both the functions. Call the function which us used to close the window from the onunload event from the body html tag.

This method will help to close the child window on closing the parent window or when the parent window is refreshed.

Read my other article for closing multiple child windows on refreshing or closing the parent window (Java Script: Closing multiple child windows on parent window closing or refreshing).

Sample Source Code in the parent page for closing child window:

<html>
<head>
<title>www.MyTecBits.com</title>
<script type="text/javascript">
<!--
 var mtbChildWin;

function LaunchMyTecBitsWindow() {
 mtbChildWin = window.open("mtbTest.htm", "MyTecBits-Child");
 return false;
 }

function CloseMyTecBitsWindow() {
 if (mtbChildWin != null && !mtbChildWin.closed)
 mtbChildWin.close();
 }
-->
</script>
</head>
<body onunload="CloseMyTecBitsWindow();">
 <input type=button value="Open Child" onclick="LaunchMyTecBitsWindow();"/>
 <br />
</body>
</html>

Java-Script-Closing-Child-Window-2


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.