Reactjs浏览器选项卡关闭事件

dhr*_*att 31 reactjs

嗨,我想知道如何在浏览器选项卡上提示消息关闭.我正在使用Reactjs.

handleWindowClose(){
    alert("Alerted Browser Close");
},
componentDidMount: function() {
    window.addEventListener('onbeforeunload', this.handleWindowClose);
},

componentWillUnmount: function() {
    window.removeEventListener('onbeforeunload', this.handleWindowClose);
}
Run Code Online (Sandbox Code Playgroud)

这是我尝试添加到我的反应组件.请指导我如何进一步.

Ami*_*mid 41

您已经完成了与事件名称的正确分离以及在该特定事件中将阻止警报的事实.

你可以这样显示消息:

window.addEventListener("beforeunload", (ev) => 
{  
    ev.preventDefault();
    return ev.returnValue = 'Are you sure you want to close?';
});
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

  • 较新版本的Chrome和其他浏览器不再允许您自定义此字符串.https://www.chromestatus.com/feature/5349061406228480 (7认同)
  • 您可以在本地字段中存储处理程序:`this.handler =(ev)=> ...`在构造函数初始化期间.然后在`addEventListener("beforeunload",this.handler)`和`removeEventListener("beforeunload",this.handler)`方法中相应地使用该字段. (3认同)

Han*_*zky 25

在用户决定关闭选项卡后,我需要触发逻辑。这是我的解决方案(针对功能性反应组件和 TypeScript):

useEffect(() => {
    window.addEventListener('beforeunload', alertUser)
    window.addEventListener('unload', handleTabClosing)
    return () => {
        window.removeEventListener('beforeunload', alertUser)
        window.removeEventListener('unload', handleTabClosing)
    }
})

const handleTabClosing = () => {
    removePlayerFromGame()
}

const alertUser = (event:any) => {
    event.preventDefault()
    event.returnValue = ''
}
Run Code Online (Sandbox Code Playgroud)

AlertUser使用默认浏览器对话框警告用户。 当用户选择关闭选项卡时,将触发handleTabClos​​ing 。

我从 Mike Pottebaum 的这篇博客文章中得出了我的解决方案


Dre*_*ese 8

如果您想在离开页面之前显示某种确认信息,请遵循beforeunload 事件指南:

根据规范,要显示确认对话框,事件处理程序应该对事件调用 PreventDefault()。

但请注意,并非所有浏览器都支持此方法,有些浏览器需要事件处理程序来实现以下两种旧方法之一:

  • 将字符串分配给事件的 returnValue 属性
  • 从事件处理程序返回一个字符串。

为了对抗不需要的弹出窗口,beforeunload除非已与页面交互,否则浏览器可能不会显示在事件处理程序中创建的提示,或者甚至可能根本不显示它们。

HTML 规范规定,在此事件期间对window.alert()window.confirm()和方法的调用可能会被忽略。有关详细信息,window.prompt()请参阅HTML 规范。

这应该涵盖大多数情况。使用挂载useEffect定义回调,添加事件监听器,并返回清理函数以删除监听器。

useEffect(() => {
  const unloadCallback = (event) => {
    event.preventDefault();
    event.returnValue = "";
    return "";
  };

  window.addEventListener("beforeunload", unloadCallback);
  return () => window.removeEventListener("beforeunload", unloadCallback);
}, []);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 在此输入图像描述

编辑 put-a-warning-if-page-refresh-in-reactjs


Jyo*_*han 7

现在可以使用钩子来实现相同的功能。例如

import { useBeforeunload } from 'react-beforeunload';
Run Code Online (Sandbox Code Playgroud)

然后在您的组件中使用:

 useBeforeunload(() => "Are you sure to close this tab?");
Run Code Online (Sandbox Code Playgroud)

虽然我们返回自定义字符串,但它会在此处显示浏览器的默认消息。


Art*_*yan 5

Amid的回答对我来说效果很好。

我的使用方式:

class MyComponent extends Component {
    // Things to do before unloading/closing the tab
    doSomethingBeforeUnload = () => {
        // Do something
    }

    // Setup the `beforeunload` event listener
    setupBeforeUnloadListener = () => {
        window.addEventListener("beforeunload", (ev) => {
            ev.preventDefault();
            return this.doSomethingBeforeUnload();
        });
    };

    componentDidMount() {
        // Activate the event listener
        this.setupBeforeUnloadListener();
    }

    // Render method.
    render() {
        return (
            <div>My component</div>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)