使用 Javascript 或 AngularJS 控制或禁用浏览器后退按钮 [英] Control or Disable Browser Back Button with Javascript or AngularJS

查看:39
本文介绍了使用 Javascript 或 AngularJS 控制或禁用浏览器后退按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Control or Disable Browser Back Button with Javascript or AngularJS

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

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

推荐答案

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

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

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

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

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:

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

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

// *** 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 控制器中放置以下事件监听器:

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

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

希望能帮到你.

最好的问候

威尔

这篇关于使用 Javascript 或 AngularJS 控制或禁用浏览器后退按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