Search code examples
javascriptasp.netinternet-explorer-9

Check if a popup window is closed


I am opening a popup window with

var popup = window.open('...', '...');

This javascript is defined in a control. This control is then used from a web page. I want to reload the page which opens this popup when the popup is closed.

Basically user is required to input some denominations in the popup window and submit. These denominations are then stored in user sessions. And when user clicks submit I am closing the popup window and at the same time want to refresh the window which opens this popup to refetch the updates which user made in the popup.

I am trying to do

var popup = window.open('...','...');
if (popup) {
  popup.onClose = function () { popup.opener.location.reload(); }
}

I guess I am doing it wrong coz this isn't seems to be working.

For testing the issue I've even tried this but no alert appeared.

if (popup) {
  popup.onclose = function() { 
    alert("1.InsideHandler");
    if (opener && !opener.closed) { 
      alert("2.Executed.");
      opener.location.reload(true); 
    } else { 
      alert("3.NotExecuted.");
    }
  }
}

Solution

  • Here's what I suggest (updated to newer code)

    in the popup you should have:

    const reloadOpener = () => {
      if (top.opener && !top.opener.closed) {
        try {
          opener.location.reload(1); 
        }
        catch(e) {
        }
        window.close();
      }
    }
    window.addEventListener("unload", () => {
      reloadOpener();
    })
    
    <form action="..." target="hiddenFrame">
    </form>
    <iframe style="width:10px; height:10px; display:none" name="hiddenFrame" src="about:blank"></iframe>
    

    then assuming the same origin, the server process can return

    <script> top.close(); </script>
    

    NOTE: location.reload takes a boolean, add true if you want to not load from cache as in opener.location.reload(1);