【整理】浏览器API概览及使用示例一百条

浏览器提供了丰富的API,使得开发者能够创建交互性强、功能丰富的Web应用程序。
后面会把一些不常用的API以单篇文章的形式详细说明用法以及延申用途
文章很长希望大家加个收藏慢慢看
还在烦恼找不到免费好看的电脑桌面吗?点我或者去主页,教你如何自己写一个电脑桌面
如果文章对您有所帮助,请帮我点个免费的赞,拒绝白嫖从我做起,我是七月、期待您的关注

目录

DOM Manipulation APIs - 操作文档对象模型
Event APIs - 处理各种事件
Storage APIs - 在客户端存储数据
Network APIs - 进行网络请求
Geolocation APIs - 获取地理位置
History APIs - 操作浏览器历史
Canvas APIs - 在网页上绘制图形
Audio/Video APIs - 处理音视频
Device APIs - 访问设备信息
Clipboard APIs - 操作剪贴板
Performance APIs - 监控性能
Web Workers - 在后台线程运行脚本
Service Workers - 拦截和处理网络请求
File APIs - 操作文件
Drag and Drop APIs - 实现拖放功能
Intersection Observer API - 监测元素可见性
Pointer Events API - 处理指针事件
WebRTC API - 实现实时通信
WebSockets API - 实现双向通信
Payment Request API - 处理支付请求
Fullscreen API - 全屏显示
Page Visibility API - 监测页面可见性
Web Authentication API - 实现认证
Web Share API - 实现内容分享
Web Speech API - 语音识别与合成
Web Storage API - 存储数据
WebVR API - 虚拟现实
WebXR API - 增强现实
Media Session API - 媒体控制
Picture-in-Picture API - 画中画模式
Wake Lock API - 防止屏幕休眠
Web Bluetooth API - 蓝牙通信
Web NFC API - NFC通信
WebUSB API - USB通信
Web Animations API - 动画效果
Resize Observer API - 监测元素尺寸变化
Mutation Observer API - 监测DOM变化
Performance Timeline API - 性能时间线
User Timing API - 用户计时
High Resolution Time API - 高精度时间
Broadcast Channel API - 广播通信
Credential Management API - 凭证管理
Payment Handler API - 支付处理
Periodic Background Sync API - 周期性后台同步
Permissions API - 权限管理
Push API - 推送通知
Screen Capture API - 屏幕捕获
Sensor APIs - 传感器数据
Storage Access API - 存储访问
Task Scheduler API - 任务调度
WebHID API - HID设备通信
WebOTP API - OTP验证
Web Serial API - 串口通信
Web Share Target API - 分享目标
Web Speech Grammar API - 语音语法
Web Speech Recognition API - 语音识别
Web Speech Synthesis API - 语音合成
WebTransport API - 传输协议
WebAssembly API - WebAssembly模块
Web Locks API - 锁机制
Performance Observer API - 性能观察
Web MIDI API - MIDI设备通信
Web NFC API - NFC通信
WebRTC Data Channels - WebRTC数据通道
File System Access API - 文件系统访问
Wake Lock API - 防止屏幕休眠
WebAssembly Memory API - WebAssembly内存
WebAssembly Table API - WebAssembly表
WebAssembly Global API - WebAssembly全局变量
WebAssembly Module API - WebAssembly模块
Audio Worklet API - 音频处理
Beacon API - 数据发送
Font Loading API - 字体加载
HTML Drag and Drop API - 拖放
Network Information API - 网络信息
Page Lifecycle API - 页面生命周期
Reporting API - 报告
Resize Observer API - 监测元素尺寸变化
User Timing API - 用户计时
Web Crypto API - 加密
WebGL 2.0 API - WebGL 2.0绘图
Web Storage API - 存储数据
Credential Management API - 凭证管理
Crypto Subtle API - 加密
Fetch API - 网络请求
Geolocation API - 地理位置
Network Information API - 网络信息
Payment Request API - 支付请求
Speech Synthesis API - 语音合成
Web Authn API - Web认证
WebRTC API - 实时通信
WebSockets API - 双向通信
WebVR API - 虚拟现实
WebXR Device API - 增强现实设备
DeviceOrientation API - 设备方向
DeviceMotion API - 设备运动
Background Sync API - 后台同步
Ambient Light Sensor API - 环境光传感器
Animation API - 动画效果
Indexed DB API - IndexedDB数据库

1. DOM Manipulation APIs

document.getElementById

// 获取ID为'myElement'的元素,并将其文本颜色设置为红色
let element = document.getElementById('myElement');
element.style.color = 'red';
document.querySelector

// 获取第一个类名为'myClass'的元素,并将其背景颜色设置为黄色
let element = document.querySelector('.myClass');
element.style.backgroundColor = 'yellow';
document.createElement

// 创建一个新的div元素,并设置其文本内容为'Hello, World!',然后将其添加到文档的body中
let newElement = document.createElement('div');
newElement.textContent = 'Hello, World!';
document.body.appendChild(newElement);
element.appendChild

// 获取ID为'parent'的元素,并创建一个新的div元素,然后将其添加为'parent'元素的子元素
let parent = document.getElementById('parent');
let child = document.createElement('div');
parent.appendChild(child);
element.removeChild

