我们如何使用JavaScript限制/限制用户重新加载页面或浏览器向后或向前浏览 [英] How can we constraint/restrict the user from page reloading or browser back or forward using javascript

查看:108
本文介绍了我们如何使用JavaScript限制/限制用户重新加载页面或浏览器向后或向前浏览的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有注册页面,当用户输入一些详细信息并单击刷新或后退/前进按钮时,我们必须以模态弹出窗口提醒用户,例如: 您确定要离开页面". 我尝试了一些,但是警报显示在每个页面中.我只需要在注册页面上,而无需刷新其他页面上的警报消息.

I have registration page, when user enters some details and click on refresh or back/forward button.Then we have to alert user with modal pop up like: "Are you sure want to leave the page". I've tried some but the alerts are showing in every page.I only need on registration page and no need to refresh alert messages in other pages.

我已将此代码添加到注册页面

I have added to this code to registration page

componentWillMount()
{
var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload';
    myEvent(chkevent, function(e) { 
    var confirmationMessage = 'Are you sure to leave the    page?'; 
(e || window.event).returnValue = confirmationMessage;
return confirmationMessage;
});
}

如何防止除注册页面之外的其他页面中出现刷新警报消息,以及如何在刷新/后退/转发按钮中添加自定义警报消息.

How can i prevent the refresh alert message in other pages except registration page and how to add custom alert message in refresh/back/forward buttons.

推荐答案

您可以在react-router-dom中使用提示,您可以在react-router-dom文档中找到

You can use prompt in react-router-dom, You may find at react-router-dom document https://reacttraining.com/react-router/core/api/Prompt

该对象具有路径名属性,该属性是下一个路径,通过检查它可以确定该路径是否安全.这就是我在说的:

The object has a pathname attribute which is the next path by checking it you can figure out if the path is safe. Here is what I'm talking about:

<Prompt message={(params) => 
        params.pathname == '/about' ? "Move away?" : true } />

,并同时引用此 https://codepen.io/anon/pen/XReabZ

这篇关于我们如何使用JavaScript限制/限制用户重新加载页面或浏览器向后或向前浏览的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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