未來網(wǎng)站開發(fā)必備:14個讓你驚艷的JavaScript Web API!
終于上線啦,有好多好玩的模型,包括最近很火的瞬息宇宙 。
文章首先介紹了JavaScript Web API的概念,解釋了它們是如何擴展網(wǎng)站功能并提供豐富用戶體驗的。接著,文章列舉了14個令人興奮的API,并詳細描述了它們的特點和用法。
這些API包括:
Web Speech API:允許網(wǎng)站實現(xiàn)語音識別和語音合成功能。 Web Bluetooth API:通過藍牙技術連接和控制外部設備。 WebVR API:為虛擬現(xiàn)實(VR)提供支持,使網(wǎng)站能夠與VR設備進行交互。 WebUSB API:允許網(wǎng)站與USB設備進行通信和交互。 WebRTC API:提供實時音視頻通信功能,支持網(wǎng)頁間的實時數(shù)據(jù)傳輸。 Web Animations API:用于創(chuàng)建復雜和流暢的動畫效果。 Web Speech Synthesis API:提供語音合成功能,讓網(wǎng)站能夠生成語音輸出。
1、Screen Capture API
屏幕捕獲API正如其名,允許我們捕獲屏幕內(nèi)容,使構建屏幕錄制器的過程變得輕而易舉。我們需要一個視頻元素來顯示捕獲的屏幕。開始按鈕將啟動屏幕捕獲。
<video id="preview" autoplay>
Your browser doesn't support HTML5.
</video>
<button id="start" class="btn">Start</button>
const previewElem = document.getElementById("preview");
const startBtn = document.getElementById("start");
async function startRecording() {
previewElem.srcObject =
await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: true,
});
}
startBtn.addEventListener("click", startRecording);
2、Web Share API
Web Share API允許我們將文本、鏈接甚至文件從網(wǎng)頁分享到設備上安裝的其他應用程序。
async function shareHandler() {
navigator.share({
title: "Tapajyoti Bose | Portfolio",
text: "Check out my website",
url: "https://tapajyoti-bose.vercel.app/",
});
}
注意:要使用Web Share API,需要用戶的交互。例如,按鈕點擊或觸摸事件。
3、Intersection Observer API
Intersection Observer API 檢測元素何時進入或離開視口,這對于實現(xiàn)無限滾動非常有用。
4、Clipboard API
剪貼板 API 允許我們讀取和寫入剪貼板中的數(shù)據(jù)。這對于實現(xiàn)復制到剪貼板的功能非常有用。
async function copyHandler() {
const text = "https://tapajyoti-bose.vercel.app/";
navigator.clipboard.writeText(text);
}
5、Screen Wake Lock API
你是否曾經(jīng)想過YouTube是如何在播放視頻時防止屏幕關閉的?這是因為使用了屏幕保持喚醒(Screen Wake Lock)API。
let wakeLock = null;
async function lockHandler() {
wakeLock = await navigator.wakeLock.request("screen");
}
async function releaseHandler() {
await wakeLock.release();
wakeLock = null;
}
注意:只有在頁面已經(jīng)在屏幕上可見的情況下,才能使用屏幕喚醒鎖定API。否則,會拋出錯誤。
6、Screen Orientation API
Screen Orientation API 檢查當前屏幕的方向,甚至將其鎖定為特定的方向。
async function lockHandler() {
await screen.orientation.lock("portrait");
}
function releaseHandler() {
screen.orientation.unlock();
}
function getOrientation() {
return screen.orientation.type;
}
7、Fullscreen API
Fullscreen API 在全屏模式下顯示一個元素或整個頁面。
async function enterFullscreen() {
await document.documentElement.requestFullscreen();
}
async function exitFullscreen() {
await document.exitFullscreen();
}
注意:要使用全屏API,需要用戶的交互。
8、Web Speech
Web Speech API 可以讓你將語音數(shù)據(jù)整合到網(wǎng)絡應用中。Web Speech API 由兩個部分組成: SpeechSynthesis (文本轉語音)和 SpeechRecognition (異步語音識別)。
// Speech Synthesis
const synth = window.speechSynthesis;
const utterance = new SpeechSynthesisUtterance("Hello World");
synth.speak(utterance);
// Speech Recognition
const SpeechRecognition =
window.SpeechRecognition ?? window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();
recognition.start();
recognition.onresult = (event) => {
const speechToText = event.results[0][0].transcript;
console.log(speechToText);
};
- 盡管語音合成在所有主要瀏覽器上都有96%的覆蓋率,但語音識別在生產(chǎn)中的使用還為時尚早,只有86%的覆蓋率。
- API 不能在沒有用戶交互的情況下使用(例如: click , keypress 等)
9、Page Visibility
頁面可見性 API 允許我們檢查頁面對用戶是否可見。當你想要暫停視頻時,這非常有用。有兩種方法來進行此檢查:
// Method 1
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") {
document.title = "Visible";
return;
}
document.title = "Not Visible";
});
// Method 2
window.addEventListener("blur", () => {
document.title = "Not Visible";
});
window.addEventListener("focus", () => {
document.title = "Visible";
});
兩種方法的區(qū)別在于,第二種方法將在您切換到另一個應用程序或不同的標簽時觸發(fā),而第一種方法只會在我們切換到另一個標簽時觸發(fā)。
10、Accelerometer
加速度計API允許我們訪問設備的加速度數(shù)據(jù)。這可以用來創(chuàng)建使用設備的動作控制或者在用戶搖動設備時添加交互的游戲,可能性無限!
const acl = new Accelerometer({ frequency: 60 });
acl.addEventListener("reading", () => {
const vector = [acl.x, acl.y, acl.z];
const magnitude = Math.sqrt(vector.reduce((s, v) => s + v * v, 0));
if (magnitude > THRESHOLD) {
console.log("I feel dizzy!");
}
});
acl.start();
可以使用以下方式請求加速度計權限:
navigator.permissions.query({ name: "accelerometer" }).then((result) => {
if (result.state === "granted") {
// now you can use accelerometer api
}
});
11、Geo-location
地理定位 API 允許我們訪問用戶的位置。如果你正在構建與地圖或基于位置的服務相關的任何內(nèi)容,這將非常有用。
navigator.geolocation.getCurrentPosition(({ coords }) => {
console.log(coords.latitude, coords.longitude);
});
可以使用以下方式請求地理位置權限:
navigator.permissions.query({ name: "geolocation" }).then((result) => {
if (result.state === "granted") {
// now you can use geolocation api
}
});
12、Web worker
Web Workers 使得在與Web應用程序的主執(zhí)行線程分離的后臺線程中運行腳本操作成為可能。這樣做的好處是可以在一個獨立的線程中執(zhí)行繁重的處理,使得主線程(通常是UI線程)能夠在沒有被阻塞/減慢的情況下運行。
// main.js
const worker = new Worker("worker.js");
worker.onmessage = (e) => console.log(e.data);
worker.postMessage([5, 3]);
// worker.js
onmessage = (e) => {
const [a, b] = e.data;
postMessage(a + b);
};
13、Resize Observer
Resize Observer API 允許我們輕松觀察元素的大小并處理其變化。當你擁有一個可調整大小的側邊欄時,它非常有用。
const sidebar = document.querySelector(".sidebar");
const observer = new ResizeObserver((entries) => {
const sidebar = entries[0];
//Do something with the element's new dimensions
});
observer.observe(sidebar);
14、Notification
Notification API,顧名思義,允許您發(fā)送通知以打擾用戶(與頁面可見性 API 捆綁在一起,以更加打擾他們 ??)
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
new Notification("Hi there!", {
body: "Notification body",
icon: "https://tapajyoti-bose.vercel.app/img/logo.png",
});
}
});
上述提到的一些API仍處于實驗階段,并不被所有瀏覽器支持。因此,如果您想在生產(chǎn)環(huán)境中使用它們,應該先檢查瀏覽器是否支持。
if ("SpeechRecognition" in window || "webkitSpeechRecognition" in window) {
// Speech Recognition is supported