使用 Javascript 或 AngularJS 控制或禁用浏览器后退按钮

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

Control or Disable Browser Back Button with Javascript or AngularJS

javascriptangularjsbuttonbrowserback

提问by Wael

Control or Disable Browser Back Button with Javascript or AngularJS

使用 Javascript 或 AngularJS 控制或禁用浏览器后退按钮

Here i am not asking a question but i want to show a solution to how you can disable and control Browser's Back Button if you are using AngularJS or even with Javascript

在这里,我不是在问问题,但我想展示一个解决方案,如果您使用的是 AngularJS 甚至 Javascript,您可以如何禁用和控制浏览器的后退按钮

回答by Wael

If you are just using Javascript you can check how you can disable Back Button from this link:

如果您只是使用 Javascript,您可以通过以下链接检查如何禁用后退按钮:

http://jordanhollinger.com/2012/06/08/disable-the-back-button-using-html5/

http://jordanhollinger.com/2012/06/08/disable-the-back-button-using-html5/

But this code above will not work well with AngularJS because AngularJS uses URL_Hash # in the background, so here i will show how you can turn around:

但是上面的这段代码不适用于 AngularJS,因为 AngularJS 在后台使用 URL_Hash #,所以在这里我将展示如何扭转:

In your main Javascript Code (Not inside AngularJS Code or controler), put the following code:

在您的主要 Javascript 代码(不在 AngularJS 代码或控制器内)中,输入以下代码:

// *** Author: Wael Sidawi
// ****  Deactive Back Button **** 
var history_api = typeof history.pushState !== 'undefined';
// history.pushState must be called out side of AngularJS Code
if ( history_api ) history.pushState(null, '', '#StayHere');  // After the # you should write something, do not leave it empty

And now inside your AngularJS Controler put the following event listner:

现在在你的 AngularJS 控制器中放置以下事件监听器:

/**
 * Event-Listner for Back-Button
 */
$scope.$on('$locationChangeStart', function(event, next, current){            
    // Here you can take the control and call your own functions:
    alert('Sorry ! Back Button is disabled');
    // Prevent the browser default action (Going back):
    event.preventDefault();            
});

I hope it could help you.

我希望它能帮助你。

Best Regards

此致

Wael

威尔