Why does window.open(...).onunload = function () { ... } not work as I expect?
Asked Answered
T

4

15

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?

Tillery answered 19/9, 2011 at 20:7 Comment(2)
What about changing window.alert to windowref.alert?Carman
@Carman The problem isn't with where the alert is coming from, it's with when the alert is being shown.Tillery
V
33

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!');
            };
      }
};
Viridissa answered 19/9, 2011 at 20:20 Comment(3)
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.Tillery
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.Tillery
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-securityDipper
P
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

Peltry answered 19/9, 2011 at 20:25 Comment(2)
Modern browsers have new rules from not allowing certain actions on window close, this might be one of them now. Maybe onbeforeunload will work.Peltry
can you please assist me for working with modern browser ? The above code doesn't work if i write "window.open('google.com')"........... else only workes if the URL same as parent.Elm
I
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!');
    });
};
Interact answered 25/5, 2023 at 13:47 Comment(0)
C
1

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>
Christchurch answered 27/6, 2023 at 13:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.