小编dhr*_*att的帖子

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)

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

reactjs

31
推荐指数
5
解决办法
3万
查看次数

ReactJs浏览器“后退”按钮

我正在使用Reactjs。我想警告用户单击后退按钮。我所做的是

handleWindowClose = (ev) => {
  ev.preventDefault();
  return ev.returnValue = 'Leaving this page will loose data';
}

componentDidMount = () => {
    window.addEventListener('beforeunload',this.handleWindowClose);     
}

componentWillUnmount = () => {
    window.removeEventListener('beforeunload',this.handleWindowClose);
}
Run Code Online (Sandbox Code Playgroud)

但是,这与单击后退按钮不起作用。所以我尝试这样做

handleWindowClose = (ev) => {
        ev.preventDefault();
        return ev.returnValue = 'Leaving this page will loose data';        
}

onBackButtonEvent = (e) => {
    e.preventDefault();
    if(confirm("Do you want to loose this data")){
    window.history.go(0);
    }else {
    window.history.forward();
  }
}

componentDidMount = () => {
    window.addEventListener('beforeunload',this.handleWindowClose);     
    window.addEventListener('popstate',this.onBackButtonEvent);
}

componentWillUnmount = () => { …
Run Code Online (Sandbox Code Playgroud)

reactjs

7
推荐指数
2
解决办法
1万
查看次数

标签 统计

reactjs ×2