如何获取路线历史中当前URL的第一个URL不同点?

How to get the first URL different of the current URL in route history?

我在我的应用程序上使用了一个重定向到上一页的按钮。

看起来像这样:

<button ng-click="goBack()">Go back</button>

$scope.goBack = function() {
    $window.history.back();        
}

我希望此按钮转到与当前 URL 不同的上一个 URL ,而不仅仅是上一个页面(可能需要与当前相同 URL)。


示例:

  • 如果我去 /home,然后 /products,然后 /products,然后再 /products
  • 那我要恢复/home

有没有办法让第一个 URL 与当前 URL 不同?

1.

您可以使用 window.history.back(); 让浏览器返回上一页,但您无法访问 URL。如果可能的话,您可以在每个用户首​​次进入您的网站时轻松监视他们。

但如果它在同一个域中,您可以使用 document.referrer 访问以前的 URL。

2.

要访问浏览器历史记录,有 History Object

您可以通过 window.history 访问它,它将 return 一组历史项目。使用该对象,您可以比较当前位置 window.location.href 和之前 returned 对象

如果您只想在 angular 应用程序中这样做,这并不难。 例如,您必须使用 stateChangeSuccess 事件监视状态变化,并在状态 URL 相同时进行计数。当您想返回上一个不同的 URL 时,您可以使用 window.history.go(-X),其中 X 是您计算的数字。

一个例子(不完美,只是一个概念,为了简单起见,一切都在 $rootScope 上)。

angular.module('YourModule').run(function() {
    var lastUrl, counter;
    $rootScope.$on('$stateChangeSuccess', function(event, toState) {
        if (lastUrl != toState.url) {
            counter = 1;
            lastUrl = toState.url;
        } else {
            counter++;
        }
    });
    $rootScope.goBack = function() {
        $window.history.go(-1 * counter);
    };
});

出于安全原因,您将无法访问本机历史记录网址。但是您可以使用 angular 来保存您自己的记录,例如myHistoryService:

app.run(function($rootScope, $location, myHistoryService) {
    $rootScope.$on('$routeChangeStart', function(ev, next) {
        var path = $location.path();
        myHistoryService.push(path);
    });
});

myHistoryService 中,您可以直接推送到数组,或使用您喜欢的任何逻辑。

这假定您只需要在您自己的域内工作的历史记录。