资源下载等离不开用户的网络方面的支持,本文会介绍获取用户网络信息的方法。最后会编写一个react hook记录用户的网络信息。
网络连接状态
window.online
返回boolean值,是否连上网络。
window.ononline
当浏览器能访问网络且Navigator.onLine设置为true时,该事件会被触发
该事件不能用来确认网站可否访问。网站自身问题或防火墙都有可能阻止对特定网站的访问。
window.addEventListener('online', () => {
console.log('you are in newwork')
});
window.onoffline
window.addEventListener('offline', () => {
console.log('you are in newwork')
});
navigator
window.navigator会返回一个Navigator对象,可以用来请求当前代码的应用程序的相关信息
例如:
const useAgent = window.navigator.useAgent; // 可用于判断用户使用的浏览器信息
大多浏览器类型的判断都是基于这个属性进行封装的,更多使用方法可以参考MDN中的例子-navigator
Navigator.connection
Navigator.connection 目前还是一个实验中的,只读属性,存在一定的浏览器兼容性问题。它提供了一个NetworkInformation对象来获取设备的网络连接信息.
const nav = window.navigation;
const connnetion = nav.connection || nav.mozConnection || nav.webkitConnection;
NetworkInformation
| 属性名 | 含义 | 类型 | 值 |
|---|---|---|---|
| type | 网络类型 | string | bluetooth、cellular、wifi、ethernet、none、wifi、wimax、other、unkonwn |
| effectType | 网络类型 | string | 同type |
| downlink | number | 返回基础连接技术的下载速度(Mbps) | - |
| downlinkMax | number | 返回基础连接技术的最大下载速度(Mbps) | - |
| rtt | 信号延迟 | number | - |
| saveData | 是否开启节省流量开关 | boolean | - |
NetworkInformation.onchange 当连接信息更改,并在此对象触发更改时触发的change
useNework
interface INetworkState {
onLine?: boolean; // 网络连接状态
rtt?: number; // 网络延迟
type?: string; // 网络类型
effectiveType?: string // 活跃的网络烈性
downlink?: number; // 下载速度
downlinkMax?: number; // 最大下载速度
saveData?: boolean; // 是否开启省流开关
}
enum NetworkEventType {
ONLINE = 'online',
OFFLINE = 'offline',
CHANGE = 'change',
}
// 获取connect对象
const getConnection = () => {
const nav = window.navigator;
if(!nav || typeof nav !== 'object') return null;
return (nav.connection || nav.mozConnection || nav.webkitConnection) as Navigator['connection'];
}
const getConnectionInfo = () => {
return getConnection() || {};
}
function useNetwork() {
// 初始花信息
const [state, setState] = useState<INetworkState>({
onLine: navigator?.onLine,
...(getConnectionInfo()),
});
useEffect(() => {
const online = () => {
setState({ ...state, online: true })
}
const onffline = () => {
setState({ ...state, online: false })
}
const onChange = () => {
setState({ ...state, ...getConnectionInfo() })
}
window.addEventListener(NetworkEventType.ONLINE, online);
window.addEventListener(NetworkEventType.OFFLINE, onffline);
const condition = getConnection();
condition?.addEventListener(NetworkEventType.ONLINE, onChange);
return () => {
window.removeEventListener(NetworkEventType.ONLINE, online);
window.removeEventListener(NetworkEventType.OFFLINE, onffline);
condition?.removeEventListener(NetworkEventType.ONLINE, onChange);
}
}, []);
return state;
}
今天就到这儿了吧,祝大家工作顺利,天天开心。