浏览器监听页面变化相关事件

553 阅读2分钟

popstate 事件

  • popstate 事件在浏览器历史记录状态发生变化时触发,比如用户点击浏览器的前进/后退按钮时。
  • 您可以在 popstate 事件处理函数中获取到 event.state 对象,它包含了当前历史记录状态的数据。
  • 示例代码:
// 监听popstate事件
window.addEventListener('popstate', function(event) {
  console.log('location: ' + document.location + ', state: ' + JSON.stringify(event.state));
});

目前已知:ios17.5.1,微信浏览器内控制浏览器返回按钮,未能触发此事件 mdn说明

pageshow 事件

  • pageshow 事件在页面显示时触发,无论是首次加载还是从浏览器缓存中读取,包含浏览器前进/后退操作。
  • 与 load 事件不同, pageshow 事件在页面从浏览器缓存中加载时也会触发。
  • 您可以通过 event.persisted 属性判断页面是否是从浏览器缓存中加载的。
  • 示例代码:
window.addEventListener('pageshow', function(event) {
  if (event.persisted) {
    console.log('This page was loaded from the bfcache.'); 
  } else {
    console.log('This page was loaded normally.');
  }
});

mdn说明

hashchange 事件

  • 当 URL 的 hash 部分发生变化时,会触发 hashchange 事件。
  • 这个事件对于不支持 HTML5 历史 API 的老版本浏览器很有用。
  • 示例代码:
window.addEventListener('hashchange', function(event) {
  console.log('The hash has changed! New hash: ' + event.newURL);
});

beforeunload 事件

  • 当用户即将离开当前页面时,会触发 beforeunload 事件(当浏览器窗口关闭或者刷新时)。
  • 您可以在这个事件处理函数中保存当前页面的状态,并在下次进入页面时恢复状态。
  • 示例代码:
window.addEventListener('beforeunload', function(event) {
  // 保存当前页面的状态
  localStorage.setItem('pageState', JSON.stringify(currentPageState));
});

mdn说明

unload 事件

  • 当用户离开当前页面时,会触发 unload 事件。
  • 与 beforeunload 事件不同, unload 事件在页面彻底卸载时触发,可以用于执行一些清理操作。
  • 示例代码:
window.addEventListener('unload', function(event) {
  // 执行一些清理操作
  cleanupResourcesAndData();
});

mdn说明及兼容性--已弃用

visibilitychange 事件

  • 当页面的可见性发生变化时,会触发 visibilitychange 事件。
  • 您可以在这个事件处理函数中暂停/恢复页面的状态管理逻辑。
  • 示例代码:
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "visible") {
    console.log('页面展示');
  } else {
    console.log('页面隐藏');
  }
});