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


当前回答

var fallbackUrl = "home.php";
if(history.back() === undefined)
    window.location.href = fallbackUrl;

其他回答

我不确定这是否有效,它完全未经测试,但试试这个:

<script type="text/javascript">

    function goBack() {
        history.back();
    }

    if (history.length > 0) { //if there is a history...
        document.getElementsByTagName('button')[].onclick="goBack()"; //assign function "goBack()" to all buttons onClick
    } else {
        die();
    }
</script>

在HTML的某处:

<button value="Button1"> //These buttons have no action
<button value="Button2">

编辑:

您还可以研究哪些浏览器支持back函数(我认为它们都支持),并使用本页中找到并详细描述的标准JavaScript浏览器检测对象。然后你可以有2个不同的页面:一个是兼容后退按钮的“好浏览器”页面,一个是告诉他们更新浏览器的“坏浏览器”页面

检查window.history.length是否等于0。

我正在使用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();
}

我试图找到一个解决方案,这是我能得到的最好的(但工作很棒,这是我在这里找到的最简单的解决方案)。

在我的情况下,我想回到历史上一个返回按钮,但如果用户打开的第一页是我的应用程序的子页,它会回到主页。

解决方案是,一旦应用程序被加载,我只是做了一个替换历史状态:

history.replaceState( {root: true}, '', window.location.pathname + window.location.hash)

这样,我只需要在返回之前检查history.state.root。如果是真的,我做一个历史代替:

if(history.state && history.state.root)
    history.replaceState( {root: true}, '', '/')
else
    history.back() 

这工作为我使用react,但可以在另一种情况下工作;当历史记录在第一页时(你不能返回)window.history.state将为null,所以如果你想知道你是否可以返回,你只需要:

if (window.history.state == null) {
   //you cannot go back
}

文档:

的历史。状态属性返回表示位于的状态的值 历史堆栈的顶端。这是一种看待国家的方式 而不必等待popstate事件。