// 获取ID为'parent'的元素和ID为'child'的元素,然后从'parent'元素中移除'child'元素
let parent = document.getElementById('parent');
let child = document.getElementById('child');
parent.removeChild(child);
element.setAttribute

// 获取ID为'myElement'的元素,并设置其'data-id'属性为'123'
let element = document.getElementById('myElement');
element.setAttribute('data-id', '123');
element.innerHTML

// 获取ID为'myElement'的元素,并将其内容设置为一个新的段落
let element = document.getElementById('myElement');
element.innerHTML = '<p>New content</p>';

2. Event APIs

element.addEventListener

// 获取ID为'myButton'的按钮元素,并为其添加点击事件监听器,当按钮被点击时弹出提示框
let button = document.getElementById('myButton');
button.addEventListener('click', function() {
    alert('Button clicked!');
});
element.removeEventListener

// 定义一个事件处理函数,并将其绑定到ID为'myButton'的按钮的点击事件上,然后移除该事件监听器
let handler = function() {
    alert('Button clicked!');
};
let button = document.getElementById('myButton');
button.addEventListener('click', handler);
button.removeEventListener('click', handler);
window.onload

// 当页面完全加载后,输出'Page loaded'到控制台
window.onload = function() {
    console.log('Page loaded');
};
window.onresize

// 当窗口大小改变时,输出'Window resized'到控制台
window.onresize = function() {
    console.log('Window resized');
};
element.onclick

// 获取ID为'myButton'的按钮元素,并为其设置点击事件处理函数,当按钮被点击时弹出提示框
let button = document.getElementById('myButton');
button.onclick = function() {
    alert('Button clicked!');
};
element.onmouseover

// 获取ID为'myElement'的元素,并为其设置鼠标悬停事件处理函数,当鼠标悬停在元素上时将其背景颜色设置为蓝色
let element = document.getElementById('myElement');
element.onmouseover = function() {
    element.style.backgroundColor = 'blue';
};
element.onkeydown

// 为整个文档设置键盘按键按下事件处理函数,当任意键被按下时输出按键信息到控制台
document.onkeydown = function(event) {
    console.log('Key pressed: ' + event.key);
};

3. Storage APIs

localStorage

// 将键值对'username'和'JohnDoe'存储到localStorage中,然后获取并输出该值
localStorage.setItem('username', 'JohnDoe');
let username = localStorage.getItem('username');
console.log(username); // Output: JohnDoe
sessionStorage

// 将键值对'token'和'abc123'存储到sessionStorage中,然后获取并输出该值
sessionStorage.setItem('token', 'abc123');
let token = sessionStorage.getItem('token');
console.log(token); // Output: abc123
IndexedDB

// 打开或创建一个名为'myDatabase'的数据库,版本号为1,并在数据库升级时创建一个名为'customers'的对象存储
let request = indexedDB.open('myDatabase', 1);
request.onupgradeneeded = function(event) {
    let db = event.target.result;
    let objectStore = db.createObjectStore('customers', { keyPath: 'id' });
};

4. Network APIs

fetch

// 使用fetch API发送一个GET请求到'https://api.example.com/data',并将返回的JSON数据输出到控制台
fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => console.log(data));
XMLHttpRequest

// 使用XMLHttpRequest发送一个GET请求到'https://api.example.com/data',并在请求成功时输出响应文本到控制台
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText);
    }
};
xhr.send();
WebSocket

// 创建一个新的WebSocket连接到'ws://example.com/socket',在连接打开时发送消息'Hello Server!',并在接收到服务器消息时输出消息内容到控制台
let socket = new WebSocket('ws://example.com/socket');
socket.onopen = function() {
    socket.send('Hello Server!');
};
socket.onmessage = function(event) {
    console.log('Message from server: ' + event.data);
};

5. Geolocation APIs

navigator.geolocation.getCurrentPosition

// 获取用户当前的地理位置,并在成功获取时输出纬度和经度到控制台
navigator.geolocation.getCurrentPosition(function(position) {
    console.log('Latitude: ' + position.coords.latitude);
    console.log('Longitude: ' + position.coords.longitude);
});
navigator.geolocation.watchPosition

// 持续监视用户的地理位置变化,并在每次位置变化时输出新的纬度和经度到控制台
let watchId = navigator.geolocation.watchPosition(function(position) {
    console.log('Latitude: ' + position.coords.latitude);
    console.log('Longitude: ' + position.coords.longitude);
});

6. History APIs

history.back

// 返回到浏览器历史记录中的上一页
history.back();

7. Canvas APIs

CanvasRenderingContext2D

// 获取ID为'myCanvas'的canvas元素,并获取其2D绘图上下文,然后在画布上绘制一个红色的矩形
let canvas = document.getElementById('myCanvas');
let ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 100);
WebGLRenderingContext

// 获取ID为'myCanvas'的canvas元素,并获取其WebGL绘图上下文,然后清空画布并设置背景颜色
let canvas = document.getElementById('myCanvas');
let gl = canvas.getContext('webgl');
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);

8. Audio/Video APIs

HTMLMediaElement

// 获取ID为'myVideo'的视频元素,并播放该视频
let video = document.getElementById('myVideo');
video.play();
Web Audio API

