Click here to Skip to main content
6,822,123 members and growing! (16,132 online)
Email Password   helpLost your password?
Web Development » Client side scripting » General     Intermediate License: The Code Project Open License (CPOL)

JavaScript to close child windows

By MCF.Goodwin

How to close open child windows when parent window is closed, using JavaScript.
Javascript, CSS, HTML, XHTML, ASP, ASP.NET, Ajax
Posted:12 Sep 2008
Views:15,573
Bookmarked:18 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
8 votes for this article.
Popularity: 4.38 Rating: 4.85 out of 5

1

2

3
1 vote, 12.5%
4
7 votes, 87.5%
5

How to Close Child Windows When the Parent Window Closes

The Motivation

When moving an application from Windows to web, I noticed that certain functionality available only in a Windows Form is expected to be carried over to the web form. Unfortunately, sometimes, achieving the said functionality can be a bit more difficult than expected.

The Objective

Being object oriented in nature, I wanted a drop in solution on the client side to achieve closing child windows. Doing a bit of research told me that the call to window.open would return a window object that I could then (at a later time) call close on. The question to be answered was how to store each window object upon opening, and how to detect the browser closing in order to close the child windows.

Note: There are more than a few articles out there on creating objects in JavaScript, and it is beyond the scope of this article.

The Code

Persisting Window Handles

The first thing, persist the window object returned by the open function call. I achieved this by storing it as a private Array within my object.

function windowController(){
  //Note: The absence of “this” indicates private
  var loadedWindows = new Array()
  …..
} //Note: Yes, in JavaScript an object
  // is declared similar to a function.

Encapsulate window.open

Now that I have a nifty array, I need a public method that would wrap the window.open function to capture the returned object and add to my array.

this.popUpWindow = function(wndUrl, wndName, wndWidth, wndHeight){
var windObj = null;
try
{
  //set default width 
  if(typeof wndWidth == 'undefined') wndWidth=500;
  //set default height
  if(typeof wndHeight == 'undefined') wndHeight=250;
  windObj = window.open(wndUrl, 
    //misc options to open a window, again mostly optional 
    wndName, 'toolbar=0,menubar=0,resizable=0,location=0,
    directories=0,width='+wndWidth+',height='+wndHeight); 
  windObj.registerID = wndName; //this is the key to the window
  loadedWindows[loadedWindows.length] = windObj;
  //add the window to our collection.
}
catch(ex) { 
  alert('WindowController.popUpWindow: ' + 
        'Exception occured, message: ' + ex.message)
} //oops, looks like we are cross domain scripting.
return windObj;
}

Further Enhance Encapsulation

Since I am wrapping window.open, I decided to only allow a single instance of each handle ID to be opened, by checking the ID against each window handle already loaded, and if it exists, I simply call focus (this is similar to what is expected from Windows Forms).

this.popUpWindow = function(wndUrl, wndName, wndWidth, wndHeight){
  var windObj = null;
  try{
    windObj = findWindow(wndName);
    if (windObj != null)
    {
      windObj.focus();
    }
    else
    {
     ......
    }

where the findWindow function simply iterates the array, and returns null if not found.

function findWindow(winHandle){
  for (var i=0; i< loadedWindows.length; i++){
  if (loadedWindows[i].closed == true){
    loadedWindows.splice(i,1);
    i--;
  }
  else{
    if (loadedWindows[i].registerID == winHandle)
      return loadedWindows[i];
    }
  }
  return null;
}

Pulling it all Together

Finally, I needed a way to know when the browser was closing in order to close all my child windows. Of course, IE, compared to other browsers, has different ways to register to events, so I created a generic method to achieve this.

function WireEvent(elem,target,func){
  if (elem.addEventListener)
    elem.addEventListener(target, func, false); //FF
  else if (elem.attachEvent)
    elem.attachEvent(target, func); //IE
  }
  WireEvent(window,'onunload',_windowController.closeAllWindows);

where the onunload function is handled as follows:

this.closeAllWindows = function(){
  for(var x = 0; x < loadedWindows.length; x++){
    try{
      loadedWindows[x].close();
    }
    catch(err) {
      alert('WindowController.closeAllWindows: ' + 
            'Exception occured, message: ' + err.message)
    }
  } //oops, cross domain scripting or window already closed etc...
}

Looks like all is in place, the last thing I needed was the ability to init the object so it would be available from code, so I added the call at the top of the js file, as follows….

var _windowController = new windowController();

Using the Object

Now, if the file is included, we have access to the window controller, so as long as all opened child windows are done through this object, we can be certain they will close upon browser exit as long as we are not cross domain.

_windowController.popUpWindow('ChildForm.aspx', 'ChildForm');

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

MCF.Goodwin


Member
Ah, just another dev living the life of Dilbert. Smile
Occupation: Software Developer
Location: United States United States

Other popular Client side scripting articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 7 of 7 (Total in Forum: 7) (Refresh)FirstPrevNext
GeneralExcellent code PinmemberEdwill Leighton6:35 25 Jun '09  
Generalgood Pinmemberaxkiller0:34 3 Jun '09  
GeneralNice article but incomplete solution PinmemberMember 15911270:07 25 Nov '08  
GeneralPrb downloading your sample PinmemberpMeric21:01 15 Sep '08  
GeneralRe: Prb downloading your sample PinmemberMCF.Goodwin1:20 16 Sep '08  
GeneralRe: Prb downloading your sample PinmemberpMeric2:19 16 Sep '08  
GeneralInteresting article Pinmembero_theophilus7:29 15 Sep '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads.

PermaLink | Privacy | Terms of Use
Last Updated: 12 Sep 2008
Editor: Smitha Vijayan
Copyright 2008 by MCF.Goodwin
Everything else Copyright © CodeProject, 1999-2010
Web10 | Advertise on the Code Project