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

血红的双手。 提交于 2019-12-05 15:44:33

问题


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?


回答1:


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!');
            };
      }
};



回答2:


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



来源:https://stackoverflow.com/questions/7476660/why-does-window-open-onunload-function-not-work-as-i-expect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!