window.navigator.onLine 不管用是什么原因?

谷歌浏览器,电脑网络状态在线。打开其他网页也没问题。网络连接正常。但是 window.navigator.onLine 却为 false。是什么原因?
而且,设置 40s 的长轮询接口大概等待 6s 多就会报错。在其他人电脑上就没问题。

阅读 5.5k
1 个回答

定一个方法getConnectionState 来返回网络状态。

const getConnection = () => {
  if (typeof navigator !== 'object') {
    return null;
  }
  const nav = navigator;
  return nav.connection || nav.mozConnection || nav.webkitConnection;
};

const getConnectionState = ()=> {
  const connection = getConnection();
  if (!connection) {
    return {};
  }
  const { downlink, downlinkMax, effectiveType, type, rtt } = connection;
  return {
    downlink,
    downlinkMax,
    effectiveType,
    type,
    rtt,
  };
};

使用(没有执行判空处理,如果你要用到生产环境, 请自己加上判断getConnectionState() 返回值是否为null的逻辑):

// online
getConnectionState().rtt > 0
// offline
getConnectionState().rtt == 0
推荐问题