Pages

Wednesday, June 12, 2013

When opening a child window, keep track of it with a window id (JavaScript 1.3)

We're all probably quite familiar with pop-up windows. In the Internet world, pop-up windows are usually advertising links to larger sites. Although, pop-up windows can have a greater purpose. Typically, when launched from a Web application form, they're used to gather information and return it to the parent form. Unfortunately, if this is the case and the user accidentally closes the parent window before the child window, the client produces errors such as, "Access is denied."


However, you can avoid such errors if you have the parent window save a reference to the child window when it opens it. As you know, to open a child window using JavaScript, you use code similar to the followng:

open(url,"","some window attributes");

To save a reference to this window, all you need to do is assign the results of the statement to a variable, like so:

var window_id
window_id = window.open(url,"","some window attributes");

With a window id, the parent window can close all of its child windows when it closes. Here's how you'll do it. First, trap for the onunload() event in the body tag, like so:

<body onunload='onBodyUnload()'>

Then, save the window id like we described earlier. Finally, in the JavaScript function you specify in your onunload() funtion, place the following code:

function onBodyUnload()
   {
      if (!window_id.closed) {
         window_id.close();
      }
   }


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.