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

Wae*_*ael 12 javascript browser button back angularjs

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

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

Wae*_*ael 14

如果您只是使用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
Run Code Online (Sandbox Code Playgroud)

现在你的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();            
});
Run Code Online (Sandbox Code Playgroud)

我希望它可以帮助你.

最好的祝福

瓦埃勒