是否可以使用javascript打开弹出窗口,然后检测用户何时关闭它? [英] is it possible to open a popup with javascript and then detect when the user closes it?

查看:151
本文介绍了是否可以使用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);

这篇关于是否可以使用javascript打开弹出窗口,然后检测用户何时关闭它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