简体   繁体   中英

window.close(); not working when page changed or refreshed

I have this little function to open/close a popup player:

function popuponclick(popup)
{
  my_window = window.open("folder/player-itself.htm", popup, "width=350,height=150");  
}

function closepopup()
{
  my_window.close();
}

I call the functions from HTML anchors that are on each page of the site (idea is to have the player stopped/started whenever you want)...now...

it works well until i change the page, or refresh the existing one - and from then the window can't be closed anymore. Any idea where i'm wrong? Tested in FF and IE8, same behavior.

Thanks for your help.

When you reload the original window (or tab), everything about the old one is gone, blasted into the digital void, never to be seen or heard from again. The bits literally disintegrate into nothingness.

Thus, the "my_window" reference you so lovingly saved when the second window was opened is gone for good, and the "my_window" variable in the newly-loaded window contains nothing. It's name is but a mockery of the variable in the now-dead page.

The only way to deal with this situation is for the popup window to periodically check back via "window.opener" to see if its parent page has been rudely replaced by some interloper. If that happens (and the new page is from the same domain), then the popup page can restore the reference to itself in the new page's "my_window" variable.

edit — OK here's a sample. You'd put something like this in the popup page, not the launching pages:

<script>
  var checkParent = setInterval(function() {
    try {
      if (window.opener && ('my_window' in window.opener))
        window.opener.my_window = window;
    }
    catch (_) {
      // clear the timer, since we probably won't be able to fix it now
      clearInterval(checkParent);
    }
  }, 100);
</script>

That's probably pretty close.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM