常用 Web API 参考
1. Crypto 加密
Crypto.subtle
仅支持 https
,用于加密、解密、签名等操作。- 示例:生成 SHA-256 哈希
1 2 3 4 5 6 7 8
| async function sha256(message) { const encoder = new TextEncoder(); const data = encoder.encode(message); const hashBuffer = await crypto.subtle.digest('SHA-256', data); return Array.from(new Uint8Array(hashBuffer)).map(b => b.toString(16).padStart(2, '0')).join(''); }
sha256('hello world').then(console.log);
|
2. Notifications API 系统通知
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function notification(title, content, iconurl) { Notification.requestPermission().then(function(permission) { if(permission == 'granted') { var mynotification = new Notification(title, { body: content, icon: (iconurl||document.getElementById('meAvatar')?.src) }); mynotification.onclick = function() { mynotification.close(); window.focus(); } } }); }
|
3. Clipboard API 剪贴板
1 2 3 4 5 6 7 8
| async function copyText(text) { try { await navigator.clipboard.writeText(text); alert('已复制到剪贴板'); } catch (err) { alert('复制失败'); } }
|
4. Fetch API 网络请求
- 替代 XMLHttpRequest,支持 Promise。
1 2 3 4
| fetch('https://api.example.com/data') .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err));
|
5. Fullscreen API 全屏
1 2 3 4 5 6 7 8 9 10
| function enterFullscreen(elem) { if (elem.requestFullscreen) { elem.requestFullscreen(); } } function exitFullscreen() { if (document.exitFullscreen) { document.exitFullscreen(); } }
|
6. Geolocation API 地理定位
1 2 3 4
| navigator.geolocation.getCurrentPosition( pos => console.log(pos.coords), err => console.error(err) );
|
7. Speech Synthesis API 语音合成
1 2 3 4
| function speak(text) { const utter = new SpeechSynthesisUtterance(text); speechSynthesis.speak(utter); }
|
8. LocalStorage & SessionStorage 本地存储
1 2 3 4 5 6
| localStorage.setItem('key', 'value'); const v = localStorage.getItem('key');
sessionStorage.setItem('key', 'value');
|
9. BroadcastChannel API 跨标签页通信
1 2 3
| const channel = new BroadcastChannel('my_channel'); channel.postMessage('hello'); channel.onmessage = e => console.log(e.data);
|
10. Page Visibility API 页面可见性
1 2 3 4 5 6 7
| document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') { } else { } });
|
更多 API 可参考 MDN Web API 文档