在弹出窗口关闭之前(使用window.open
),我需要执行一些操作。
类似下面这样的代码会很好:
var new_window = window.open('some url')
new_window.onBeforeUnload = function(){ my code}
我该如何实现这个目标?
在弹出窗口关闭之前(使用window.open
),我需要执行一些操作。
类似下面这样的代码会很好:
var new_window = window.open('some url')
new_window.onBeforeUnload = function(){ my code}
我该如何实现这个目标?
虽然已经有一个正确的答案适用于同源环境,但我找到了一个可以解决跨域弹窗的方法:
var win = window.open('http://www.google.com');
var timer = setInterval(function() {
if(win.closed) {
clearInterval(timer);
alert('closed');
}
}, 1000);
对于那些考虑使用它的人来说。
即使Facebook在其Javascript SDK中也使用这个“技巧”。
您可以通过查看他们的代码来验证这一点。只需在https://connect.facebook.net/en_US/sdk.js中搜索.closed
即可。
只要弹出窗口URL与父页面在相同的域名下,并将事件改为全部小写,您的示例就能正常运行:
var new_window = window.open('some url')
new_window.onbeforeunload = function(){ /* my code */ }
onbeforeunload
而非onBeforeUnload
。JS区分大小写。你可能不想覆盖 onbeforeunload
的值,因为这会干扰弹出窗口的处理程序,如果它也使用了那个钩子。
改用 addEventListener('beforeunload', ...)
。
const wnd = window.open(theUrl)
wnd.addEventListener('beforeunload', () => {
// do stuff
})
unload
和pageHide
。请阅读文档以确定哪个事件最适合您的实现。onbeforeunload
事件应该在弹出窗口加载后添加。例如,您可以在其加载事件的末尾添加它,如下所示:
const new_window = window.open('some url')
new_window.onload = function(){
/* my code */
this.onbeforeunload = function(){ /* my code */ }
}
import { useEffect, useRef } from "react";
const usePopupWindow = ({
url,
onPopupClose,
popupProperties = "width=200,height=200",
}) => {
const timer = useRef();
const handleWindowPopup = () => {
const windowPopup = window.open(url, "popup", popupProperties);
timer.current = setInterval(() => {
if (windowPopup.closed) {
clearInterval(timer.current);
onPopupClose();
}
}, 1000);
};
useEffect(() => {
return () => clearInterval(timer.current);
}, []);
return { handleWindowPopup };
};
export default usePopupWindow;
我为React使用场景创建了这个钩子
var new_window = window.open('some_url')
你也可以检查new_window.window
是否为null
。但是你需要使用setTimeout
或setInterval
函数手动检查。
顺便说一下,当你不在同一个域时,这是唯一的检查方式。