Reactjs 浏览器选项卡关闭事件 [英] Reactjs Browser Tab Close Event

查看:109
本文介绍了Reactjs 浏览器选项卡关闭事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi I want to know how to prompt a message on browser tab close. I am using Reactjs.

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

componentWillUnmount: function() {
    window.removeEventListener('onbeforeunload', this.handleWindowClose);
}

这是我尝试添加到我的 React 组件中的内容.请指导我如何进一步操作.

this is what I have tried adding to my react component.Please guide me on how to proceed further.

推荐答案

除了事件名称以及警报将在该特定事件中被阻止的事实之外,您所做的都是正确的.

What you did is correct apart from the event name and the fact that alert will be blocked in that particular event.

您可以显示如下消息:

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

希望这会有所帮助.

这篇关于Reactjs 浏览器选项卡关闭事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