使用Javascript或AngularJS控制或禁用浏览器返回按钮

Control or Disable Browser Back Button with Javascript or AngularJS

本文关键字:浏览器 返回 按钮 控制 Javascript AngularJS 使用      更新时间:2023-09-26

使用Javascript或AngularJS 控制或禁用浏览器返回按钮

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

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

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

但是上面的代码不能很好地与AngularJS一起使用,因为AngularJS在后台使用URL_Hash#,所以在这里我将展示如何扭转局面:

在您的主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

现在,在您的AngularJS Controler中放入以下事件列表:

/**
 * 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();            
});

我希望它能帮助你。

致以最诚挚的问候

Wael