页面状态监听

177 阅读1分钟
记录一些状态监听方式

1.见面是否可见状态监听

      let vEvent = 'visibilitychange';
      if (document.webkitHidden !== undefined) {
        // 设置前缀
        vEvent = 'webkitvisibilitychange';
      }

      function visibleChanged() {
        if (document.hidden || document.webkitHidden) {
          console.log('页面隐藏');
        } else {
          console.log('页面显示');
        }
      }

      document.addEventListener(vEvent, visibleChanged, false);

2.网络状态变化监听

const connection = navigator.connection ||
        navigator.mozConnection ||
        navigator.webkitConnection;
      const type = connection.effectiveType;

      function updateStatus() {
        console.log(
          '网络变化 从 ' + type + ' 变成 ' + connection.effectiveType
        );
      }

      connection.addEventListener('change', updateStatus);