我想用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上为我工作。

其他回答

你不能直接检查后退按钮是否可用。你可以看看历史。长度为>0,但如果在当前页之前还有页,这也是成立的。只有当history.length===0时,才能确定后退按钮不可用。

如果这还不够好,你所能做的就是调用history.back(),如果你的页面之后仍然被加载,返回按钮是不可用的!当然,这意味着如果后退按钮可用,则您刚刚导航离开了页面。你不允许取消onunload中的导航,所以你所能做的就是从onbeforeunload中返回一些东西,这将导致一个恼人的大提示符出现。这不值得。

事实上,用历史做任何事情通常都是一个非常糟糕的主意。历史导航是chrome浏览器,不是网页。添加“返回”链接通常会引起更多用户的困惑,而不是它的价值。

我正在使用Angular,我需要检查是否有历史记录,触发location.back(),否则重定向到父路由。

来自https://stackoverflow.com/a/69572533/18856708的解决方案效果很好。

constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private location: Location,
}
...

back(): void {
    if (window.history.state === null) {
      this.router.navigate(['../'], { relativeTo: this.activatedRoute });
      return;
    }

    this.location.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上为我工作。

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

window.history.length == 1

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

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

我用的是window。在我的网站上的常见问题解答。

当用户想退出FAQ时,他们可以点击退出按钮(在后退按钮旁边)

我对这个“退出”策略的逻辑是基于入口ID,然后返回到该状态的状态数。

所以进入:

  enterState: { navigationId:number } = {navigationId: 1}

  constructor() {
    this.enterState = window.history.state
  }

假设用户正在浏览FAQ

然后,当用户单击退出按钮时,读取当前状态并计算delta:

exitFaq() {
    // when user started in faq, go back to first state, replace it with home and navigate
    if (this.enterState.navigationId === 1) {
      window.history.go((window.history.state.navigationId - 1) * -1)
      this.router.navigateByUrl('/')
      //  non-angular
      //  const obj = {Title: 'Home', Url: '/'}
      //  window.history.replaceState(obj, obj.Title, obj.Url)
    } else {
      window.history.go(this.enterState.navigationId - window.history.state.navigationId - 1)
    }
  }

如你所见,我还使用了一个回退当用户开始在faq,在这种情况下,状态。navigationId为1,我们想要路由回去,替换第一个状态,并显示主页(为此我使用Angular路由器,但你也可以使用历史记录。当你处理自己的路由时,也可以使用replaceState)

供参考:

history.go history.state history.replaceState Angular.router.navigateByUrl