我有以下函数可以在弹出窗口中打开网址:
function windowPopup(url, width, height) {
// center
var left = (screen.width / 2) - (width / 2),
top = (screen.height / 2) - (height / 2);
handle=window.open(
url,
"",
"menubar=no,toolbar=no,resizable=yes,scrollbars=yes,width=" +
width + ",height=" + height + ",top=" + top + ",left=" + left
);
}
我希望能够检测到此窗口何时关闭并执行一些代码。如何使用函数中的句柄来绑定卸载或关闭?
我想知道有人分享到 Twitter 后窗口是否关闭:
windowPopup("https://twitter.com/intent/tweet/?text=Check%20out%20this%20website!&url=https%3A%2F%2Fgoogle.com%2F", 500, 300);
我更新了拉尔的建议:
function windowPopup(url, width, height) {
// center
var left = (screen.width / 2) - (width / 2),
top = (screen.height / 2) - (height / 2);
handle=window.open(
url,
"",
"menubar=no,toolbar=no,resizable=yes,scrollbars=yes,width=" +
width + ",height=" + height + ",top=" + top + ",left=" + left
);
handle.onbeforeunload = function() {
alert('Bye!');
}
}
虽然这对某些弹出窗口有效,但当我关闭 Twitter 窗口时却不起作用......
您正在寻找
beforeunload
活动:
handle.onbeforeunload = function() {
console.log('Bye!');
}
window.closed
。
原因有两个:您打开的窗口可能不是您自己的域,CORS 将阻止您注册事件,并且
beforeunload
可能会在子窗口自己的侦听器中被阻止,但您的代码仍然会认为它确实关闭了。
const polling = setInterval(() => {
if (handle.closed) {
clearInterval(polling);
alert('Bye!');
}
}, 500);