英文:
How to detec if browser was reload - React/Typescript
问题
Sure, here's the translated code part:
你能帮忙吗?
我正在尝试一种方法来检测浏览器是否已重新加载,关于这个问题的大多数答案都类似于:
```javascript
const typeOfNavigation = (performance.getEntriesByType("navigation")[0] as PerformanceNavigationTiming).type;
if (typeOfNavigation === 'reload') {
localStorage.removeItem('products-list');
}
问题是上面的代码自用户刷新浏览器后,类型始终保持为“reload”,并且该API没有用于刷新或清除“navigation”的方法,理想情况下,它应该返回到其原始状态“navigate”,但这并不发生,所以我需要一些动态的东西。
我发现上面的代码对我来说很完美,但它已经被弃用:
if (window.event?.type === "loadend") {
localStorage.removeItem('products-list');
}
简而言之,有人能帮我解决这个问题吗?任何想法都受欢迎,我需要知道每次用户通过F5刷新浏览器或单击按钮时的情况。
注:我正在使用React/TypeScript
提前感谢您
<details>
<summary>英文:</summary>
Can you help, please?
I'm trying a way for detec if browser was reload and the most answers about this say something like
const typeOfNavigation = (performance.getEntriesByType("navigation")[0] as PerformanceNavigationTiming).type
if(typeOfNavigation === 'reload'){
localStorage.removeItem('products-list');
}
**The problem** is that the code above since user make refresh the browser , the type is **always** stay like **"reload"** and that Api does not exist method for refresh or clear to "navigation", Ideally, it would return to its original state. "navigate", but that doesn't happen, So I need that something dinamic.
I found the code above, work perfect for me , but is **deprecated**
if(window.event?.type === "loadend"){
localStorage.removeItem('products-list')
}
In short, Can someone help me about that question , any idea is welcome, I need know **each time** when the user make refresh the browser through f5 or clicking the button,
Obs: I'm using React/Typescript
Thanks in advance
</details>
# 答案1
**得分**: 0
你可以监听 `beforeunload` 事件。此事件在用户导航离开页面、关闭窗口/标签或重新加载页面时触发。[文档链接][1]。
[1]: https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
<details>
<summary>英文:</summary>
You can listen for the `beforeunload` event. This event is fired when the user navigates away from the page, closes the window/tab, or reloads the page. [Documentation][1].
[1]: https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论