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


当前回答

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

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

文档:

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

其他回答

浏览器有后退和前进按钮。我想出了这个问题的解决办法。但它会影响浏览器的转发操作,并导致一些浏览器的错误。

它的工作原理是这样的:如果浏览器打开一个从未打开过的新url,历史。长度会变长。

你可以改变哈希值

  location.href = '#__transfer__' + new Date().getTime() 

要得到一个从未显示的url,然后历史。长度会得到真正的长度。

  var realHistoryLength = history.length - 1

但是,它并不总是工作得很好,我不知道为什么,特别是当url自动跳转很快。

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

<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个不同的页面:一个是兼容后退按钮的“好浏览器”页面,一个是告诉他们更新浏览器的“坏浏览器”页面

我使用了一点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>

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

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

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

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

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()