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

前端 未结 2 1324
时光说笑
时光说笑 2021-02-19 22:10

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:


  
    &l         


        
相关标签:
2条回答
  • 2021-02-19 22:58

    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!');
                };
          }
    };
    
    0 讨论(0)
  • 2021-02-19 23:06

    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

    0 讨论(0)
提交回复
热议问题