我想用JavaScript看是否有历史记录,后退按钮在浏览器上是否可用。
当前回答
历史。长度是无用的,因为它不能显示用户是否可以回到历史。 另外,不同的浏览器使用初始值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);
其他回答
我不确定这是否有效,它完全未经测试,但试试这个:
<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();
}
我找到了一个真正有效的JQuery解决方案
window.history.length == 1
这适用于Chrome, Firefox和Edge。 如果你想在没有窗口历史记录的情况下隐藏或删除网页上的后退按钮,你可以使用下面这段JQuery代码,它在上述3种浏览器的最新版本上都适用。
$(window).load(function() {
if (window.history.length == 1) {
$("#back-button").remove();
}
})
还有另一种检查方法——检查推荐人。第一页通常会有一个空的引用。
if (document.referrer == "") {
window.close()
} else {
history.back()
}