如何检测用户是否在 Angularjs 中单击浏览器后退按钮

How to detect if a user clicks browser back button in Angularjs

我有一个包含一些数据的类似表单的页面。并希望在用户单击浏览器后退按钮时显示 popup/alert,询问 "if they want to go back or stay on the same page"。我正在使用 angular-ui-路由器的 $stateProvider 并且只想将其绑定到一个 state/view.

这是我之前对其他问题的回答,不过对你有帮助应该不错

您可以使用 angular $routeChangeStart

$routeChangeStart

在路线改变之前广播。此时,路由服务开始解析发生路由更改所需的所有依赖项。通常这涉及获取视图模板以及解析路由 属性 中定义的任何依赖项。一旦所有依赖项都得到解决,$routeChangeSuccess 就会被触发。

可以通过调用事件的 preventDefault 方法来阻止路由更改(以及触发它的 $location 更改)。有关事件对象的更多详细信息,请参阅 $rootScope.Scope


所以请尝试下面的代码。

  $scope.$on('$routeChangeStart', function (scope, next, current) {
        if (next.$$route.controller != "Your Controller Name") {
            // Show here for your model, and do what you need**
            $("#yourModel").show();
        }
    });

更新:

您需要在模型弹出窗口中编写您的功能工作。喜欢

放置一些link按钮
  • 您确定要转到上一页吗?
  • 你想停留在当前页面吗?
  • 您要注销吗?等等

然后为转到上一页添加 ng-click 事件,使用 return false 保持当前页面等

这是我的解决方案

app.run(function($rootScope, $location) {
    $rootScope.$on('$locationChangeSuccess', function() {
        if($rootScope.previousLocation == $location.path()) {
            console.log("Back Button Pressed");
        }
        $rootScope.previousLocation = $rootScope.actualLocation;
        $rootScope.actualLocation = $location.path();
    });
});

您最好将 $stateChangeStart 事件与 angular ui 路由器一起使用。 $routeChangeStart 会出现问题,因为 $routeChangeStart 事件将在 url 更改时触发。

例如:

您有 4 个状态,每个状态有 2 个子状态,每个 sub/state 或状态不与 url 关联。在这种情况下,监听 $routeChangeStart 可能不起作用。

在要提示用户确认重定向的 controller/view 处执行此操作。

当您当前范围(即您所在的view/controller)中的状态发生变化时将调用此函数

$scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
    //Open the modal
    $('my-modal').show();
});

类似于 syraz37 的答案,但对于新的 $transition API:

angular
    .module('app')
    .run(function($rootScope, $transitions) {

        // Track "previous state" to be used elsewhere to determine if the user
        // goes "back".
        $transitions.onStart({}, (transition) => {
            if ($rootScope._previousState === transition.$to().name) {
                $rootScope._isPreviousState = true;
            } else {
                $rootScope._isPreviousState = false;
            }
            $rootScope._previousState = transition.$from().name;
        });

    });

然后在任何控制器中,您可以检查它是否被加载为 "previous state":

if ($rootScope._isPreviousState) {
    // ...reload some aspect of the controller state...
}

这属于上面 ninjaPixel 指出的警告,您可以先进入状态 A,然后进入状态 B,然后再次进入状态 A(全部向前),它会认为用户已经离开 "back",但对于我们的需要,这是可行的。