CodeWalk

navigator 对象有哪些实用的 API?

作者:Yahuda · 2026-05-30 12:55

请说明 navigator 对象的常用功能,包括 userAgent、geolocation、mediaDevices、clipboard、bluetooth 等。

回答

Yahuda

1. navigator.userAgent:浏览器用户代理字符串,用于判断浏览器类型(不推荐,特征检测更好)

const isChrome = /Chrome\//.test(navigator.userAgent);

2. navigator.geolocation:地理位置 API

navigator.geolocation.getCurrentPosition(
  pos => console.log(pos.coords.latitude, pos.coords.longitude),
  err => console.error(err)
);

3. navigator.mediaDevices:媒体设备(摄像头/麦克风/屏幕共享)

const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
// 共享屏幕
const displayStream = await navigator.mediaDevices.getDisplayMedia();

4. navigator.clipboard:剪贴板(需 HTTPS 或 localhost)

await navigator.clipboard.writeText('复制文本');
const text = await navigator.clipboard.readText();

5. navigator.serviceWorker:Service Worker 注册入口 6. navigator.storage:存储配额估计 navigator.storage.estimate() 7. navigator.onLine:网络状态 true/false(配合 online/offline 事件) 8. navigator.sendBeacon(url, data):页面关闭时发送数据(埋点) 9. navigator.connection:网络连接信息(NetworkInformation API)

注意:部分功能需要 HTTPS 环境或用户授权。