我想用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不允许脚本关闭窗口。

我的代码让浏览器返回一个页面,如果失败,它加载一个回退url。它还可以检测标签的变化。

当后退按钮不可用时,回退url将在500毫秒后加载,这样浏览器就有足够的时间加载上一页。在window.history.go(-1)之后加载回退url;会导致浏览器使用回退url,因为js脚本还没有停止。

function historyBackWFallback(fallbackUrl) {
    fallbackUrl = fallbackUrl || '/';
    var prevPage = window.location.href;

    window.history.go(-1);

    setTimeout(function(){ 
        if (window.location.href == prevPage) {
            window.location.href = fallbackUrl; 
        }
    }, 500);
}
var func = function(){ console.log("do something"); };
if(document.referrer.includes(window.location.hostname) && history.length-1 <= 1){
    func();
}
else{
    const currentUrl = window.location.href;
    history.back();
    setTimeout(function(){
        currentUrl === window.location.href && func();
    }, 100);
}

我使用了一点PHP来实现这个结果。不过有点生锈了。但它应该会起作用。

<?php 
function pref(){ 
  return (isset($_SERVER['HTTP_REFERER'])) ? true : '';
}
?>
<html>
<body>

<input type="hidden" id="_pref" value="<?=pref()?>">

<button type="button" id="myButton">GoBack</button>

<!-- Include jquery library -->
<script> 
  if (!$('#_pref').val()) { 
    $('#myButton').hide() // or $('#myButton').remove()
  } 
</script>
</body>
</html>

我在我的项目中使用了一个片段:

function back(url) {
    if (history.length > 2) {
        // if history is not empty, go back:
        window.History.back();
    } else if (url) {
        // go to specified fallback url:
        window.History.replaceState(null, null, url);
    } else {
        // go home:
        window.History.replaceState(null, null, '/');
    }
}

供参考:我使用history. js来管理浏览器历史。


为什么要比较历史。2的长度?

因为Chrome的开始页面是浏览器历史记录中的第一项。


历史的可能性很少。长度和用户行为:

用户在浏览器中打开新的空选项卡,然后运行一个页面。历史。Length = 2,在这种情况下我们要禁用back(),因为user将转到空选项卡。 用户在新选项卡中通过单击前面某处的链接打开页面。历史。Length = 1,同样我们要禁用back()方法。 最后,用户登陆当前页面后重新加载几个页面。历史。长度> 2和now back()可以启用。


注意:当用户点击外部网站的链接后,没有target="_blank"时,我省略了大小写。

注2:文件。referrer是空的,当你打开网站输入它的地址,也当网站使用ajax加载子页面,所以我停止检查这个值在第一种情况下。