我想用JavaScript看是否有历史记录,后退按钮在浏览器上是否可用。
当前回答
还有另一个近乎完美的解决方案,来自于另一个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上为我工作。
其他回答
我不确定这是否有效,它完全未经测试,但试试这个:
<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个不同的页面:一个是兼容后退按钮的“好浏览器”页面,一个是告诉他们更新浏览器的“坏浏览器”页面
我的代码让浏览器返回一个页面,如果失败,它加载一个回退url。它还可以检测标签的变化。
当后退按钮不可用时,回退url将在500毫秒后加载,这样浏览器就有足够的时间加载上一页。在window.history.go(-1)之后加载回退url;会导致浏览器使用回退url,因为js脚本还没有停止。
function historyBackWFallback(fallbackUrl) {
fallbackUrl = fallbackUrl || '/';
var prevPage = window.location.href;
window.history.go(-1);
setTimeout(function(){
if (window.location.href == prevPage) {
window.location.href = fallbackUrl;
}
}, 500);
}
这是我的解决方案:
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);
}
注意window.history.length,因为它还包括window.history.forward()的条目。
window。history。length可能有多于1个条目,但没有历史回溯条目。 这意味着如果你触发window.history.back()
还有另一个近乎完美的解决方案,来自于另一个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上为我工作。