Chrome:如何检测历史导航(后退按钮已被按下)

2eafrhcq  于 2023-02-01  发布在  Go
关注(0)|答案(1)|浏览(126)

我知道,这个问题看起来很像那些问和reassed定期,例如在这里:
How to force reloading a page when using browser back button?
我需要知道用户是否有...
.导航到当前页面,或重新加载当前页面(在这两种情况下,页面已正常加载,我不需要进一步的具体行动)
.或使用历史 * 后退 * 或 * 前进 * 按钮到达当前页面(在这些情况下,页面 * 未 * 加载,只是无论如何从浏览器缓存中取出,并且我需要采取进一步的措施-最简单的是重新加载页面,window.location.reload();或等效)。
我尝试了这里公开的解决方案:https://stackoverflow.com/a/43043658/3872061和此处:https://stackoverflow.com/a/56851042/3872061以及其他几个地方,在Stackoverflow或没有。
它在Firefox(105.0.1)和Edge(105.0.1343.50)上运行良好,但我无法让它在Chrome(105.0.5195.127)上运行。
这是我能想到的最简单的测试。

第一页. html

<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    $(window).on("pageshow", function(e){

      $("#type").text(window.performance.getEntriesByType("navigation")[0].type);
      let historyTraversal = event.persisted
        || ( typeof window.performance != "undefined" && window.performance.getEntriesByType("navigation")[0].type === "back_forward" );
      if ( historyTraversal ) { // Handle page restore.
        $("#backOrNot").text('User just came back using the history "back" button');
        //window.location.reload(); // this is actually the targetted action: reload page
      }
      else {
        $("#backOrNot").text('User loaded the page');
      }

    });
  </script>
</head>
<body>
  <p id="backOrNot"></p>
  <p>( window.performance.getEntriesByType("navigation")[0].type = <span id="type"></span> )</p>
  <p><a href="page2.html">Just a link from where you can click the history back button</a></p>
</body>
</html>

第二页. html

<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
</head>
<body>
  <p>
    From here, try to:<br>
    1. Navigate to <a href="page1.html">page1.html</a><br>
    2. Go back to page1.html using the history back-button
  </p>
</body>
</html>

对于FF和Edge,当您使用历史记录返回到 * page 1 * 时,“back_forward”信息可用。

使用Chrome浏览器时,你只会看到页面初始加载时的状态(“导航”或“重新加载”),就好像你从未离开过页面,然后使用后退按钮返回一样。

我错过了什么?我做错了什么?

9q78igpj

9q78igpj1#

如果您发送页面头以禁止缓存itemsList.php页面,则页面将自动重新加载。我的测试代码-see answer here-应该有助于您理解这个概念。我仍在尝试找到更好的方法来以不同的方式解决这个问题。在我的示例中,我将启动一个“page-is-now-loading-spinner”,它不会将自身重置为隐藏。如果按下后退按钮(返回一页)。

相关问题