Simple Popup Window Management In JavaScript

This article Based on a question that I received earlier this week on closing windows within a page that were opened through the window.open() function in JavaScript, I thought I would throw together a very quick example demonstrating how to easily open and close them all from the page that spawned them.

The Problem

You spawned a rogue window through JavaScript and you want to close it from the page that spawned it (or you want it to go away when you leave the page as well).

The Solution

The simplest method of handling this issue is to have a single variable within your JavaScript code keep track of the window that you opened and dispose of it properly. So we will add a variable that will store our value windowOpened and our necessary functionality to open and close the window:

  1. <script type='text/javascript'>  
  2.     // Stores our opened window  
  3.     var windowOpened;  
  4.   
  5.     // Opens our Window  
  6.     function openWindow() {  
  7.         windowOpened = window.open("http://www.microsoft.com""ChildWindow""height=600,width=300");  
  8.     }  
  9.     // Closes the window  
  10.     function closeWindow() {  
  11.         windowOpened.close();  
  12.     }  
  13. </script>  

That’s basically it. So to see it in action, we would just need to wire up two buttons to handle showing and hiding the window: 

  1. <input type='button' value='Create Popup' onclick='openWindow();' />   
  2. <input type='button' value='Close Popup' onclick='closeWindow();' />   

No Child Left Behind

If you wanted to ensure that you didn’t leave a poor orphaned popup window all by its lonesome if the parent page navigated elsewhere, you would just need to add the closeWindow() function to the onunload event from the body element of your parent page: 

  1. <body onunload='closeWindow();'>   

You can find a full working example of this post available here.

Up Next
    Ebook Download
    View all
    Learn
    View all