如何检测浏览器是否已重新加载 – React/Typescript

huangapple go评论142阅读模式
英文:

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&#39;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 **&quot;reload&quot;** and that Api does not exist method for refresh or clear to &quot;navigation&quot;, Ideally, it would return to its original state. &quot;navigate&quot;, but that doesn&#39;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&#39;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>



huangapple
  • 本文由 发表于 2023年3月9日 20:00:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75684316.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定