【问题标题】:Control or Disable Browser Back Button with Javascript or AngularJS [closed]使用 Javascript 或 AngularJS 控制或禁用浏览器后退按钮 [关闭]
【发布时间】:2015-06-03 10:12:41
【问题描述】:

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

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

【问题讨论】:

标签: javascript angularjs button browser back


【解决方案1】:

如果您只是使用 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 控制器中放入以下事件监听器:

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

希望对你有帮助。

最好的问候

瓦尔

【讨论】:

  • 为什么不使用 $location.replace() ?
  • @Wael,上面的代码用于禁用后退按钮。但它甚至在登录页面中禁用 ng-href
  • @Hema 不幸的是,它禁用了所有角度导航...
  • @JosefE。是的,我注意到了。我以另一种方式克服了这一点。
猜你喜欢
  • 1970-01-01
  • 2014-04-17
  • 2010-09-10
  • 2014-07-07
  • 2011-08-06
  • 1970-01-01
  • 2010-10-31
相关资源
最近更新 更多