防止用户使用 jquery 或 javascript 重新加载页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11094887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:25:48  来源:igfitidea点击:

Prevent User to reload page using jquery or javascript

javascriptjqueryhtmlrefreshreload

提问by Georgian Citizen

Possible Duplicate:
Prevent any form of page refresh using jQuery/Javascript

可能的重复:
使用 jQuery/Javascript 防止任何形式的页面刷新

how can i prevent user to reload (refresh) html page using javascript or jquery.

如何防止用户使用 javascript 或 jquery 重新加载(刷新)html 页面。

after loading the page for the first time, i want to prevent user reload the page either by press F5 or refresh from browser or by any way.

第一次加载页面后,我想阻止用户通过按 F5 或从浏览器刷新或以任何方式重新加载页面。

Can i do that?

Can i do that?

Note:i try window.onbeforeunload, but i didn't know how to stop window.onload event from it.

注意:我尝试过window.onbeforeunload,但我不知道如何从中停止 window.onload 事件。

Any help?

有什么帮助吗?

回答by gopi1410

It is not possibleto stop the user from page reload/page close if the user wants it. Two methods which you can use are as follows:

如果用户需要,则无法阻止用户重新加载/关闭页面。您可以使用的两种方法如下:

You can ask for a confirmation like this:

您可以要求这样的确认:

<script>
window.onbeforeunload = function (e) {
e = e || window.event;

// For IE and Firefox prior to version 4
if (e) {
    e.returnValue = 'Sure?';
}

// For Safari
return 'Sure?';
};
</script>

Here is the fiddle for above: http://jsfiddle.net/gopi1410/NujmL/

这是上面的小提琴:http: //jsfiddle.net/gopi1410/NujmL/

You can preventDefault on pressing of F5 key using:

您可以使用以下方法在按下 F5 键时防止默认:

document.onkeydown = function(event) {
  if(window.event){
        event.preventDefault();
  }
}

回答by Quentin

No, you can't. If a user wants to reload a page you cannot stop them.

不,你不能。如果用户想要重新加载页面,您无法阻止他们。