常用 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
// https://developer.mozilla.org/zh-CN/docs/Web/API/Notifications_API
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
localStorage.setItem('key', 'value');
const v = localStorage.getItem('key');

// SessionStorage
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 文档