14

I want to be able to tell when a window that I open is closed by the user. This is the code of my attempt at monitoring this:

<html>
  <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">
        window.document.onready = function () {
            document.getElementById('openWindow').onclick = function () {
                var windowref = window.open('tests2.html');
                windowref.onunload =  function () {
                    window.alert('hola!');
                };
            };
        };
  </script>
</head>
<body>
  <button id='openWindow'>Open Window</button>

</body>
</html>

I would expect this to alert "hola!" in the original window after the window that was opened with window.open was closed. Instead, it alerts "hola!" in the original window immediately after opening the new window with window.open. Why does it work like this? Is there a way of doing what I want to do?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Steven Oxley
  • 6,563
  • 6
  • 43
  • 55

4 Answers4

32

The window first loads with a blank page and then unloads the page, causing the unload event.
Your page then loads. Try attaching the event when the onload event fires to avoid this.

Simple demo

document.getElementById('openWindow').onclick = function () {
      var windowref = window.open('tests2.html');
      windowref.onload = function() {
            windowref.onunload =  function () {
                window.alert('hola!');
            };
      }
};
Digital Plane
  • 37,354
  • 7
  • 57
  • 59
  • I think jsfiddle.net is doing something funky. Clearly, your demo works, but try to put it into an empty HTML page. I can't get it to work in a normal HTML page. The `window.onload` event is never fired. – Steven Oxley Sep 19 '11 at 20:56
  • 1
    Actually, it looks like I was doing something funky. It seems to have to do with the way I was serving the files (via the filesystem instead of a web server). It probably had to do with a same-origin restriction. – Steven Oxley Sep 19 '11 at 20:59
  • 1
    Unfortunately this doesn't work if domain of the new window is different from the parent. It doesn't work even if I run Chrome with `--disable-web-security` – JustAMartin Jul 11 '14 at 14:33
1

Try adding after the window loads

document.getElementById('openWindow').onclick = function () {
    var windowref = window.open('tests2.html');
    windowref.window.onload = function(){  //wait til load to add onunload event
        windowref.window.onunload =  function () {
            window.alert('hola!');
        };
    }
};

JSBin Example

epascarello
  • 204,599
  • 20
  • 195
  • 236
  • Modern browsers have new rules from not allowing certain actions on window close, this might be one of them now. Maybe onbeforeunload will work. – epascarello May 27 '15 at 13:24
  • 1
    can you please assist me for working with modern browser ? The above code doesn't work if i write "window.open('http://google.com')"........... else only workes if the URL same as parent. – Jay May 27 '15 at 13:26
1

Digital Plane answer seems to work, but it feels a bit brittle (e.g. if the browser changed behavior and stopped loading/unloading "about:blank" the event would stop firing.)

My solution was to check windowref.location.href of the popup and skip the handler when it is "about:blank":

document.getElementById('openWindow').onclick = function () {
    var windowref = window.open('tests2.html');
    windowref.addEventListener('unload', () => {
        if (windowref.location.href === "about:blank")
            return;
        window.alert('hola!');
    });
};
InvisibleBacon
  • 3,137
  • 26
  • 27
0

Very late response to this one, but I've just had the same issue with this code in an aspx page:

function handleButton() {
    var myPopup = window.open('/Home/MyPopup', 'Popup');
    myPopup.addEventListener("unload", function (x) {
        console.log(x.results);
    });
}


<button onclick="handleButton()">My Button</button>

My mistake was to omit giving the button a type="button", so the page defaults to type="submit" and posts back when the button is clicked (I assume removing the reference to the event listener when the page reloads). Giving the button a type of button fixed the issue:

<button type="button" onclick="handleButton()">My Button</button>
lukep
  • 111
  • 10