我希望你做得很好!
我正试图在我的项目中捕捉窗口关闭、选项卡关闭或刷新事件,我尝试了所有可能的解决方案,但都没有成功。
我尝试使用:
useEffect(() => {
return () => {
window.alert("Alert");
};
});
我试过:
useEffect(() => {
window.onbeforeunload = () => {
window.alert("alert");
};
return () => {
window.onbeforeunload = null;
};
});
这似乎只有当我的窗口在后台显示一段时间时才会触发。
我试过:
window.addEventListener("onbeforeunload", () => {
window.alert("alert");
});
但还没能捕捉到。
每当用户关闭窗口或选项卡或刷新时,我将使用此功能将数据发送到特定的API(如果可能的话,还可能在页面上关闭PC(。但所有这些方法对我都不起作用
还有其他办法吗?或者他们不工作的原因是什么?
感谢您抽出时间!
您可能需要调用preventDefault
,我认为该事件被称为beforeunload
,请尝试:
window.addEventListener("beforeunload", ev => {
ev.preventDefault()
return (ev.returnValue = "Are you sure you want to close?")
})
在注册事件侦听器时,应该使用useEffect
执行此操作,以便正确地删除侦听器。
useEffect(() => {
const onUnload = (e: any) => {
e.preventDefault()
return (e.returnValue = "Are you sure you want to close?")
}
window.addEventListener("beforeunload", onUnload)
return () => window.removeEventListener("beforeunload", onUnload)
}, [])
关于beforeunload
:的一些须知
它不调用诸如alert
、prompt
或confirm
之类的阻塞函数。从用户的角度来看,这是显而易见的。
只有当用户与该网站进行了任何交互时,它才会被触发。如果没有任何交互(甚至在任何地方单击一次(,事件beforeunload
都不会被触发。
不可能捕捉到选项卡/浏览器关闭,即使是这样,也不可靠,因为用户可能会强制关闭浏览器或终止进程等。
所以我找到的最好的选择是,我在这里包装了一个NPM包:https://www.npmjs.com/package/@车库熊猫/卸载前使用
看看,让我知道它是否适合你。
这就是你使用它的方式:
const setEnabledBeforeUnload = useBeforeUnload({
initEnable: false, // do you need to be enabled by default
onRefresh: () => {
// the page has been refreshed (the user has clicked Reload)
},
onCancel: () => {
// the user has clicked Cancel
}
});
知道用户是否已离开您的页面的唯一可能(也是正确的方法(是在用户登录您的页面时实际捕捉事件(例如会话存储为空(。