views:

254

answers:

1

Hi,

I have an application that has a "parent" window. In the parent window there are menu items, like the following (using PHP here):

// sample link
echo "<li><a href=\"#\" onclick=openurl('covershift.php');>Shift Coverage</a></\
li>";

// logout link
echo "<li><a href=\"#\" onclick=openurl('logout');>Logout</a></li>";

Each link opens the appropriate page in a different "child" window. When the parent closes all of the child windows must close. I have implemented this functionality with Javascript, here is the function:

var childWindow = new Array();
var windowCount = 0;
function openurl(url)
{
  if(url != 'logout') {
    childWindow[windowCount]=window.open(url,'_blank','height=600,width=800,scr\
ollbars=1');
    windowCount++;
    if (window.focus) {
      childWindow.focus();
    }
  } else {
    var iCount;
    for (iCount=0; iCount < windowCount; iCount++) {
      if ((childWindow[iCount] != null) && !(childWindow[iCount].closed)) {
        childWindow[iCount].close();
      }
    }
    window.location='logout.php';
  }
}

Here is my problem, when a user reloads the parent window and then clicks logout, the child windows remain open. This makes sense as the childWindow array is lost when the parent reloads.

How can I make the childWindow array persistent through a reload?

Thanks!

+1  A: 

I don't think you can make a JavaScript object persist through a window load. Instead, could you make an unload event handler that closes your pages?

window.onunload = myCloseFunction;
function myCloseFunction()
{
    // Just copying your code...
    var iCount;
    for (iCount=0; iCount < windowCount; iCount++) {
      if ((childWindow[iCount] != null) && !(childWindow[iCount].closed)) {
        childWindow[iCount].close();
      }
    }
}

Another option might be to have the child windows poll for the existence of the parent.

In the child window:

// Checks every 1 second for valid window.opener
var parentChecker = setInterval(function(){
    if(!opener){
        // Is this good practice?  I don't know!
        clearInterval(parentChecker);
        window.close();
    }
}, 1000);
Jonathon
Jonathon,Thank you for the prompt reply. Both solutions have their merits. The first is nice because it requires a modification in only one place. The only issue I can foresee with the first solution is that a user might want to preserve their data on the child windows and just reload the parent window. The second solution probably won't work due to user behavior. The users of my application are notorious for just clicking buttons, and, hence, might accidentally close the parent and call me with a bug report :-). If there is no way to make the data persisent, I will go with option 1. Thanks!
Guhan Iyer