Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 872
Steven Oxley Avatar asked Sep 19 '11 20:09

Steven Oxley


People also ask

What is unload in javascript?

Definition and UsageThe onunload event occurs once a page has unloaded (or the browser window has been closed). onunload occurs when the user navigates away from the page (by clicking on a link, submitting a form, closing the browser window, etc.).

How do I unsubscribe from Beforeunload?

Cancelable: The beforeunload event can be canceled by user interaction: // by https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload#Example window. addEventListener("beforeunload", function(event) { event. preventDefault(); // Cancel the event as stated by the standard.


2 Answers

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!');
            };
      }
};
like image 199
Digital Plane Avatar answered Oct 19 '22 12:10

Digital Plane


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

like image 37
epascarello Avatar answered Oct 19 '22 14:10

epascarello