【问题标题】:React - onbeforeunload event never triggeredReact - onbeforeunload 事件从未触发
【发布时间】: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


    【解决方案1】:

    从“onbeforeunload”中删除“on”,它应该可以工作。以防万一,我创建了a quick playground to demonstrate how it should be implemented

    基本上,我设置了一个效果挂钩来每秒读取一次本地存储,另一个效果挂钩在 2.5 秒后延迟写入本地存储,另一个效果实现“前卸载”。如果您将其注释掉,您将看到该消息在未加载的情况下显示(因为它没有被删除)。

    'beforeunload'的实现:

    React.useEffect(() => {
      const onBeforeUnload = (ev) => {
        localStorage.removeItem("message");
      };
      window.addEventListener("beforeunload", onBeforeUnload);
      return () => window.removeEventListener("beforeunload", onBeforeUnload);
    }, []);
    

    【讨论】:

      猜你喜欢
      • 2020-05-29
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 2015-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多