【问题标题】:pagehide event on Google ChromeGoogle Chrome 上的 pagehide 事件
【发布时间】:2019-09-19 10:54:10
【问题描述】:

我正在拼命尝试在 Chrome 上完成这项工作(在 Firefox 上很好)

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

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

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

【问题讨论】:

  • 感谢@shashank,但“每次活动历史条目在同一文档的两个历史条目之间发生变化时,都会向窗口发送一个 popstate 事件。”
  • 我在 chromium 上遇到了同样的问题,并且能够将这个“错误”缩小到以下情况: - chrome 69 以后(可能是 70,不记得确切),以及 - 导航交叉 -网站或http / https之间。
  • unload 事件应该适合您的场景。它适用于 Chrome、Firefox 和 Edge 等主要浏览器的页面重新加载。 “pagehide”是一个专门为IOS safari 编写的杂乱API。相信我,我们在 timeonsite 跟踪器上大量使用它来卸载、刷新和转发事件。它只在他们推荐“pagehide”的IOS设备上失败。
  • @clivend 你能找到解决方案吗?我目前遇到了同样的错误。 Firefox 支持页面隐藏,但 Chrome 不支持。我需要调用这些来清理功能代码

标签: javascript google-chrome dom-events page-lifecycle


【解决方案1】:

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

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

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

【讨论】:

  • 感谢@Darren,但不幸的是这并没有发生:(
【解决方案2】:
  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
      function()
    } else {
      // If the event's persisted property is not `true` the page is about to be unloaded.
      function()
    }
  }),
    { capture: true }

“有几个浏览器实现了后向缓存,页面生命周期 API 将缓存的页面分类为处于冻结状态。由于这个 API 是全新的,这些浏览器还没有实现冻结和恢复事件,尽管这种状态仍然可以通过 pagehide 和 pageshow 事件观察到。”

Article on Page Lifecycle API - Google Developers

【讨论】:

  • 请注意:如果最后一段是来自某个网​​站的引文,您应该提供链接以及引文(并将段落格式化为块引用)。
猜你喜欢
  • 2014-02-14
  • 1970-01-01
  • 2015-07-13
  • 2011-03-24
  • 1970-01-01
  • 1970-01-01
  • 2013-07-02
  • 2018-08-31
  • 1970-01-01
相关资源
最近更新 更多