React JS实现页面关闭事件处理(排除页面刷新场景)
解决页面刷新误触发登出的问题
你当前的代码在页面刷新时也会弹出提示并执行会话清理,这是因为浏览器的beforeunload和unload事件在刷新页面、关闭标签页/浏览器、跳转页面时都会触发。要实现仅在关闭标签页/浏览器时触发提示和登出清理,需要区分刷新和关闭操作。
解决方案思路
利用「页面刷新会触发load事件,而关闭标签页/浏览器不会」的特性,通过定时器延迟执行清理逻辑:在unload事件中设置定时器,若页面是刷新操作,后续的load事件会取消这个定时器,避免执行清理;若为关闭操作,定时器会正常执行清理代码。
修改后的代码实现
useEffect(() => { let unloadTimer: NodeJS.Timeout | null = null; const handleBeforeUnload = (event: any) => { const customMessage = '你正试图未登出就离开客服界面,可能会导致数据丢失。确定要退出吗?'; event.preventDefault(); event.returnValue = customMessage; // 兼容部分浏览器,返回提示文本确保弹窗正常显示 return customMessage; }; const handleUnload = () => { // 设置定时器,延迟执行会话清理 unloadTimer = setTimeout(() => { reduxDispatch(onSelectCampaign("")); RemoveCookiesData(); clearAllData(reduxDispatch); }, 500); }; const handleLoad = () => { // 页面刷新后触发load事件,取消定时器阻止清理 if (unloadTimer) { clearTimeout(unloadTimer); unloadTimer = null; } }; window.addEventListener('beforeunload', handleBeforeUnload); window.addEventListener('unload', handleUnload); window.addEventListener('load', handleLoad); return () => { // 组件卸载时移除所有事件监听并清理定时器 window.removeEventListener('beforeunload', handleBeforeUnload); window.removeEventListener('unload', handleUnload); window.removeEventListener('load', handleLoad); if (unloadTimer) clearTimeout(unloadTimer); }; }, []);
额外需求实现:返回页面重定向登录页
在组件初始化时检查登录状态(比如校验登录Cookie、Redux中的用户信息),若未登录直接重定向到登录页:
useEffect(() => { // 替换为你的登录状态判断逻辑 const isLoggedIn = !!document.cookie.includes('auth_token') || !!reduxState.userInfo; if (!isLoggedIn) { window.location.href = '/login'; } }, []);
内容的提问来源于stack exchange,提问作者anjali dixit
相关产品推荐
相关产品推荐

