我想用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>

其他回答

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

历史。长度是无用的,因为它不能显示用户是否可以回到历史。 另外,不同的浏览器使用初始值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);

这可能会有帮助:

const prev = window.location.pathname;
window.history.back();
setTimeout(() => {
  if (prev === window.location.pathname) {
    // Do something else ... 
  }
}, 1000);

这似乎很管用:

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

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

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

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

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