// 创建一个新的音频上下文,并加载一个音频文件,然后播放该音频
let audioContext = new (window.AudioContext || window.webkitAudioContext)();
let audioElement = document.getElementById('myAudio');
let track = audioContext.createMediaElementSource(audioElement);
track.connect(audioContext.destination);
audioElement.play();

9. Device APIs

Notification API

// 请求用户授权显示通知,然后在授权通过后显示一个通知
if (Notification.permission === 'granted') {
    new Notification('Hello', { body: 'This is a notification' });
} else if (Notification.permission !== 'denied') {
    Notification.requestPermission().then(permission => {
        if (permission === 'granted') {
            new Notification('Hello', { body: 'This is a notification' });
        }
    });
}
Vibration API

// 使设备振动1000毫秒
navigator.vibrate(1000);
Battery Status API

// 获取设备的电池状态,并在电池状态变化时输出电池电量到控制台
navigator.getBattery().then(battery => {
    console.log('Battery level: ' + battery.level * 100 + '%');
    battery.onlevelchange = function() {
        console.log('Battery level changed: ' + battery.level * 100 + '%');
    };
});

10. Clipboard APIs

Clipboard API

// 将文本'Hello, World!'写入剪贴板
navigator.clipboard.writeText('Hello, World!').then(() => {
    console.log('Text copied to clipboard');
});

11. Performance APIs

Performance API

// 获取当前时间戳,并输出到控制台
let time = performance.now();
console.log('Current time: ' + time);
Navigation Timing API

// 获取页面的加载性能数据,并输出页面加载时间到控制台
let timing = performance.timing;
let loadTime = timing.loadEventEnd - timing.navigationStart;
console.log('Page load time: ' + loadTime + 'ms');
Resource Timing API

// 获取页面上所有资源的加载性能数据,并输出第一个资源的加载时间到控制台
let resources = performance.getEntriesByType('resource');
let firstResource = resources[0];
console.log('First resource load time: ' + firstResource.responseEnd - firstResource.startTime + 'ms');

12. Web Workers

Worker

// 创建一个新的Web Worker,并在Worker中执行一个耗时任务
let worker = new Worker('worker.js');
worker.onmessage = function(event) {
    console.log('Message from worker: ' + event.data);
};
worker.postMessage('Start task');
SharedWorker

// 创建一个新的Shared Worker,并在Worker中执行一个任务
let worker = new SharedWorker('shared-worker.js');
worker.port.onmessage = function(event) {
    console.log('Message from shared worker: ' + event.data);
};
worker.port.postMessage('Start task');

13. Service Workers

ServiceWorker

// 注册一个Service Worker,并在注册成功后输出消息到控制台
if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/service-worker.js').then(registration => {
        console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }).catch(error => {
        console.log('ServiceWorker registration failed: ', error);
    });
}
Cache API

// 打开一个缓存,并添加一个资源到缓存中
caches.open('my-cache').then(cache => {
    cache.add('/index.html');
});

14. File APIs

FileReader

// 创建一个新的FileReader,并读取一个文件的内容,然后在读取完成后输出文件内容到控制台
let fileReader = new FileReader();
fileReader.onload = function(event) {
    console.log('File content: ' + event.target.result);
};
fileReader.readAsText(file);
Blob

// 创建一个新的Blob对象,并将其内容转换为URL,然后在新的窗口中打开该URL
let blob = new Blob(['Hello, World!'], { type: 'text/plain' });
let url = URL.createObjectURL(blob);
window.open(url);
File

// 获取文件输入元素,并在文件选择变化时输出文件名到控制台
let fileInput = document.getElementById('fileInput');
fileInput.onchange = function(event) {
    let file = event.target.files[0];
    console.log('Selected file: ' + file.name);
};

15. Drag and Drop APIs

dragstart

// 获取ID为'draggable'的元素,并为其设置拖动开始事件处理函数,当元素开始被拖动时输出消息到控制台
let draggable = document.getElementById('draggable');
draggable.ondragstart = function(event) {
    console.log('Drag started');
};
dragover

// 获取ID为'dropzone'的元素,并为其设置拖动悬停事件处理函数,当元素被拖动到悬停区域时输出消息到控制台
let dropzone = document.getElementById('dropzone');
dropzone.ondragover = function(event) {
    event.preventDefault();
    console.log('Drag over');
};
drop

// 获取ID为'dropzone'的元素,并为其设置拖放事件处理函数,当元素被拖放到悬停区域时输出消息到控制台
let dropzone = document.getElementById('dropzone');
dropzone.ondrop = function(event) {
    event.preventDefault();
    console.log('Dropped');
};

16. Intersection Observer API

IntersectionObserver

// 创建一个新的IntersectionObserver,并观察ID为'target'的元素,当元素进入或离开视口时输出消息到控制台
let observer = new IntersectionObserver(entries => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            console.log('Element is in view');
        } else {
            console.log('Element is out of view');
        }
    });
});
observer.observe(document.getElementById('target'));

17. Pointer Events API

pointerdown

// 获取ID为'pointerElement'的元素,并为其设置指针按下事件处理函数,当指针按下时输出消息到控制台
let pointerElement = document.getElementById('pointerElement');
pointerElement.onpointerdown = function(event) {
    console.log('Pointer down');
};
pointermove

