未来网站开发必备:14个让你惊艳的JavaScript Web API!

111 阅读5分钟
微信搜索 【大迁世界】, 我会第一时间和你分享前端行业趋势,学习途径等等。
本文 GitHub github.com/qq449245884… 已收录,有一线大厂面试完整考点、资料以及我的系列文章。

快来免费体验ChatGpt plus版本的,我们出的钱 体验地址:chat.waixingyun.cn 可以加入网站底部技术群,一起找bug,另外新版作图神器已上线 cube.waixingyun.cn/home

文章首先介绍了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正如其名,允许我们捕获屏幕内容,使构建屏幕录制器的过程变得轻而易举。我们需要一个视频元素来显示捕获的屏幕。开始按钮将启动屏幕捕获。

<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);</code></pre><h2 id="item-0-2">2. Web Share API</h2><p>Web Share API允许我们将文本、链接甚至文件从网页分享到设备上安装的其他应用程序。</p><pre><code>async function shareHandler() {
                      navigator.share({
                          title: "Tapajyoti Bose | Portfolio",
                              text: "Check out my website",
                                  url: "https://tapajyoti-bose.vercel.app/",
                                    });
                                    }</code></pre><p>注意:要使用Web Share API,需要用户的交互。例如,按钮点击或触摸事件。</p><h2 id="item-0-3">3. Intersection Observer API</h2><p>Intersection Observer API 检测元素何时进入或离开视口,这对于实现无限滚动非常有用。</p><h2 id="item-0-4">4. Clipboard API</h2><p>剪贴板 API 允许我们读取和写入剪贴板中的数据。这对于实现复制到剪贴板的功能非常有用。</p><pre><code>async function copyHandler() {
                                      const text = "https://tapajyoti-bose.vercel.app/";
                                        navigator.clipboard.writeText(text);
                                        }</code></pre><h2 id="item-0-5">5. Screen Wake Lock API</h2><p>你是否曾经想过YouTube是如何在播放视频时防止屏幕关闭的?这是因为使用了屏幕保持唤醒(Screen Wake Lock)API。</p><pre><code>let wakeLock = null;
                                        
                                        async function lockHandler() {
                                          wakeLock = await navigator.wakeLock.request("screen");
                                          }
                                          
                                          async function releaseHandler() {
                                            await wakeLock.release();
                                              wakeLock = null;
                                              }</code></pre><p>注意:只有在页面已经在屏幕上可见的情况下,才能使用屏幕唤醒锁定API。否则,会抛出错误。</p><h2 id="item-0-6">6. Screen Orientation API</h2><p>Screen Orientation API 检查当前屏幕的方向,甚至将其锁定为特定的方向。</p><pre><code>async function lockHandler() {
                                                await screen.orientation.lock("portrait");
                                                }
                                                
                                                function releaseHandler() {
                                                  screen.orientation.unlock();
                                                  }
                                                  
                                                  function getOrientation() {
                                                    return screen.orientation.type;
                                                    }</code></pre><p></p><h2 id="item-0-7">7. Fullscreen API</h2><p>Fullscreen API 在全屏模式下显示一个元素或整个页面。</p><pre><code>async function enterFullscreen() {
                                                      await document.documentElement.requestFullscreen();
                                                      }
                                                      
                                                      async function exitFullscreen() {
                                                        await document.exitFullscreen();
                                                        }</code></pre><p>注意:要使用全屏API,需要用户的交互。</p><h2 id="item-0-8">8.Web Speech</h2><p>Web Speech API 可以让你将语音数据整合到网络应用中。Web Speech API 由两个部分组成: <code>SpeechSynthesis</code> (文本转语音)和 <code>SpeechRecognition</code> (异步语音识别)。</p><pre><code>// 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) =&gt; {
                                                            const speechToText = event.results[0][0].transcript;
                                                              console.log(speechToText);
                                                              };</code></pre><ol><li>尽管语音合成在所有主要浏览器上都有96%的覆盖率,但语音识别在生产中的使用还为时尚早,只有86%的覆盖率。</li><li>API 不能在没有用户交互的情况下使用(例如: click , keypress 等)</li></ol><h2 id="item-0-9">9.Page Visibility</h2><p>页面可见性 API 允许我们检查页面对用户是否可见。当你想要暂停视频时,这非常有用。有两种方法来进行此检查:</p><pre><code>// Method 1
                                                              document.addEventListener("visibilitychange", () =&gt; {
                                                                if (document.visibilityState === "visible") {
                                                                    document.title = "Visible";
                                                                        return;
                                                                          }
                                                                            document.title = "Not Visible";
                                                                            });
                                                                            
                                                                            // Method 2
                                                                            window.addEventListener("blur", () =&gt; {
                                                                              document.title = "Not Visible";
                                                                              });
                                                                              window.addEventListener("focus", () =&gt; {
                                                                                document.title = "Visible";
                                                                                });</code></pre><p>两种方法的区别在于,第二种方法将在您切换到另一个应用程序或不同的标签时触发,而第一种方法只会在我们切换到另一个标签时触发。</p><h2 id="item-0-10">10. Accelerometer</h2><p>加速度计API允许我们访问设备的加速度数据。这可以用来创建使用设备的动作控制或者在用户摇动设备时添加交互的游戏,可能性无限!</p><pre><code>const acl = new Accelerometer({ frequency: 60 });
                                                                                
                                                                                acl.addEventListener("reading", () =&gt; {
                                                                                  const vector = [acl.x, acl.y, acl.z];
                                                                                    const magnitude = Math.sqrt(vector.reduce((s, v) =&gt; s + v * v, 0));
                                                                                      if (magnitude &gt; THRESHOLD) {
                                                                                          console.log("I feel dizzy!");
                                                                                            }
                                                                                            });
                                                                                            
                                                                                            acl.start();</code></pre><p>可以使用以下方式请求加速度计权限:</p><pre><code>navigator.permissions.query({ name: "accelerometer" }).then((result) =&gt; {
                                                                                                if (result.state === "granted") {
                                                                                                      // now you can use accelerometer api
                                                                                                          } 
                                                                                                            });</code></pre><h2 id="item-0-11">11. Geo-location</h2><p>地理定位 API 允许我们访问用户的位置。如果你正在构建与地图或基于位置的服务相关的任何内容,这将非常有用。</p><pre><code>navigator.geolocation.getCurrentPosition(({ coords }) =&gt; {
                                                                                                              console.log(coords.latitude, coords.longitude);
                                                                                                              });</code></pre><p>可以使用以下方式请求地理位置权限:</p><pre><code>navigator.permissions.query({ name: "geolocation" }).then((result) =&gt; {
                                                                                                                  if (result.state === "granted") {
                                                                                                                        // now you can use geolocation api
                                                                                                                            } 
                                                                                                                              });</code></pre><h2 id="item-0-12">12. Web worker</h2><p>Web Workers 使得在与Web应用程序的主执行线程分离的后台线程中运行脚本操作成为可能。这样做的好处是可以在一个独立的线程中执行繁重的处理,使得主线程(通常是UI线程)能够在没有被阻塞/减慢的情况下运行。</p><pre><code>// main.js
                                                                                                                              const worker = new Worker("worker.js");
                                                                                                                              worker.onmessage = (e) =&gt; console.log(e.data);
                                                                                                                              worker.postMessage([5, 3]);
                                                                                                                              
                                                                                                                              // worker.js
                                                                                                                              onmessage = (e) =&gt; {
                                                                                                                                const [a, b] = e.data;
                                                                                                                                  postMessage(a + b);
                                                                                                                                  };</code></pre><h2 id="item-0-13">13. Resize Observer</h2><p>Resize Observer API 允许我们轻松观察元素的大小并处理其变化。当你拥有一个可调整大小的侧边栏时,它非常有用。</p><pre><code>const sidebar = document.querySelector(".sidebar");
                                                                                                                                  const observer = new ResizeObserver((entries) =&gt; {
                                                                                                                                    const sidebar = entries[0];
                                                                                                                                      //Do something with the element's new dimensions
                                                                                                                                      });
                                                                                                                                      observer.observe(sidebar);</code></pre><h2 id="item-0-14">14.Notification</h2><p>Notification API,顾名思义,允许您发送通知以打扰用户(与页面可见性 API 捆绑在一起,以更加打扰他们 😈)</p><pre><code>Notification.requestPermission().then((permission) =&gt; {
                                                                                                                                        if (permission === "granted") {
                                                                                                                                            new Notification("Hi there!", {
                                                                                                                                                  body: "Notification body",
                                                                                                                                                        icon: "https://tapajyoti-bose.vercel.app/img/logo.png",
                                                                                                                                                            });
                                                                                                                                                              }
                                                                                                                                                              });</code></pre><p>上述提到的一些API仍处于实验阶段,并不被所有浏览器支持。因此,如果您想在生产环境中使用它们,应该先检查浏览器是否支持。</p><pre><code>if ("SpeechRecognition" in window || "webkitSpeechRecognition" in window) {
                                                                                                                                                                // Speech Recognition is supported
                                                                                                                                                                }</code></pre><h3 id="item-0-15">交流</h3><blockquote><p>有梦想,有干货,微信搜索 <strong>【大迁世界】</strong> 关注这个在凌晨还在刷碗的刷碗智。</p><p>本文 GitHub  <a href="https://link.segmentfault.com/?enc=Ul7GW1aWU6erSVEvrdIX0A%3D%3D.atq2Vffq8WqNJWFJFKMaiH8zR%2BrA%2FcymCkg77j4sDuzg2jooxHusnAjHCTC2xWok" rel="nofollow" target="_blank">https://github.com/qq449245884/xiaozhi</a> 已收录,有一线大厂面试完整考点、资料以及我的系列文章。</p></blockquote><p></p>