我想用JavaScript看是否有历史记录,后退按钮在浏览器上是否可用。
当前回答
我的代码让浏览器返回一个页面,如果失败,它加载一个回退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);
}
其他回答
下面的解决方案将导航回来,并告诉是否发生了导航:
async function goBack() {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject('nowhere to go'), 100);
window.history.back();
const onBack = () => {
window.removeEventListener('beforeunload', onBack);
window.removeEventListener('popstate', onBack);
clearTimeout(timer);
resolve(true);
};
window.addEventListener('beforeunload', onBack);
window.addEventListener('popstate', onBack);
});
}
// usage
await goBack().catch(err => console.log('failed'));
工作原理:
试着导航回去 添加事件监听器,在导航到另一个网站或同一网站上的另一个页面时触发(SPA网站等) 如果上述事件在100毫秒内没有发生,就可以推断出没有地方可以回去
注意goBack()是一个异步函数。
浏览器有后退和前进按钮。我想出了这个问题的解决办法。但它会影响浏览器的转发操作,并导致一些浏览器的错误。
它的工作原理是这样的:如果浏览器打开一个从未打开过的新url,历史。长度会变长。
你可以改变哈希值
location.href = '#__transfer__' + new Date().getTime()
要得到一个从未显示的url,然后历史。长度会得到真正的长度。
var realHistoryLength = history.length - 1
但是,它并不总是工作得很好,我不知道为什么,特别是当url自动跳转很快。
这似乎很管用:
function goBackOrClose() {
window.history.back();
window.close();
//or if you are not interested in closing the window, do something else here
//e.g.
theBrowserCantGoBack();
}
调用history.back(),然后调用window.close()。如果浏览器能够返回历史记录,它将无法到达下一条语句。如果无法返回,就会关闭窗口。
但是,请注意,如果已经通过输入url到达页面,那么firefox不允许脚本关闭窗口。
这是我的解决方案:
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);
}
我在我的项目中使用了一个片段:
function back(url) {
if (history.length > 2) {
// if history is not empty, go back:
window.History.back();
} else if (url) {
// go to specified fallback url:
window.History.replaceState(null, null, url);
} else {
// go home:
window.History.replaceState(null, null, '/');
}
}
供参考:我使用history. js来管理浏览器历史。
为什么要比较历史。2的长度?
因为Chrome的开始页面是浏览器历史记录中的第一项。
历史的可能性很少。长度和用户行为:
用户在浏览器中打开新的空选项卡,然后运行一个页面。历史。Length = 2,在这种情况下我们要禁用back(),因为user将转到空选项卡。 用户在新选项卡中通过单击前面某处的链接打开页面。历史。Length = 1,同样我们要禁用back()方法。 最后,用户登陆当前页面后重新加载几个页面。历史。长度> 2和now back()可以启用。
注意:当用户点击外部网站的链接后,没有target="_blank"时,我省略了大小写。
注2:文件。referrer是空的,当你打开网站输入它的地址,也当网站使用ajax加载子页面,所以我停止检查这个值在第一种情况下。