How to Open and Close Windows with JavaScript from Parent and Child

Today I wasted a couple hours trying to figure out how to close a window that had been opened from a parent page with a button in the child window. I wrote this quick JavaScript tutorial on how to open and close windows from parent and child in hopes that it will help someone else figure it out faster than I did.

To keep it simple, we will use two HTML files in this example and we'll call them open_close_window.html and popup.html where open_close_window.html will be the parent and popup.html will be the child pop up window. open_close_window.html, the parent, will include two JS functions and a button while the child, popup.php will include nothing but a button to close itself. What I found a little odd was that in order to close the child window from within itself, I had to call a function from the parent. Here's how it is done. Below is the full contents of both files:

open_close_window.html content:

<html>
<head>
<script>
var myWin;
function openWin(){
myWin = window.open("popup.html", "myWindow", 'width=600,height=300');
}//end openWin JS function

function closeWin(){
myWin.close();
}//end closeWin JS function
</script>
</head>
<body>
<button type="button" onclick="openWin();">Open Window</button>
</body>
</html>

Notice that I set the var myWin in the first line of the JavaScript code above. It will not work if you do not place the myWin variable in the global scope like this. Also you can not simply name the window in the window.open function call like I thought I could at first, you have to use a variable to reference the window when closing it.

popup.html content:

<html>
<head>
</head>
<body>
<button type="button" onclick="opener.closeWin();">Close Window</button>
</body>
</html>

Summary

I hope you can see how this all works from this simple demonstration. You don't even need to upload the two files to a web server to test them since they are HTML files, simply place both on your desktop and open the parent, open_close_window.html from there and see how you can click the button to open the child window and then click the child's button to close itself by calling a close function in the parent. Odd, but that's how it's done!

Leave a Reply

Your email address will not be published. Required fields are marked *