【发布时间】:2021-06-17 03:32:08
【问题描述】:
我有一个钩子,当有人离开当前页面或离开网站时执行传递给它的函数
const useOnPageLeave = (handler) => {
useEffect(() => {
window.onbeforeunload = undefined;
window.addEventListener('beforeunload', (event) => { //When they leave the site
event.preventDefault(); // Cancel the event as stated by the standard.
handler();
});
return () => {
handler(); //When they visit another local link
document.removeEventListener('beforeunload', handler);
};
}, []);
};
当使用 Firefox 或 Safari 时,会出现此警告消息(仅当他们离开网站时,而不是当他们访问本地链接时),我不希望显示此警告消息
如果我删除event.preventDefault()这一行,那么handler函数就不会被执行,我需要handler事件被执行
【问题讨论】:
-
你在使用 React-router 进行本地页面导航吗?
-
@ShubhamKhatri 是的,这发生在页面离开时
标签: reactjs react-hooks addeventlistener use-effect onbeforeunload