如何在React中检测页面刷新

发布于 2025-01-31 14:36:39 字数 238 浏览 4 评论 0原文

我正在使用此代码,

useEffect(() => {
window.addEventListener("beforeunload",() => {
localStorage.removeItem("token")
})
})

但是我的要求是只有在关闭所有选项卡或浏览器本身时才清除此令牌该页面被刷新,仅在关闭选项卡或浏览器时才执行。

任何帮助都将是高度明显的,谢谢!!!

I am using this code,

useEffect(() => {
window.addEventListener("beforeunload",() => {
localStorage.removeItem("token")
})
})

but my requirement is to clear this token only when all tabs get closed or the browser itself gets closed, but this event is occurring for even page refresh, so is there any possible way to block this part of code when the page gets refreshed and only execute when tabs or browser gets closed.

Any help would be highly appreciable, thanks in advance!!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲娇萝莉攻 2025-02-07 14:36:39

您可以尝试使用 sessionstorage 。关闭选项卡之后,它将自动清除令牌,但仅适用于一个选项卡。

You can try using sessionStorage. It will automatically clear token after closing the tab but it works only for one tab.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文