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


当前回答

简单的回答:你不能。

技术上有一个准确的方法,那就是检查属性:

history.previous

然而,这是行不通的。这样做的问题是,在大多数浏览器中,这被认为是违反安全的,通常只是返回undefined。

history.length

是其他人认为的… 然而,长度并不能完全起作用,因为它不能表明你所处的历史位置。此外,它并不总是从相同的数字开始。例如,一个未设置有登录页的浏览器将从0开始,而另一个使用登录页的浏览器将从1开始。

大多数情况下,添加的链接调用:

history.back();

or

 history.go(-1);

如果你不能返回,那么点击链接就没有任何作用。

其他回答

这工作为我使用react,但可以在另一种情况下工作;当历史记录在第一页时(你不能返回)window.history.state将为null,所以如果你想知道你是否可以返回,你只需要:

if (window.history.state == null) {
   //you cannot go back
}

文档:

的历史。状态属性返回表示位于的状态的值 历史堆栈的顶端。这是一种看待国家的方式 而不必等待popstate事件。

这是我的解决方案:

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);
}
var fallbackUrl = "home.php";
if(history.back() === undefined)
    window.location.href = fallbackUrl;

浏览器有后退和前进按钮。我想出了这个问题的解决办法。但它会影响浏览器的转发操作,并导致一些浏览器的错误。

它的工作原理是这样的:如果浏览器打开一个从未打开过的新url,历史。长度会变长。

你可以改变哈希值

  location.href = '#__transfer__' + new Date().getTime() 

要得到一个从未显示的url,然后历史。长度会得到真正的长度。

  var realHistoryLength = history.length - 1

但是,它并不总是工作得很好,我不知道为什么,特别是当url自动跳转很快。

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

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