当弹出窗口关闭时,如何引发事件(jQuery或vanilla Javascript)?

当弹出窗口关闭时,如何引发事件(jQuery或vanilla Javascript)?

问题描述:

我希望在弹出窗口关闭时,或者最好在关闭之前引发一个事件。我将弹出窗口对象存储为对象,但我不知道绑定到close事件的任何方式,或者在窗口关闭之前的事件。

I want to raise an event when a popup window is closed, or preferably, just before closing. I'm storing the popup window object as an object, but I don't know of any way to bind to the close event, or an event just before the window is closed.

var popupWindow = window.open("/popup.aspx", "popupWindow", "height=550,width=780");

有没有办法使用jQuery或原始javascript订阅close事件?我正在使用jQuery并且不能添加另一个库,所以如果它不能在jQuery中完成,我将不得不以某种方式滚动我自己的事件系统,以便它可以在所有浏览器中工作。

Is there any way to subscribe to the close event using jQuery, or just raw javascript? I'm using jQuery and can't add another library, so if it can't be done in jQuery I'll have to roll my own event system somehow so that it will work across all browsers.

更新:

我尝试在jQuery中使用unload事件,由于某种原因,只要我的弹出窗口打开而不是引发事件当它关闭。如果我使用Firebug设置断点来延迟卸载事件的订阅,则卸载事件的工作方式应该如此,但无论出于何种原因,当允许javascript自然执行时它无法正常工作。

UPDATE:
I've tried using the unload event in jQuery and for some reason the event is raised as soon as my popup opens instead of when it is closed. If I use Firebug to set a breakpoint to delay the unload event from being subscribed to, the unload event works the way it is supposed to, but for whatever reason, it doesn't work correctly when the javascript is allowed to execute naturally.

var popupWindow = window.open("/popup.aspx", "popupWindow", "height=550,width=780");
$(popupWindow.window).unload(function() { alert('hello'); });

是否有人知道为什么在加载窗口时可能会引发卸载事件?

Does anybody have any idea as to why the unload event could be raised when the window is loading?

另一个问题是,我注意到jQuery的卸载事件不会像通常那样保持订阅窗口:

One other catch is that I've noticed that jQuery's "unload" event does not stay subscribed to the window like it normally does if I just do:

popupWindow.onunload = function(){alert('hello')};

每次募集活动似乎都取消订阅。这应该发生吗?如果它不是jQuery中的这个bug(或功能?),那么可以在加载时引发事件,因为我可以检查 popupWindow.closed 属性在事件内部,以确保窗口真的关闭。

It seems to unsubscribe from the event every time it is raised. Is this supposed to happen? If it weren't for this bug (or feature?) in jQuery, it would by fine to have the event get raised on load since I can check the popupWindow.closed property inside of the event to ensure the window was really closed.

我创建了一个检查器,检查窗口是否已关闭:

I created a watcher that checks if the window has been closed:

var w = window.open("http://www.google.com", "_blank", 'top=442,width=480,height=460,resizable=yes', true);
var watchClose = setInterval(function() {
    if (w.closed) {
     clearTimeout(watchClose);
     //Do something here...
    }
 }, 200);