8个你可能不了解但很实用的Web API

雨浩大大_8635

雨浩大大_8635

2022-08-19

3013人浏览

转载

在 web api 中,有非常有用的对象、属性和函数可用于执行小到访问 dom 这样的小任务,大到处理音频、视频这样的复杂任务。常见的 api 有 canvas、web worker、history、fetch 等。下面就来看一些不常见但很实用的 web api!

全文概览:

  • Web Audio API

  • Fullscreen API

  • Web Speech API

  • Web Bluetooth API

  • Vibration API

  • Broadcast Channel API

  • Clipboard API

  • Web Share API

1. Web Audio API

Audio API 允许我们在 Web 上操作音频流,它可以用于 Web 上的音频源添加效果和过滤器。音频源可以来自@#@#@#@#@#@#@#@#@#@0】

下面来看一个例子:

    <header>
        <h2>Web APIs<h2>
    </h2>
</h2></header>
    <div>

        <div>
            <div>
                Demo - Audio
            </div>
            <div>
                <div></div>
                <div>
                    <audio></audio>
                </div>

                <div>
                    <button>Init</button>
                    <button>Play</button>
                    <button>Pause</button>
                    <button>Stop</button>
                </div>
                <div>

                    <span>Vol: <input></span>
                    <span>Pan: <input></span>
                </div>

            </div>
        </div>

    </div>


<script>
    const l = console.log
    let audioFromAudioFile = (function() {
        var audioContext
        var volNode
        var pannerNode
        var mediaSource

        function init() {
            l("Init")
        try {
                audioContext = new AudioContext()        
                mediaSource = audioContext.createMediaElementSource(audio)
                volNode = audioContext.createGain()
                volNode.gain.value = 1
                pannerNode = new StereoPannerNode(audioContext, { pan:0 })

                mediaSource.connect(volNode).connect(pannerNode).connect(audioContext.destination)
            }
            catch(e) {
                error.innerHTML = "此设备不支持 Web Audio API"
                error.classList.remove("close")
            }
        }

        function play() {
            audio.play()            
        }

        function pause() {
            audio.pause()
        }

        function stop() {
            audio.stop()            
        }

        function changeVolume() {
            volNode.gain.value = this.value
            l("Vol Range:",this.value)
        }

        function changePan() {
            pannerNode.gain.value = this.value
            l("Pan Range:",this.value)
        }

        return {
            init,
            play,
            pause,
            stop,
            changePan,
            changeVolume
        }
    })()
</script>

