【发布时间】:2021-11-30 09:02:36
【问题描述】:
当我的 react 应用程序关闭时,我需要运行代码来清除本地存储中的数据。我已经尝试过我在类似问题中看到的内容,但我的 onbeforeunload 代码似乎永远不会运行(如果这很重要,我在 chrome 上)。
App.tsx 代码:
handleWindowClose() // never gets run
{
var value = window.localStorage.getItem('tabs')
if (value !== null) {
var loc = +value // convert to num
window.localStorage.setItem('tabs', (loc - 1).toString());
}
}
componentWillMount()
{
var handle = this.handleWindowClose
window.addEventListener('onbeforeunload', (ev: any) => {
// breakpoints in here do not trigger, alert does not show up
// adding a long loop to delay does not actually delay the close operation
ev.preventDefault();
alert('you are closing')
handle()
});
}
有人知道为什么我的 onbeforeunload 事件永远不会触发吗?
更新 我尝试过使用 onbeforeunload、onpagehide 和 onunload 事件。它们似乎都没有在 chrome 中运行。
【问题讨论】:
标签: node.js reactjs typescript google-chrome onbeforeunload