我想用JavaScript看是否有历史记录,后退按钮在浏览器上是否可用。


当前回答

注意window.history.length,因为它还包括window.history.forward()的条目。

window。history。length可能有多于1个条目,但没有历史回溯条目。 这意味着如果你触发window.history.back()

其他回答

还有另一种检查方法——检查推荐人。第一页通常会有一个空的引用。

if (document.referrer == "") {
    window.close()
} else {
    history.back()
}

我找到了一个真正有效的JQuery解决方案

window.history.length == 1

这适用于Chrome, Firefox和Edge。 如果你想在没有窗口历史记录的情况下隐藏或删除网页上的后退按钮,你可以使用下面这段JQuery代码,它在上述3种浏览器的最新版本上都适用。

$(window).load(function() {
        if (window.history.length == 1) {
            $("#back-button").remove();
        }
    })

我试图找到一个解决方案,这是我能得到的最好的(但工作很棒,这是我在这里找到的最简单的解决方案)。

在我的情况下,我想回到历史上一个返回按钮,但如果用户打开的第一页是我的应用程序的子页,它会回到主页。

解决方案是,一旦应用程序被加载,我只是做了一个替换历史状态:

history.replaceState( {root: true}, '', window.location.pathname + window.location.hash)

这样,我只需要在返回之前检查history.state.root。如果是真的,我做一个历史代替:

if(history.state && history.state.root)
    history.replaceState( {root: true}, '', '/')
else
    history.back() 
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);
}

下面的解决方案将导航回来,并告诉是否发生了导航:

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()是一个异步函数。