// 获取ID为'pointerElement'的元素,并为其设置指针移动事件处理函数,当指针移动时输出消息到控制台
let pointerElement = document.getElementById('pointerElement');
pointerElement.onpointermove = function(event) {
    console.log('Pointer move');
};
pointerup

// 获取ID为'pointerElement'的元素,并为其设置指针抬起事件处理函数,当指针抬起时输出消息到控制台
let pointerElement = document.getElementById('pointerElement');
pointerElement.onpointerup = function(event) {
    console.log('Pointer up');
};

18. WebRTC API

RTCPeerConnection

// 创建一个新的RTCPeerConnection,并添加一个本地媒体流
let peerConnection = new RTCPeerConnection();
navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(stream => {
    stream.getTracks().forEach(track => {
        peerConnection.addTrack(track, stream);
    });
});
RTCDataChannel

// 创建一个新的RTCDataChannel,并在通道打开时发送消息'Hello'
let dataChannel = peerConnection.createDataChannel('chat');
dataChannel.onopen = function() {
    dataChannel.send('Hello');
};

19. WebSockets API

WebSocket

// 创建一个新的WebSocket连接到'ws://example.com/socket',在连接打开时发送消息'Hello Server!',并在接收到服务器消息时输出消息内容到控制台
let socket = new WebSocket('ws://example.com/socket');
socket.onopen = function() {
    socket.send('Hello Server!');
};
socket.onmessage = function(event) {
    console.log('Message from server: ' + event.data);
};

20. Payment Request API

PaymentRequest

// 创建一个新的PaymentRequest对象,并显示支付请求界面
let supportedPaymentMethods = [
    { supportedMethods: 'basic-card' }
];
let paymentDetails = {
    total: { label: 'Total', amount: { currency: 'USD', value: '10.00' } }
};
let request = new PaymentRequest(supportedPaymentMethods, paymentDetails);
request.show().then(response => {
    console.log('Payment successful');
    response.complete('success');
}).catch(error => {
    console.log('Payment failed: ' + error);
});

21. Fullscreen API

requestFullscreen

// 获取ID为'myElement'的元素,并请求全屏显示
let element = document.getElementById('myElement');
element.requestFullscreen();
exitFullscreen

// 退出全屏模式
document.exitFullscreen();

22. Page Visibility API

visibilitychange

// 监听页面的可见性变化事件
document.addEventListener('visibilitychange', function () {
    if (document.visibilityState === 'visible') {
        console.log('页面可见');
    } else {
        console.log('页面不可见');
    }
});

23. Web Authentication API

navigator.credentials.create

// 创建一个新的凭据对象
navigator.credentials.create({
    publicKey: {
        challenge: new Uint8Array([/* challenge */]),
        rp: { name: 'Example Corp' },
        user: {
            id: new Uint8Array([/* user id */]),
            name: 'user@example.com',
            displayName: 'John Doe'
        },
        pubKeyCredParams: [{ type: 'public-key', alg: -7 }]
    }
}).then(credential => {
    console.log('Credential created');
}).catch(error => {
    console.log('Credential creation failed: ' + error);
});



navigator.credentials.get

// 获取现有的凭据对象
navigator.credentials.get({
    publicKey: {
        challenge: new Uint8Array([/* challenge */]),
        allowCredentials: [{ type: 'public-key', id: new Uint8Array([/* credential id */]) }]
    }
}).then(credential => {
    console.log('Credential retrieved');
}).catch(error => {
    console.log('Credential retrieval failed: ' + error);
});

24. Web Share API

navigator.share

// 分享当前页面
if (navigator.share) {
    navigator.share({
        title: 'Example Page',
        text: 'Check out this example page',
        url: window.location.href
    }).then(() => {
        console.log('Shared successfully');
    }).catch(error => {
        console.log('Sharing failed: ' + error);
    });
}

25. Web Speech API

SpeechRecognition

// 创建一个新的语音识别对象,并开始识别语音
let recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.onresult = function(event) {
    console.log('Recognized speech: ' + event.results[0][0].transcript);
};
recognition.start();
SpeechSynthesis

// 创建一个新的语音合成对象,并朗读文本'Hello, World!'
let synth = window.speechSynthesis;
let utterance = new SpeechSynthesisUtterance('Hello, World!');
synth.speak(utterance);

26. Web Storage API

localStorage

// 将键值对'username'和'JohnDoe'存储到localStorage中,然后获取并输出该值
localStorage.setItem('username', 'JohnDoe');
let username = localStorage.getItem('username');
console.log(username); // Output: JohnDoe
sessionStorage

// 将键值对'token'和'abc123'存储到sessionStorage中,然后获取并输出该值
sessionStorage.setItem('token', 'abc123');
let token = sessionStorage.getItem('token');
console.log(token); // Output: abc123

27. WebVR API

navigator.xr

// 检查是否支持WebXR API
if (navigator.xr) {
    navigator.xr.isSessionSupported('immersive-vr').then(supported => {
        if (supported) {
            console.log('WebXR VR supported');
        } else {
            console.log('WebXR VR not supported');
        }
    });
}

28. WebXR API

navigator.xr.requestSession

// 请求一个新的WebXR会话
navigator.xr.requestSession('immersive-vr').then(session => {
    console.log('WebXR session started');
    // 在这里添加WebXR会话的初始化
});

