我想用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);
其他回答
这是我的解决方案:
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);
}
我的代码让浏览器返回一个页面,如果失败,它加载一个回退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);
}
简单的回答:你不能。
技术上有一个准确的方法,那就是检查属性:
history.previous
然而,这是行不通的。这样做的问题是,在大多数浏览器中,这被认为是违反安全的,通常只是返回undefined。
history.length
是其他人认为的… 然而,长度并不能完全起作用,因为它不能表明你所处的历史位置。此外,它并不总是从相同的数字开始。例如,一个未设置有登录页的浏览器将从0开始,而另一个使用登录页的浏览器将从1开始。
大多数情况下,添加的链接调用:
history.back();
or
history.go(-1);
如果你不能返回,那么点击链接就没有任何作用。
我找到了一个真正有效的JQuery解决方案
window.history.length == 1
这适用于Chrome, Firefox和Edge。 如果你想在没有窗口历史记录的情况下隐藏或删除网页上的后退按钮,你可以使用下面这段JQuery代码,它在上述3种浏览器的最新版本上都适用。
$(window).load(function() {
if (window.history.length == 1) {
$("#back-button").remove();
}
})
以这里和这里的答案为基础。我认为,更确切的答案是检查这是否是一个新标签中的新页面。
如果页面的历史记录不止一个,那么我们可以返回到当前页面之前的页面。如果不是,则该标签是新打开的标签,我们需要创建一个新标签。
不同的是,对于链接的答案,我们不会检查一个推荐人,因为一个新的标签仍然会有一个推荐人。
if(1 < history.length) {
history.back();
}
else {
window.close();
}