是否可以使用javascript打开弹出窗口,然后检测用户何时关闭它?

是否可以使用javascript打开弹出窗口,然后检测用户何时关闭它?

问题描述:

问题几乎全在标题中。

是否有可能(以及如何?)用javascript打开弹出窗口,然后检测用户何时关闭它?

Is it possible (and how?) to open a popup with javascript and then detect when the user closes it?

我在项目中使用jquery,所以jquery解决方案会很好。干杯!

I am using jquery within the project so a jquery solution would be good. Cheers!

如果您可以控制弹出窗口的内容,请处理窗口的卸载事件并通过 opener 属性通知原始窗口,首先检查开启器是否已关闭。请注意,这在Opera中并不总是有效。

If you have control over the contents of the pop-up, handle the window's unload event there and notify the original window via the opener property, checking first whether the opener has been closed. Note this won't always work in Opera.

window.onunload = function() {
    var win = window.opener;
    if (!win.closed) {
        win.someFunctionToCallWhenPopUpCloses();
    }
};

由于卸载事件将在每次发生时触发用户在弹出窗口中导航离开页面,而不仅仅是在窗口关闭时,你应该检查弹出窗口是否实际关闭了 someFunctionToCallWhenPopUpCloses

Since the unload event will fire whenever the user navigates away from the page in the pop-up and not just when the window is closed, you should check that the pop-up has actually closed in someFunctionToCallWhenPopUpCloses:

var popUp = window.open("popup.html", "thePopUp", "");
function someFunctionToCallWhenPopUpCloses() {
    window.setTimeout(function() {
        if (popUp.closed) {
            alert("Pop-up definitely closed");
        }
    }, 1);
}

如果您无法控制弹出窗口的内容,或者,如果您的某个目标浏览器不支持卸载事件,您将在主窗口中简化为某种轮询解决方案。调整间隔以适应。

If you don't have control over the contents of the pop-up, or if one of your target browsers does not support the unload event, you're reduced to some kind of polling solution in the main window. Adjust interval to suit.

var win = window.open("popup.html", "thePopUp", "");
var pollTimer = window.setInterval(function() {
    if (win.closed !== false) { // !== is required for compatibility with Opera
        window.clearInterval(pollTimer);
        someFunctionToCallWhenPopUpCloses();
    }
}, 200);