function getNetworkType() {
  /* wired 有线
    bluetooth,
    wifi,
    2g,3g,4g,5g...,
    unkown
  */
  var ua = navigator.userAgent;
  var ut = navigator.connection;
  var utt = ut ? ut.type ? ut.type.toLowerCase() : null : null;
  if(utt){
    switch (utt) {//bluetooth,
      case 'cellular':
      case 'wimax':
        utt = ut ? ut.effectiveType ? ut.effectiveType.toLowerCase() : null : null;
        break;
      case 'wifi':
        break;
      case 'ethernet':
        utt = 'wired';
      case 'none':
      case 'other':
      case 'unknown':
        utt = null;
      default:
        break;
    }
  }
  var networkStr = utt ? utt : ua.match(/NetType\/\w+/) ? ua.match(/NetType\/\w+/)[0] : '';
  networkStr = networkStr.toLowerCase().replace('nettype/', '');

  return networkStr ? networkStr === '3gnet' ? '3g' : networkStr : 'unknown';
}

userAgent和connection的兼容性其实都不好,特别是pc,所以很多情况还是返回unkown


肥皂泡
382 声望6 粉丝

码农