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


当前回答

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

其他回答

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

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

你可以改变哈希值

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

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

  var realHistoryLength = history.length - 1

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

以这里和这里的答案为基础。我认为,更确切的答案是检查这是否是一个新标签中的新页面。

如果页面的历史记录不止一个,那么我们可以返回到当前页面之前的页面。如果不是,则该标签是新打开的标签,我们需要创建一个新标签。

不同的是,对于链接的答案,我们不会检查一个推荐人,因为一个新的标签仍然会有一个推荐人。

if(1 < history.length) {
    history.back();
}
else {
    window.close();
}

历史。长度是无用的,因为它不能显示用户是否可以回到历史。 另外,不同的浏览器使用初始值0或1 -这取决于浏览器。

有效的解决方案是使用$(window)。on('beforeunload'事件,但我不确定它会工作,如果页面是通过ajax加载和使用pushState改变窗口历史。

所以我使用了下一个解决方案:

var currentUrl = window.location.href;
window.history.back();
setTimeout(function(){
    // if location was not changed in 100 ms, then there is no history back
    if(currentUrl === window.location.href){
        // redirect to site root
        window.location.href = '/';
    }
}, 100);

还有另一个近乎完美的解决方案,来自于另一个SO答案:

if( (1 < history.length) && document.referrer ) {
    history.back();
}
else {
    // If you can't go back in history, you could perhaps close the window ?
    window.close();
}

有人报告说,当使用target="_blank"时,它不工作,但它似乎在Chrome上为我工作。

这是我的解决方案:

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);
}