我想用JavaScript看是否有历史记录,后退按钮在浏览器上是否可用。
当前回答
我找到了一个真正有效的JQuery解决方案
window.history.length == 1
这适用于Chrome, Firefox和Edge。 如果你想在没有窗口历史记录的情况下隐藏或删除网页上的后退按钮,你可以使用下面这段JQuery代码,它在上述3种浏览器的最新版本上都适用。
$(window).load(function() {
if (window.history.length == 1) {
$("#back-button").remove();
}
})
其他回答
简单的回答:你不能。
技术上有一个准确的方法,那就是检查属性:
history.previous
然而,这是行不通的。这样做的问题是,在大多数浏览器中,这被认为是违反安全的,通常只是返回undefined。
history.length
是其他人认为的… 然而,长度并不能完全起作用,因为它不能表明你所处的历史位置。此外,它并不总是从相同的数字开始。例如,一个未设置有登录页的浏览器将从0开始,而另一个使用登录页的浏览器将从1开始。
大多数情况下,添加的链接调用:
history.back();
or
history.go(-1);
如果你不能返回,那么点击链接就没有任何作用。
这可能会有帮助:
const prev = window.location.pathname;
window.history.back();
setTimeout(() => {
if (prev === window.location.pathname) {
// Do something else ...
}
}, 1000);
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>
我试图找到一个解决方案,这是我能得到的最好的(但工作很棒,这是我在这里找到的最简单的解决方案)。
在我的情况下,我想回到历史上一个返回按钮,但如果用户打开的第一页是我的应用程序的子页,它会回到主页。
解决方案是,一旦应用程序被加载,我只是做了一个替换历史状态:
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()