Google Chrome 上的页面隐藏事件

问题描述 投票:0回答:2

我正在拼命地尝试让这个在 Chrome 上工作(在 Firefox 上很好)

window.addEventListener(
  "pagehide",
  function() {
    console.log("pagehide");
  },
  { capture: true }
);

现在这会在页面重新加载时触发,但是当按前进或后退按钮导致另一个网站时,它无法工作。

PS 我在这里发现了很多问题 bugs.chromium.org 但我不确定它们是否以及哪些可能适用。

javascript google-chrome dom-events page-lifecycle
2个回答
0
投票

它确实有效,但可能不是你期望的那样。简单的测试方法:

window.addEventListener('pagehide', function() {
  window.open('https://google.com');
});

每当页面通过刷新或后退/前进导航隐藏时,您都应该有一个新的 Google 标签。


0
投票
  window.addEventListener('pagehide', function (event) {
    if (event.persisted) {
      // If the event's persisted property is `true` the page is about
      // to enter the Back-Forward Cache, which is also in the frozen state
    } else {
      // If the event's persisted property is not `true` the page is about to be unloaded.
    }
  },
    { capture: true }
  );

“一些浏览器实现了后退缓存,并且页面生命周期 API 将缓存的页面分类为冻结状态。由于此 API 是全新的,因此这些浏览器尚未实现冻结和恢复事件,尽管这种状态仍然可以实现通过 pagehide 和 pageshow 事件观察。”

有关页面生命周期 API 的文章 - Google Developers

© www.soinside.com 2019 - 2024. All rights reserved.