这个例子中将音频从 @#@#@#@#@#@#@#@#@#@1

  • MDN 文档:@#@#@#@#@#@#@#@#@#@2
  • 2. Fullscreen API

    Fullscreen API 用于在 Web 应用程序中开启全屏模式,使用它就可以在全屏模式下查看页面/元素。在安卓手机中,它会溢出浏览器窗口和安卓顶部的状态栏(显示网络状态、电池状态等的地方)。

    Fullscreen API 方法:

    • requestFullscreen:系统上以全屏模式显示所选元素,会关闭其他应用程序以及浏览器和系统 UI 元素。
    • exitFullscreen:退出全屏模式并切换到正常模式。

    下面来看一个常见的例子,使用全屏模式观看视频::

        <header>
            <h2>Web APIs<h2>
        </h2>
    </h2></header>
        <div>
            <div>
            <div>
                Demo - Fullscreen
            </div>
            <div>
            <div></div>
            <div>
                This API makes fullscreen-mode of our webpage possible. It lets you select the Element you want to view in fullscreen-mode, then it shuts off the browsers window features like URL bar, the window pane, and presents the Element to take the entire width and height of the system.
    
    In Android phones, it will remove the browsers window and the Android UI where the network status, battery status are displayed, and display the Element in full width of the Android system.
            </div>
            <div>
                <video></video>
                <button>Toogle Fullscreen</button>
            </div>
            <div>
                This API makes fullscreen-mode of our webpage possible. It lets you select the Element you want to view in fullscreen-mode, then it shuts off the browsers window features like URL bar, the window pane, and presents the Element to take the entire width and height of the system.
    
    In Android phones, it will remove the browsers window and the Android UI where the network status, battery status are displayed, and display the Element in full width of the Android system.
            </div>
            </div>
            </div>
        </div>
    
    
    <script>
        const l =console.log
    
        function toggle() {
            const videoStageEl = document.querySelector(".video-stage")
            if(videoStageEl.requestFullscreen) {
                if(!document.fullscreenElement){
                    videoStageEl.requestFullscreen()
                }
                else {
                    document.exitFullscreen()
                }
            } else {
                error.innerHTML = "此设备不支持 Fullscreen API"
                error.classList.remove("close")        
            }
        }
    </script>

    可以看到,video 元素在 div#video-stage 元素中,带有一个按钮 Toggle Fullscreen。

    1.png

    当点击按钮切换全屏时,我们想让元素 div#video-stage 全屏显示。toggle 函数的实现如下:

    function toggle() {
      const videoStageEl = document.querySelector(".video-stage")
      if(!document.fullscreenElement)
        videoStageEl.requestFullscreen()
      else
        document.exitFullscreen()
    }

    这里通过 querySelector 查找 div#video-stage 元素并将其 HTMLDivElement 实例保存在 videoStageEl 上。

    然后,使用 document.fullsreenElement 属性来确定 document 是否是全屏的,所以可以在 videoStageEl 上调用 requestFullscreen()。 这将使 div#video-stage 占据整个设备的视图。

    如果在全屏模式下点击 Toggle Fullscreen 按钮,就会在 document 上调用 exitFullcreen,这样 UI 视图就会返回到普通视图(退出全屏)。

    2.png

    相关资源:

    阿拉丁·前端工程工坊|脚手架·组件·规范落地·构建优化·性能与可访问性一体
    阿拉丁·前端工程工坊|脚手架·组件·规范落地·构建优化·性能与可访问性一体

    阿拉丁·前端工程工坊把「前端只会写页面、规范停在文档里、脚手架手敲、构建靠抄、性能靠猜、可访问性靠忘」从「手动搭项目、抄配置、肉眼查规范」升级成一条本地工具链——多框架脚手架生成(React/Vue3/Svelte + Vite)、可复用组件生成(Props 类型+样式+示例)、规范落地检查(lint-lite:命名/未用变量/console残留/TS any/目录结构)、构建配置生成与产物体积预算、性能审计(依赖体积/重复/懒加载/Lighthouse 清单)、可访问性(a11y)校验(alt/aria

    下载

    3. Web Speech API

    Web Speech API 提供了将语音合成和语音识别添加到 Web 应用程序的功能。使用此 API,我们将能够向 Web 应用程序发出语音命令,就像在 Android 上通过其 Google Speech 或在 Windows 中使用 Cortana 一样。

    下面来看一个简单的例子,使用 Web Speech API 实现文字转语音和语音转文字:

        <header>
            <h2>Web APIs<h2>
        </h2>
    </h2></header>
        <div>
            <div></div>
    
            <div>
                <div>
                    Demo - Text to Speech
                </div>
                <div>
                    <div>
                        <input>
                    </div>
    
                    <div>
                        <button>Tap to Speak</button>
                    </div>
                </div>
            </div>
    
            <div>
                <div>
                    Demo - Speech to Text
                </div>
                <div>
                    <div>
                        <textarea></textarea>
                    </div>
    
                    <div>
                        <button>Tap and Speak into Mic</button>
                    </div>
                </div>
            </div>
    
        </div>
    
    
    <script>
    
        try {
            var speech = new SpeechSynthesisUtterance()
            var SpeechRecognition = SpeechRecognition;
            var recognition = new SpeechRecognition()
    
        } catch(e) {
            error.innerHTML = "此设备不支持 Web Speech API"
            error.classList.remove("close")                
        }
    
        function speak() {
            speech.text = textToSpeech.value
            speech.volume = 1
            speech.rate=1
            speech.pitch=1
            window.speechSynthesis.speak(speech)
        }
    
        function tapToSpeak() {
            recognition.onstart = function() { }
    
            recognition.onresult = function(event) {
                const curr = event.resultIndex
                const transcript = event.results[curr][0].transcript
                speechToText.value = transcript
            }
    
            recognition.onerror = function(ev) {
                console.error(ev)
            }
    
            recognition.start()
        }
    </script>

    2-2.png

    第一个演示 Demo - Text to Speech 演示了使用这个 API 和一个简单的输入字段,接收输入文本和一个按钮来执行语音操作。

    function speak() {
      const speech = new SpeechSynthesisUtterance()
      speech.text = textToSpeech.value
      speech.volume = 1
      speech.rate = 1
      speech.pitch = 1
      window.speechSynthesis.speak(speech)
    }

    它实例化了 SpeechSynthesisUtterance() 对象,将文本设置为从输入框中输入的文本中朗读。 然后,使用 speech 对象调用 SpeechSynthesis#speak 函数,在扬声器中说出输入框中的文本。

    第二个演示 Demo - Speech to Text 将语音识别为文字。 点击 Tap and Speak into Mic 按钮并对着麦克风说话,我们说的话会被翻译成文本输入框中的内容。

    点击 Tap and Speak into Mic 按钮会调用 tapToSpeak 函数:

    function tapToSpeak() {
      var SpeechRecognition = SpeechRecognition;
      const recognition = new SpeechRecognition()
      recognition.onstart = function() { }
      recognition.onresult = function(event) {
        const curr = event.resultIndex
        const transcript = event.results[curr][0].transcript
        speechToText.value = transcript
      }
      recognition.onerror = function(ev) {
        console.error(ev)
      }
      recognition.start()
    }

    这里实例化了 SpeechRecognition,然后注册事件处理程序和回调。语音识别开始时调用 onstart,发生错误时调用 onerror。 每当语音识别捕获一条线时,就会调用 onresult。

    在 onresult 回调中,提取内容并将它们设置到 textarea 中。 因此,当我们对着麦克风说话时,文字会出现在 textarea 内容中。

    相关资源:

    4. Web Bluetooth API

    Bluetooth API 让我们可以访问手机上的低功耗蓝牙设备,并使用它将网页上的数据共享到另一台设备。

    基本 API 是 navigator.bluetooth.requestDevice。 调用它将使浏览器提示用户使用设备选择器,用户可以在其中选择一个设备或取消请求。navigator.bluetooth.requestDevice 需要一个强制对象。 此对象定义过滤器,用于返回与过滤器匹配的蓝牙设备。

    下面来看一个简单的例子,使用 navigator.bluetooth.requestDevice API 从 BLE 设备检索基本设备信息:

      <header>
        <h2>Web APIs<h2>
          </h2>
    </h2></header>
          <div>
            
            <div>
              <div>
                Demo - Bluetooth
              </div>
              <div>
                <div></div>
                <div>
                  <div>Device Name: <span></span>
    </div>
                  <div>Device ID: <span></span>
    </div>
                  <div>Device Connected: <span></span>
    </div>
                </div>
                
                <div>
                  <button>Get BLE Device</button>
                </div>
                
              </div>
            </div>
            
          </div>
          
        
        <script>
          function bluetoothAction(){
            if(navigator.bluetooth) {
              navigator.bluetooth.requestDevice({
                acceptAllDevices: true
              }).then(device => {            
                dname.innerHTML = device.name
                did.innerHTML = device.id
                dconnected.innerHTML = device.connected
              }).catch(err => {
                error.innerHTML = "Oh my!! Something went wrong."
                error.classList.remove("close")
              })
            } else {
              error.innerHTML = "Bluetooth is not supported."            
              error.classList.remove("close")
            }
          }
    </script>

    3.png

    这里会显示设备信息。 单击 Get BLE Device 按钮会调用 bluetoothAction 函数:

    function bluetoothAction(){
      navigator.bluetooth.requestDevice({
        acceptAllDevices: true
      }).then(device => {            
        dname.innerHTML = device.name
        did.innerHTML = device.id
        dconnected.innerHTML = device.connected
      }).catch(err => {
        console.error("Oh my!! Something went wrong.")
      })
    }

    bluetoothAction 函数调用带有 acceptAllDevices:true 选项的 navigator.bluetooth.requestDevice API,这将使其扫描并列出所有附近的蓝牙活动设备。 它返回了一个 promise,所以将它解析为从回调函数中获取一个参数 device,这个 device 参数将保存列出的蓝牙设备的信息。这是我们使用其属性在设备上显示信息的地方。

    相关资源:

    5. Vibration API

    Vibration API 可以使我们的设备振动,作为对我们应该响应的新数据或信息的通知或物理反馈的一种方式。

    执行振动的方法是 navigator.vibrate(pattern)。pattern 是描述振动模式的单个数字或数字数组。

    这将使设备振动在 200 毫秒之后停止:

    navigator.vibrate(200)
    navigator.vibrate([200])

    这将使设备先振动 200 毫秒,再暂停 300 毫秒,最后振动 400 毫秒并停止:

    navigator.vibrate([200, 300, 400])

    可以通过传递 0、[]、[0,0,0] 来消除振动。

    下面来看一个简单的例子:

      <header>
        <h2>Web APIs<h2>
      </h2>
    </h2></header>
      <div>
        <div>
          <div>
            Demo - Vibration
          </div>
          <div>
            <div></div>
            <div>
              <input>
            </div>
            <div>
              <button>Vibrate</button>
            </div>
          </div>
        </div>
      </div>
    
        
    <script>
          if(navigator.vibrate) {
            function vibrate() {
              const time = vibTime.value
              if(time != "")
                navigator.vibrate(time)
            }
          } else {
            error.innerHTML = "Vibrate API not supported in this device."
            error.classList.remove("close")        
          }
    </script>

    这里有一个输入框和一个按钮。 在输入框中输入振动的持续时间并按下按钮。我们的设备将在输入的时间内振动。

    4.png

    相关资源:

    元素传输到 AudioContext,声音效果(如平移)在被输出到音频输出(扬声器)之前被添加到音频源。

    按钮 Init 在单击时调用 init 函数。 这将创建一个 AudioContext 实例并将其设置为 audioContext。 接下来,它创建一个媒体源 createMediaElementSource(audio),将音频元素作为音频源传递。音量节点 volNode 由 createGain 创建,可以用来调节音量。接下来使用 StereoPannerNode 设置平移效果,最后将节点连接至媒体源。

    5.png

    点击按钮(Play、Pause、Stop)可以播放、暂停和停止音频。页面有一个音量和平移的范围滑块,滑动滑块就可以调节音频的音量和平移效果。

    相关资源:

    6. Broadcast Channel API

    Broadcast Channel API 允许从同源的不同浏览上下文进行消息或数据的通信。其中,浏览上下文指的是窗口、选项卡、iframe、worker 等。

    BroadcastChannel 类用于创建或加入频道:

    const politicsChannel = new BroadcastChannel("politics")

    politics 是频道的名称,任何使用 politics 始化 BroadcastChannel 构造函数的上下文都将加入 politics 频道,它将接收在频道上发送的任何消息,并可以将消息发送到频道中。

    如果它是第一个具有 politics 的 BroadcastChannel 构造函数,则将创建该频道。可以使用 BroadcastChannel.postMessage API 来将消息发布到频道。使用 BroadcastChannel.onmessage API 要订阅频道消息。

    下面来看一个简单的聊天应用:

      <header>
        <h2>Web APIs<h2>
       </h2>
    </h2></header>
       <div>
           <div>
              <div>
                Demo - BroadcastChannel
              </div>
              <div>
                <div>Open this page in another <i>tab</i>, <i>window</i> or <i>iframe</i> to chat with them.</div>
                <div></div>
                <div>
                </div>
                <div>
                  <input>
                  <button>Send Msg to Channel</button>
                </div>
              </div>
            </div> 
        </div>
    
    <script>
          const l = console.log;
          try {
            var politicsChannel = new BroadcastChannel("politics")
            politicsChannel.onmessage = onMessage
            var userId = Date.now()
            } catch(e) {
              error.innerHTML = "BroadcastChannel API not supported in this device."
              error.classList.remove("close")
            }
          
          input.addEventListener("keydown", (e) => {
            if(e.keyCode === 13 && e.target.value.trim().length > 0) {
              sendMsg()            
            }
          })
          
          function onMessage(e) {     
            const {msg,id}=e.data   
            const newHTML = "<div class='chat-msg'><span><i>"+id+": "+msg+""
            displayMsg.innerHTML = displayMsg.innerHTML + newHTML
            displayMsg.scrollTop = displayMsg.scrollHeight
          }
          
          function sendMsg() {
            politicsChannel.postMessage({msg:input.value,id:userId})
            
            const newHTML = "<div class='chat-msg'><span><i>Me: "+input.value+""
            displayMsg.innerHTML = displayMsg.innerHTML + newHTML
            
            input.value = ""
            
            displayMsg.scrollTop = displayMsg.scrollHeight
          }   
    </script>

    这里有一个简单的文本和按钮。 输入消息,然后按按钮发送消息。下面初始化了politicalChannel,并在 politicalChannel 上设置了一个 onmessage 事件监听器,这样它就可以接收和显示消息。

    6.png

    点击按钮就会调用sendMsg 函数。 它通过 BroadcastChannel#postMessage API 将消息发送到 politics 频道。任何初始化此脚本的选项卡、iframe 或工作程序都将接收从此处发送的消息,因此此页面将接收从其他上下文发送的消息。相关资源:

    • Demo:

    大量免费API接口:立即使用
    涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!

    相关文章

    PHP速学视频免费教程(入门到精通)
    PHP速学视频免费教程(入门到精通)

    PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

    下载

    相关标签:

    javascript 前端

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

    相关专题

    更多
    Golang channel原理
    Golang channel原理

    本专题整合了Golang channel通信相关介绍,阅读专题下面的文章了解更多详细内容。

    2025.11.14

    474

    8

    golang channel相关教程
    golang channel相关教程

    本专题整合了golang处理channel相关教程,阅读专题下面的文章了解更多详细内容。

    2025.11.17

    639

    10

    Go语言 channel用法详解
    Go语言 channel用法详解

    本专题整合了go语言中channel的各种使用方法,阅读专题下面的文章了解更多详细步骤。

    2026.04.03

    543

    23

    DOM是什么意思
    DOM是什么意思

    dom的英文全称是documentobjectmodel,表示文件对象模型,是w3c组织推荐的处理可扩展置标语言的标准编程接口;dom是html文档的内存中对象表示,它提供了使用javascript与网页交互的方式。想了解更多的相关内容,可以阅读本专题下面的文章。

    2024.08.14

    6561

    7

    promise的用法
    promise的用法

    “promise” 是一种用于处理异步操作的编程概念,它可以用来表示一个异步操作的最终结果。Promise 对象有三种状态:pending(进行中)、fulfilled(已成功)和 rejected(已失败)。Promise的用法主要包括构造函数、实例方法(then、catch、finally)和状态转换。

    2023.10.12

    5040

    6

    html文本框类型介绍
    html文本框类型介绍

    html文本框类型有单行文本框、密码文本框、数字文本框、日期文本框、时间文本框、文件上传文本框、多行文本框等等。详细介绍:1、单行文本框是最常见的文本框类型,用于接受单行文本输入,用户可以在文本框中输入任意文本,例如用户名、密码、电子邮件地址等;2、密码文本框用于接受密码输入,用户在输入密码时,文本框中的内容会被隐藏,以保护用户的隐私;3、数字文本框等等。

    2023.10.12

    5023

    6

    html5动画制作有哪些制作方法
    html5动画制作有哪些制作方法

    html5动画制作方法有使用CSS3动画、使用JavaScript动画库、使用HTML5 Canvas等。想了解更多html5动画制作方法相关内容,可以阅读本专题下面的文章。

    2023.10.23

    5051

    6

    canva可画使用技巧汇总
    canva可画使用技巧汇总

    本专题汇集了PHP中文网精心整理的Canva可画新手使用技巧大全,专为零基础用户打造。无论你是想制作精美海报、PPT还是社交媒体配图,这里都有从注册登录、模板搜索到AI辅助设计、导出分享的全流程保姆级教程。通过深入浅出的图文指南,帮助你快速跨越设计门槛,轻松掌握Canva可画的实用操作,让每个人都能成为设计达人!

    2026.05.19

    304

    21

    github中文官网入口 github中文版官网网页进入
    github中文官网入口 github中文版官网网页进入

    github中文官网入口https://docs.github.com/zh/get-started,GitHub 是一种基于云的平台,可在其中存储、共享并与他人一起编写代码。 通过将代码存储在GitHub 上的“存储库”中,你可以: “展示或共享”你的工作。 持续“跟踪和管理”对代码的更改。

    2026.01.21

    9005

    27

    热门下载

    更多
    网站特效
    /
    网站源码
    /
    网站素材
    /
    前端模板

    精品课程

    更多
    相关推荐
    /
    热门推荐
    /
    最新课程