29. Media Session API

navigator.mediaSession

// 设置当前媒体的元数据和操作
if ('mediaSession' in navigator) {
    navigator.mediaSession.metadata = new MediaMetadata({
        title: 'Song Title',
        artist: 'Artist Name',
        album: 'Album Name',
        artwork: [
            { src: 'cover.jpg', sizes: '96x96', type: 'image/jpeg' }
        ]
    });
    navigator.mediaSession.setActionHandler('play', () => {
        console.log('Play button pressed');
    });
    navigator.mediaSession.setActionHandler('pause', () => {
        console.log('Pause button pressed');
    });
}
  1. Picture-in-Picture API
requestPictureInPicture

// 获取视频元素并请求画中画模式
let video = document.getElementById('myVideo');
video.requestPictureInPicture().then(() => {
    console.log('Entered Picture-in-Picture mode');
});
exitPictureInPicture

// 退出画中画模式
document.exitPictureInPicture().then(() => {
    console.log('Exited Picture-in-Picture mode');
});

31. Wake Lock API

navigator.wakeLock

// 请求屏幕唤醒锁
if ('wakeLock' in navigator) {
    navigator.wakeLock.request('screen').then(() => {
        console.log('Wake lock acquired');
    }).catch(err => {
        console.error('Wake lock request failed: ', err);
    });
}

32. Web Bluetooth API

navigator.bluetooth.requestDevice

// 请求连接蓝牙设备
navigator.bluetooth.requestDevice({
    filters: [{ services: ['battery_service'] }]
}).then(device => {
    console.log('Device selected: ' + device.name);
}).catch(error => {
    console.log('Bluetooth device request failed: ' + error);
});

33. Web NFC API

navigator.nfc.watch

// 监听NFC标签
if ('nfc' in navigator) {
    navigator.nfc.watch(message => {
        console.log('NFC message received: ', message);
    }).then(() => {
        console.log('NFC watch started');
    }).catch(error => {
        console.log('NFC watch failed: ' + error);
    });
}

34. WebUSB API

navigator.usb.requestDevice

// 请求连接USB设备
navigator.usb.requestDevice({ filters: [] }).then(device => {
    console.log('USB device selected: ' + device.productName);
}).catch(error => {
    console.log('USB device request failed: ' + error);
});

35. Web Animations API

element.animate

// 对元素进行动画处理
let element = document.getElementById('myElement');
element.animate([
    { transform: 'translateX(0px)' },
    { transform: 'translateX(100px)' }
], {
    duration: 1000,
    iterations: Infinity
});

36. Resize Observer API

ResizeObserver

// 监听元素的大小变化
let observer = new ResizeObserver(entries => {
    for (let entry of entries) {
        console.log('Element size changed: ', entry.contentRect);
    }
});
observer.observe(document.getElementById('myElement'));

37. Mutation Observer API

MutationObserver

// 监听DOM变化
let observer = new MutationObserver(mutations => {
    mutations.forEach(mutation => {
        console.log('DOM mutation: ', mutation);
    });
});
observer.observe(document.body, {
    childList: true,
    subtree: true
});

38. Performance Timeline API

performance.getEntries

// 获取性能时间线数据
let entries = performance.getEntries();
entries.forEach(entry => {
    console.log('Performance entry: ', entry);
});

39. User Timing API

performance.mark

// 标记性能时间点
performance.mark('startTask');
// 执行一些任务
performance.mark('endTask');
performance.measure('task', 'startTask', 'endTask');
let measures = performance.getEntriesByName('task');
console.log('Task duration: ' + measures[0].duration + 'ms');

40. High Resolution Time API

performance.now

// 获取高精度时间戳
let startTime = performance.now();
// 执行一些任务
let endTime = performance.now();
console.log('Task duration: ' + (endTime - startTime) + 'ms');

41. Broadcast Channel API

BroadcastChannel

// 创建或加入一个广播频道
let channel = new BroadcastChannel('myChannel');
channel.onmessage = function(event) {
    console.log('Message received: ' + event.data);
};
channel.postMessage('Hello, World!');

42. Credential Management API

navigator.credentials.get

// 获取凭据信息
navigator.credentials.get({
    password: true
}).then(credential => {
    if (credential) {
        console.log('Credential retrieved: ', credential);
    } else {
        console.log('No credential available');
    }
}).catch(error => {
    console.log('Credential retrieval failed: ' + error);
});

43. Payment Handler API

registerPaymentHandler

// 注册一个支付处理程序
if ('PaymentRequest' in window) {
    navigator.registerProtocolHandler('web+payment', 'https://example.com/pay?amount=%s', 'My Payment Handler');
}

44. Periodic Background Sync API

navigator.serviceWorker.ready

// 注册周期性后台同步
navigator.serviceWorker.ready.then(registration => {
    registration.periodicSync.register({
        tag: 'fetch-news',
        minInterval: 24 * 60 * 60 * 1000 // 每天一次
    }).then(() => {
        console.log('Periodic sync registered');
    }).catch(error => {
        console.log('Periodic sync registration failed: ' + error);
    });
});

45. Permissions API

navigator.permissions.query

// 查询权限状态
navigator.permissions.query({ name: 'geolocation' }).then(result => {
    if (result.state === 'granted') {
        console.log('Geolocation permission granted');
    } else if (result.state === 'prompt') {
        console.log('Geolocation permission prompt');
    } else {
        console.log('Geolocation permission denied');
    }
});

46. Push API

registration.pushManager.subscribe

// 订阅推送通知
navigator.serviceWorker.ready.then(registration => {
    registration.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: new Uint8Array([/* VAPID key */])
    }).then(subscription => {
        console.log('Push subscription: ', subscription);
    }).catch(error => {
        console.log('Push subscription failed: ' + error);
    });
});

47. Screen Capture API

navigator.mediaDevices.getDisplayMedia

// 获取屏幕共享流
navigator.mediaDevices.getDisplayMedia({ video: true }).then(stream => {
    let video = document.getElementById('myVideo');
    video.srcObject = stream;
}).catch(error => {
    console.log('Screen capture failed: ' + error);
});

48. Sensor APIs

Accelerometer

// 获取加速度传感器数据
if ('Accelerometer' in window) {
    let accelerometer = new Accelerometer({ frequency: 60 });
    accelerometer.onreading = () => {
        console.log('Acceleration along X-axis: ' + accelerometer.x);
        console.log('Acceleration along Y-axis: ' + accelerometer.y);
        console.log('Acceleration along Z-axis: ' + accelerometer.z);
    };
    accelerometer.start();
}

49. Storage Access API

document.requestStorageAccess

// 请求存储访问权限
document.requestStorageAccess().then(() => {
    console.log('Storage access granted');
}).catch(error => {
    console.log('Storage access request failed: ' + error);
});

50. Task Scheduler API

navigator.scheduling.isInputPending

// 检查是否有未处理的输入事件
if ('scheduling' in navigator) {
    setInterval(() => {
        if (navigator.scheduling.isInputPending()) {
            console.log('There are pending input events');
        } else {
            console.log('No pending input events');
        }
    }, 1000);
}

51. WebHID API

navigator.hid.requestDevice

// 请求连接HID设备
navigator.hid.requestDevice({ filters: [] }).then(devices => {
    if (devices.length === 0) {
        console.log('No HID devices selected');
        return;
    }
    let device = devices[0];
    console.log('HID device selected: ' + device.productName);
}).catch(error => {
    console.log('HID device request failed: ' + error);
});

52. WebOTP API

navigator.credentials.get

// 获取OTP凭据
if ('OTPCredential' in window) {
    navigator.credentials.get({
        otp: { transport: ['sms'] }
    }).then(otp => {
        console.log('OTP received: ' + otp.code);
    }).catch(error => {
        console.log('OTP retrieval failed: ' + error);
    });
}

53. Web Serial API

navigator.serial.requestPort

// 请求连接串口设备
navigator.serial.requestPort().then(port => {
    console.log('Serial port selected');
    return port.open({ baudRate: 9600 });
}).then(port => {
    console.log('Serial port opened');
}).catch(error => {
    console.log('Serial port request failed: ' + error);
});

54. Web Share Target API

registerWebApp

// 注册Web应用为分享目标
if ('registerProtocolHandler' in navigator) {
    navigator.registerProtocolHandler('web+share', 'https://example.com/share?title=%s&text=%s&url=%s', 'My Share Target');
}

55. Web Speech Grammar API

SpeechGrammarList

// 创建一个语音语法列表
let speechRecognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
let speechGrammarList = new (window.SpeechGrammarList || window.webkitSpeechGrammarList)();
let grammar = '#JSGF V1.0; grammar colors; public <color> = red | green | blue ;';
speechGrammarList.addFromString(grammar, 1);
speechRecognition.grammars = speechGrammarList;
speechRecognition.onresult = function(event) {
    console.log('Recognized speech: ' + event.results[0][0].transcript);
};
speechRecognition.start();

56. Web Speech Recognition API

SpeechRecognition

// 创建一个新的语音识别对象,并开始识别语音
let recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.onresult = function(event) {
    console.log('Recognized speech: ' + event.results[0][0].transcript);
};
recognition.start();

57. Web Speech Synthesis API

SpeechSynthesis

// 创建一个新的语音合成对象,并朗读文本'Hello, World!'
let synth = window.speechSynthesis;
let utterance = new SpeechSynthesisUtterance('Hello, World!');
synth.speak(utterance);

58. WebTransport API

WebTransport

// 创建一个新的WebTransport连接
let transport = new WebTransport('https://example.com/transport');
transport.ready.then(() => {
    console.log('WebTransport connection established');
}).catch(error => {
    console.log('WebTransport connection failed: ' + error);
});

59. WebAssembly API

WebAssembly.compile

// 编译WebAssembly模块
fetch('module.wasm').then(response =>
    response.arrayBuffer()
).then(bytes =>
    WebAssembly.compile(bytes)
).then(module => {
    console.log('WebAssembly module compiled');
}).catch(error => {
    console.log('WebAssembly compilation failed: ' + error);
});

60. Web Locks API

navigator.locks.request

// 请求一个锁
navigator.locks.request('my-lock', lock => {
    console.log('Lock acquired');
    return new Promise(resolve => {
        setTimeout(() => {
            console.log('Lock released');
            resolve();
        }, 1000);
    });
}).catch(error => {
    console.log('Lock request failed: ' + error);
});

61. Performance Observer API

navigator.credentials.create

// 创建一个新的凭据对象
navigator.credentials.create({
    publicKey: {
        challenge: new Uint8Array([/* challenge */]),
        rp: { name: 'Example Corp' },
        user: {
            id: new Uint8Array([/* user id */]),
            name: 'user@example.com',
            displayName: 'John Doe'
        },
        pubKeyCredParams: [{ type: 'public-key', alg: -7 }]
    }
}).then(credential => {
    console.log('Credential created');
}).catch(error => {
    console.log('Credential creation failed: ' + error);
});

62. Web MIDI API

navigator.requestMIDIAccess

// 请求MIDI访问权限
navigator.requestMIDIAccess().then(midiAccess => {
    console.log('MIDI access granted');
    let inputs = midiAccess.inputs;
    let outputs = midiAccess.outputs;
    inputs.forEach(input => {
        input.onmidimessage = function(message) {
            console.log('MIDI message received: ', message.data);
        };
    });
}).catch(error => {
    console.log('MIDI access request failed: ' + error);
});

63. Web NFC API

navigator.nfc.watch

// 监听NFC标签
if ('nfc' in navigator) {
    navigator.nfc.watch(message => {
        console.log('NFC message received: ', message);
    }).then(() => {
        console.log('NFC watch started');
    }).catch(error => {
        console.log('NFC watch failed: ' + error);
    });
}

64. WebRTC Data Channels

RTCPeerConnection

// 创建一个新的RTCPeerConnection,并添加一个本地媒体流
let peerConnection = new RTCPeerConnection();
navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(stream => {
    stream.getTracks().forEach(track => {
        peerConnection.addTrack(track, stream);
    });
});

RTCDataChannel

// 创建一个新的RTCDataChannel,并在通道打开时发送消息'Hello'
let dataChannel = peerConnection.createDataChannel('chat');
dataChannel.onopen = function() {
    dataChannel.send('Hello');
};

65. File System Access API

window.showOpenFilePicker

// 打开文件选择器以访问用户的文件
window.showOpenFilePicker().then(fileHandles => {
    console.log('Files selected:', fileHandles);
    return fileHandles[0].getFile();
}).then(file => {
    console.log('File name:', file.name);
    console.log('File size:', file.size);
}).catch(error => {
    console.log('File access failed:', error);
});

66. Wake Lock API

navigator.wakeLock.request

// 请求屏幕唤醒锁
if ('wakeLock' in navigator) {
    navigator.wakeLock.request('screen').then(() => {
        console.log('Wake lock acquired');
    }).catch(error => {
        console.log('Wake lock request failed:', error);
    });
}

67. WebAssembly Memory API

WebAssembly.Memory

// 创建一个新的WebAssembly内存对象
let memory = new WebAssembly.Memory({ initial: 10, maximum: 100 });
console.log('WebAssembly memory created');

68. WebAssembly Table API

WebAssembly.Table

// 创建一个新的WebAssembly表对象
let table = new WebAssembly.Table({ initial: 2, element: 'anyfunc' });
console.log('WebAssembly table created');

69. WebAssembly Global API

WebAssembly.Global

// 创建一个新的WebAssembly全局对象
let global = new WebAssembly.Global({ value: 'i32', mutable: true }, 42);
console.log('WebAssembly global created');

70. WebAssembly Module API

WebAssembly.Module

// 编译WebAssembly模块
fetch('module.wasm').then(response =>
    response.arrayBuffer()
).then(bytes =>
    WebAssembly.compile(bytes)
).then(module => {
    console.log('WebAssembly module compiled');
}).catch(error => {
    console.log('WebAssembly compilation failed: ' + error);
});

71. Audio Worklet API

AudioWorklet

// 创建并使用一个音频处理节点
let audioContext = new AudioContext();
audioContext.audioWorklet.addModule('processor.js').then(() => {
    let node = new AudioWorkletNode(audioContext, 'my-processor');
    console.log('AudioWorkletNode created');
});

72. Beacon API

navigator.sendBeacon

// 使用Beacon API发送异步请求
let data = new Blob(['Hello, World!'], { type: 'text/plain' });
navigator.sendBeacon('/log', data);
console.log('Beacon sent');

73. Font Loading API

document.fonts.load

// 加载字体并使用
document.fonts.load('12px "My Font"').then(() => {
    console.log('Font loaded');
});

74. HTML Drag and Drop API

draggable

// 设置一个元素为可拖动的
let element = document.getElementById('myElement');
element.draggable = true;
element.ondragstart = function(event) {
    event.dataTransfer.setData('text/plain', 'This is a draggable element');
};

75. Network Information API

navigator.connection

// 检查网络连接的信息
let connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
console.log('Connection type: ' + connection.effectiveType);

76. Page Lifecycle API

document.addEventListener('visibilitychange', function () {
    // 在页面隐藏和显示时做出响应
    if (document.visibilityState === 'hidden') {
        console.log('Page is hidden');
    } else {
        console.log('Page is visible');
    }
});

77. Reporting API

reportingObserver

// 创建一个新的ReportingObserver
let observer = new ReportingObserver((reports, observer) => {
    reports.forEach(report => {
        console.log('Report type: ' + report.type);
    });
});
observer.observe();

78. Resize Observer API

ResizeObserver

// 监测元素大小变化
let resizeObserver = new ResizeObserver(entries => {
    for (let entry of entries) {
        console.log('Resized: ', entry.target);
    }
});
resizeObserver.observe(document.body);

79. User Timing API

performance.mark

// 标记和测量性能
performance.mark('myStartMark');
// 执行一些任务
performance.mark('myEndMark');
performance.measure('myMeasure', 'myStartMark', 'myEndMark');

80. Web Crypto API

window.crypto

// 生成加密随机数
let array = new Uint32Array(10);
window.crypto.getRandomValues(array);
console.log('Random values: ', array);

81. WebGL 2.0 API

canvas.getContext('webgl2')

// 获取WebGL 2.0上下文
let canvas = document.createElement('canvas');
let gl = canvas.getContext('webgl2');
if (gl) {
    console.log('WebGL 2.0 context obtained');
}

82. Web Storage API

localStorage.setItem

// 在localStorage中存储和检索数据
localStorage.setItem('myKey', 'myValue');
let value = localStorage.getItem('myKey');
console.log('Stored value: ', value);

83. Credential Management API

navigator.credentials.store

// 存储凭据
let cred = new PasswordCredential({
    id: 'user@example.com',
    password: 'password123',
    name: 'Example User'
});
navigator.credentials.store(cred).then(() => {
    console.log('Credential stored');
});

84. Crypto Subtle API

crypto.subtle.digest

// 计算数据的哈希值
let data = new TextEncoder().encode('Hello, world!');
crypto.subtle.digest('SHA-256', data).then(hash => {
    console.log('Hash: ', new Uint8Array(hash));
});

85. Fetch API

fetch

// 使用Fetch API发起网络请求
fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => console.log('Data: ', data));

86. Geolocation API

navigator.geolocation.getCurrentPosition

// 获取当前位置
navigator.geolocation.getCurrentPosition(position => {
    console.log('Latitude: ', position.coords.latitude);
    console.log('Longitude: ', position.coords.longitude);
});

87. Network Information API

navigator.connection

// 检查网络连接速度
let connection = navigator.connection;
console.log('Connection effective type: ', connection.effectiveType);

88. Payment Request API

PaymentRequest

// 创建新的支付请求
let request = new PaymentRequest([{ supportedMethods: 'basic-card' }], { total: { label: 'Total', amount: { currency: 'USD', value: '10.00' }}});
request.show().then(response => {
    console.log('Payment successful');
    response.complete('success');
});

89. Speech Synthesis API

speechSynthesis

// 合成并播放语音
let utterance = new SpeechSynthesisUtterance('Hello, world!');
window.speechSynthesis.speak(utterance);

90. Web Authn API

navigator.credentials.create

// 创建Web Authn凭证
navigator.credentials.create({ publicKey: {...} }).then(cred => {
    console.log('Credential created');
});

91. WebRTC API

RTCPeerConnection

// 创建WebRTC对等连接
let pc = new RTCPeerConnection();
pc.onicecandidate = event => {
    if (event.candidate) {
        console.log('ICE candidate: ', event.candidate);
    }
};

92. WebSockets API

WebSocket

// 连接到WebSocket服务器
let ws = new WebSocket('ws://example.com/socket');
ws.onopen = () => ws.send('Hello, server!');
ws.onmessage = event => console.log('Message from server: ', event.data);

93. WebVR API

navigator.getVRDisplays

// 获取VR显示设备
navigator.getVRDisplays().then(displays => {
    if (displays.length > 0) {
        console.log('VR displays available');
    } else {
        console.log('No VR displays found');
    }
});

94. WebXR Device API

navigator.xr.requestDevice

// 请求WebXR设备
navigator.xr.requestDevice().then(device => {
    console.log('XR device requested');
});

95. DeviceOrientation API

window.addEventListener('deviceorientation', event => {
    console.log('Alpha: ', event.alpha);
    console.log('Beta: ', event.beta);
    console.log('Gamma: ', event.gamma);
});

96. DeviceMotion API

window.addEventListener('devicemotion', event => {
    console.log('Acceleration: ', event.acceleration);
    console.log('Acceleration with gravity: ', event.accelerationIncludingGravity);
});

97. Background Sync API

navigator.serviceWorker.ready.then(registration => {
    return registration.sync.register('mySync');
}).then(() => {
    console.log('Sync registered');
});

98. Ambient Light Sensor API

let sensor = new AmbientLightSensor();
sensor.onreading = () => {
    console.log('Current light level: ', sensor.illuminance);
};
sensor.start();

99. Animation API

element.animate

// 创建元素动画
element.animate([
    { transform: 'translateY(0px)' },
    { transform: 'translateY(-10px)' }
], {
    duration: 500,
    iterations: Infinity
});

100. Indexed DB API

indexedDB.open

// Open an IndexedDB database
let request = indexedDB.open('myDatabase', 1);
request.onupgradeneeded = function(event) {
    let db = event.target.result;
    db.createObjectStore('myStore', { keyPath: 'id' });
};
request.onsuccess = function(event) {
    console.log('Database opened');
};
  • 18
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值