我想用JavaScript看是否有历史记录,后退按钮在浏览器上是否可用。
当前回答
浏览器有后退和前进按钮。我想出了这个问题的解决办法。但它会影响浏览器的转发操作,并导致一些浏览器的错误。
它的工作原理是这样的:如果浏览器打开一个从未打开过的新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个不同的页面:一个是兼容后退按钮的“好浏览器”页面,一个是告诉他们更新浏览器的“坏浏览器”页面
还有另一个近乎完美的解决方案,来自于另一个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上为我工作。
以这里和这里的答案为基础。我认为,更确切的答案是检查这是否是一个新标签中的新页面。
如果页面的历史记录不止一个,那么我们可以返回到当前页面之前的页面。如果不是,则该标签是新打开的标签,我们需要创建一个新标签。
不同的是,对于链接的答案,我们不会检查一个推荐人,因为一个新的标签仍然会有一个推荐人。
if(1 < history.length) {
history.back();
}
else {
window.close();
}
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);
}
检查window.history.length是否等于0。