views:

603

answers:

4

Hi,

With some javascript I openup a popup no prob using:

function myPopup2(x){
    if (x==1)
    {
        myWindow = window.open( "timer.html", "", "height = 150, width = 300" );
    }else
    {
        myWindow.close();
    }
}

I then run some PHP script which refreshs reloads the page.

When I later then go to close the popup - it doesn't, because the page has been reloaded and myWindow variable gone. 'myWindow' is undefined is the javascript error.

Anyone know how I can get around this?

Thanks,

A: 

As outlined here: http://www.faqts.com/knowledge_base/view.phtml/aid/1460

window.open() takes a second parameter, which is the name of the window. On refresh, you could check on the status of that window and close it if necessary. As discussed in the link, there's no direct way to check for the window after refresh, so you have to do something like this:

var win = window.open ('', 'windowName')

and then operate on win.

(edit: I initally had a second idea involving cookies, but I don't think that really saves you anything, since you still have to do the above to access the window.)

sprugman
A: 

I guess you can't. Cause the child window (timer.html) loses its connection to the parent window as soon you refresh it. It would be very scary, if you could close every window from within another window without any reference between both.

Philippe Gerber
+2  A: 

If you give your window a name when you open it, it is possible to get a handle to the window later.

function myPopup2(x){
    if (x==1)
    {
        myWindow = window.open( "timer.html", "windowName", "height = 150, width = 300" );
    }else
    {
        if (!myWindow) {
            myWindow = window.open("", "windowName");
        }
        myWindow.close();
    }
}
Matt Bridges
This does not work in FF 3.0.11
Philippe Gerber
You just beat me to it!..nice one.
thegunner
But it will work without the if statement. :S myWindow = window.open("", "windowName"); myWindow.close();
Philippe Gerber
didn';t need the: if (!myWindow) { bit
thegunner
A: 

Have the child window execute a function every few seconds to check the parent window for a flag that signals it should close. The parent window can set the flag on a reload instead of trying to track down the child.

Scott Stevenson