我想用JavaScript看是否有历史记录,后退按钮在浏览器上是否可用。


当前回答

我正在使用Angular,我需要检查是否有历史记录,触发location.back(),否则重定向到父路由。

来自https://stackoverflow.com/a/69572533/18856708的解决方案效果很好。

constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private location: Location,
}
...

back(): void {
    if (window.history.state === null) {
      this.router.navigate(['../'], { relativeTo: this.activatedRoute });
      return;
    }

    this.location.back();
}

其他回答

这似乎很管用:

function goBackOrClose() {  

    window.history.back();
    window.close(); 

    //or if you are not interested in closing the window, do something else here
    //e.g. 
    theBrowserCantGoBack();

}

调用history.back(),然后调用window.close()。如果浏览器能够返回历史记录,它将无法到达下一条语句。如果无法返回,就会关闭窗口。

但是,请注意,如果已经通过输入url到达页面,那么firefox不允许脚本关闭窗口。

我正在使用Angular,我需要检查是否有历史记录,触发location.back(),否则重定向到父路由。

来自https://stackoverflow.com/a/69572533/18856708的解决方案效果很好。

constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private location: Location,
}
...

back(): void {
    if (window.history.state === null) {
      this.router.navigate(['../'], { relativeTo: this.activatedRoute });
      return;
    }

    this.location.back();
}

这是我的解决方案:

function historyBack() {
  console.log('back');
  window.history.back() || window.history.go(-1);
  if (!window.history.length) window.close();
  var currentUrl = window.location.href;
  setTimeout(function(){
    // if location was not changed in 100 ms, then there is no history back
    if(current === window.location.href){
        console.log('History back is empty!');
    }
  }, 100);
}
function historyForward() {
  console.log('forward');
  window.history.forward() || window.history.go(+1);
  var current = window.location.href;
  setTimeout(function(){
    // if location was not changed in 100 ms, then there is no history forward
    if(current === window.location.href){
        console.log('History forward is empty!');
    }
  }, 100);
}

解决方案

'use strict';
function previousPage() {
  if (window.location.pathname.split('/').filter(({ length }) => length > 0).length > 0) {
    window.history.back();
  }
}

解释

window.location.pathname会给你当前的URI。例如,https://domain/question/1234/i-have-a-problem会给出/question/1234/i-have-a-problem。请参阅有关窗口的文档。获取更多信息的位置。

接下来,调用split()将为我们提供该URI的所有片段。所以如果我们使用我们之前的URI,我们将会有像["","question", "1234", "i-have-a-problem"]这样的东西。有关更多信息,请参阅有关String.prototype.split()的文档。

这里调用filter()来过滤掉由反斜杠生成的空字符串。它基本上只返回长度大于1的URI片段(非空字符串)。所以我们会有像["question", "1234", "i-have-a-question"]这样的东西。这可以写成这样:

'use strict';
window.location.pathname.split('/').filter(function(fragment) {
  return fragment.length > 0;
});

有关更多信息,请参阅关于Array.prototype.filter()和析构赋值的文档。

现在,如果用户在https://domain/上尝试返回,我们不会触发if语句,也不会触发window.history.back()方法,这样用户就会留在我们的网站中。这个URL将等价于长度为0的[],0 > 0为假值。因此,默默的失败。当然,如果您愿意,您可以记录一些内容或其他操作。

'use strict';
function previousPage() {
  if (window.location.pathname.split('/').filter(({ length }) => length > 0).length > 0) {
    window.history.back();
  } else {
    alert('You cannot go back any further...');
  }
}

限制

当然,如果浏览器不支持History API,这个解决方案将不起作用。在使用此解决方案之前,请查看文档以了解更多信息。

我找到了一个真正有效的JQuery解决方案

window.history.length == 1

这适用于Chrome, Firefox和Edge。 如果你想在没有窗口历史记录的情况下隐藏或删除网页上的后退按钮,你可以使用下面这段JQuery代码,它在上述3种浏览器的最新版本上都适用。

$(window).load(function() {
        if (window.history.length == 1) {
            $("#back-button").remove();
        }
    })