Javascript 浏览器后退按钮处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14543245/
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 17:08:32  来源:igfitidea点击:

Browser back button handling

javascriptjqueryhtmlbrowser

提问by Ramesh Paul

I am trying to handle browser back button event but i could not find any solution.

我正在尝试处理浏览器后退按钮事件,但找不到任何解决方案。

I want to ask user if he clicks on browser back button using "confirm box" if he chooses ok i have to allow back button action else i have to stop back button action.

我想问用户他是否使用“确认框”点击浏览器后退按钮,如果他选择确定,我必须允许后退按钮动作,否则我必须停止后退按钮动作。

Can any one help me in implementing this.

任何人都可以帮助我实现这一点。

回答by Sampath

Warn/confirm User if Back button is Pressed is as below.

如果按下后退按钮,警告/确认用户如下。

window.onbeforeunload = function() { return "Your work will be lost."; };

You can get more information using below mentioned links.

您可以使用下面提到的链接获取更多信息。

Disable Back Button in Browser using JavaScript

使用 JavaScript 在浏览器中禁用后退按钮

I hope this will help to you.

我希望这会对你有所帮助。

回答by Szorstki

You can also add hash when page is loading:

您还可以在页面加载时添加哈希:

location.hash = "noBack";

Then just handle location hash change to add another hash:

然后只需处理位置哈希更改以添加另一个哈希:

$(window).on('hashchange', function() {
    location.hash = "noBack";
});

That makes hash always present and back button tries to remove hash at first.Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.

这使得哈希始终存在,而后退按钮首先尝试删除哈希。然后通过“hashchange”处理程序再次添加哈希 - 因此页面实际上永远无法更改为前一个。