thegunner thegunner - 9 days ago 6
Javascript Question

Close popup window if it exists

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?

Answer

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();
    }
}