文章首先介绍了JavaScript Web API的概念,解释了它们是如何扩展网站功能并提供丰富用户体验的。接着,文章列举了14个令人兴奋的API,并详细描述了它们的特点和用法。
这些API包括:
Web Speech API:允许网站实现语音识别和语音合成功能。 Web Bluetooth API:通过蓝牙技术连接和控制外部设备。 WebVR API:为虚拟现实(VR)提供支持,使网站能够与VR设备进行交互。 WebUSB API:允许网站与USB设备进行通信和交互。 WebRTC API:提供实时音视频通信功能,支持网页间的实时数据传输。 Web Animations API:用于创建复杂和流畅的动画效果。 Web Speech Synthesis API:提供语音合成功能,让网站能够生成语音输出。
1. Screen Capture API
屏幕捕获API正如其名,允许我们捕获屏幕内容,使构建屏幕录制器的过程变得轻而易举。我们需要一个视频元素来显示捕获的屏幕。开始按钮将启动屏幕捕获。
const previewElem = document.getElementById("preview");const startBtn = document.getElementById("start");asyncfunctionstartRecording() {previewElem.srcObject =await navigator.mediaDevices.getDisplayMedia({video:true,audio:true,});}startBtn.addEventListener("click", startRecording);
2. Web Share API
Web Share API允许我们将文本、链接甚至文件从网页分享到设备上安装的其他应用程序。
asyncfunctionshareHandler() {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 检测元素何时进入或离开视口,这对于实现无限滚动非常有用。
4. Clipboard API
剪贴板 API 允许我们读取和写入剪贴板中的数据。这对于实现复制到剪贴板的功能非常有用。
asyncfunctioncopyHandler() {const text ="https://tapajyoti-bose.vercel.app/";navigator.clipboard.writeText(text);}
5. Screen Wake Lock API
你是否曾经想过YouTube是如何在播放视频时防止屏幕关闭的?这是因为使用了屏幕保持唤醒(Screen Wake Lock)API。
letwakeLock = null;asyncfunctionlockHandler() {wakeLock = await navigator.wakeLock.request("screen");}asyncfunctionreleaseHandler() {await wakeLock.release();wakeLock = null;}
注意:只有在页面已经在屏幕上可见的情况下,才能使用屏幕唤醒锁定API。否则,会抛出错误。
6. Screen Orientation API
Screen Orientation API 检查当前屏幕的方向,甚至将其锁定为特定的方向。
asyncfunctionlockHandler() {await screen.orientation.lock("portrait");}functionreleaseHandler() {screen.orientation.unlock();}functiongetOrientation() {returnscreen.orientation.type;}
7. Fullscreen API
Fullscreen API 在全屏模式下显示一个元素或整个页面。
asyncfunctionenterFullscreen() {await document.documentElement.requestFullscreen();}asyncfunctionexitFullscreen() {await document.exitFullscreen();}
注意:要使用全屏API,需要用户的交互。
8.Web Speech
Web Speech API 可以让你将语音数据整合到网络应用中。Web Speech API 由两个部分组成:SpeechSynthesis
(文本转语音)和SpeechRecognition
(异步语音识别)。
// Speech Synthesisconst synth = window.speechSynthesis;const utterance = new SpeechSynthesisUtterance("Hello World");synth.speak(utterance);// Speech Recognitionconst 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%的覆盖率,但语音识别在生产中的使用还为时尚早,只有86%的覆盖率。
API 不能在没有用户交互的情况下使用(例如: click , keypress 等)
9.Page Visibility
页面可见性 API 允许我们检查页面对用户是否可见。当你想要暂停视频时,这非常有用。有两种方法来进行此检查:
// Method 1document.addEventListener("visibilitychange", () => {if(document.visibilityState ==="visible") {document.title ="Visible";return;}document.title ="Not Visible";});// Method 2window.addEventListener("blur", () => {document.title ="Not Visible";});window.addEventListener("focus", () => {document.title ="Visible";});
两种方法的区别在于,第二种方法将在您切换到另一个应用程序或不同的标签时触发,而第一种方法只会在我们切换到另一个标签时触发。
10. Accelerometer
加速度计API允许我们访问设备的加速度数据。这可以用来创建使用设备的动作控制或者在用户摇动设备时添加交互的游戏,可能性无限!
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 允许我们访问用户的位置。如果你正在构建与地图或基于位置的服务相关的任何内容,这将非常有用。
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应用程序的主执行线程分离的后台线程中运行脚本操作成为可能。这样做的好处是可以在一个独立的线程中执行繁重的处理,使得主线程(通常是UI线程)能够在没有被阻塞/减慢的情况下运行。
// main.jsconst worker = new Worker("worker.js");worker.onmessage = (e) => console.log(e.data);worker.postMessage([5, 3]);// worker.jsonmessage = (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 elements new dimensions});observer.observe(sidebar);
14.Notification
Notification API,顾名思义,允许您发送通知以打扰用户(与页面可见性 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仍处于实验阶段,并不被所有浏览器支持。因此,如果您想在生产环境中使用它们,应该先检查浏览器是否支持。
if("SpeechRecognition"inwindow ||"webkitSpeechRecognition"inwindow) {// Speech Recognition is supported}
欢迎长按图片加刷碗智为好友,定时分享 Vue React Ts 等。
最后: