8 Web APIs you may not know about but are very useful
Aug 19, 2022 pm 08:18 PMIn Web API, there are very useful objects, properties, and functions that can be used to perform small tasks such as accessing the DOM, to complex tasks such as processing audio and video. Common APIs include Canvas, Web Worker, History, Fetch, etc. Let’s take a look at some uncommon but useful Web APIs!
Full text overview:
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 allows us to operate audio streams on the Web. It can be used to add effects and filters to audio sources on the Web. The audio source can come from <audio></audio>
, a video/audio source file, or an audio network stream. [Related recommendations: javascript learning tutorial]
Let’s look at an example:
????<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 = "此設(shè)備不支持 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>
In this example, the audio is removed from the <audio></audio>
element Transferred to AudioContext
, sound effects (such as panning) are added to the audio source before being output to the audio output (speaker).
Button Init calls the init
function when clicked. This will create an AudioContext
instance and set it to audioContext
. Next, it creates a media source createMediaElementSource(audio)
, passing the audio element as the audio source. Volume node volNode
is created by createGain
and can be used to adjust the volume. Next use StereoPannerNode
to set the panning effect, and finally connect the node to the media source.
Click the buttons (Play, Pause, Stop) to play, pause and stop the audio. The page has a volume and pan range slider, and you can adjust the audio volume and pan effect by sliding the slider.
Related resources:
- Demo: web-api-examples.github.io/audio.html
- MDN Documentation: developer.mozilla.org/zh-CN/docs/…
2. Fullscreen API
Fullscreen API is used to enable full screen mode in web applications. Use it to view pages/elements in full screen mode. On Android phones, it overflows the browser window and the status bar at the top of Android (where network status, battery status, etc. are displayed).
Fullscreen API methods:
-
requestFullscreen
: Displays the selected element in full screen mode on the system, closing other applications as well as browser and system UI elements. -
exitFullscreen
: Exit full screen mode and switch to normal mode.
Let’s look at a common example, using full screen mode to watch a video:
????<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 = "此設(shè)備不支持 Fullscreen API" error.classList.remove("close") } } </script>
As you can see, the video element is in the div#video-stage element, with a button Toggle Fullscreen.
When the button is clicked to switch to full screen, we want the element div#video-stage
to be displayed in full screen. toggle
The implementation of the function is as follows:
function?toggle()?{ ??const?videoStageEl?=?document.querySelector(".video-stage") ??if(!document.fullscreenElement) ????videoStageEl.requestFullscreen() ??else ????document.exitFullscreen() }
Here, querySelector
is used to find the div#video-stage
element and save its HTMLDivElement instance in videoStageEl
on.
Then, use the document.fullsreenElement
property to determine if the document
is full screen, so requestFullscreen(() can be called on
videoStageEl )
. This will make div#video-stage
occupy the entire device view.
If you click the Toggle Fullscreen button in full screen mode, exitFullscreen
will be called on the document
, so that the UI view will return to normal view (exit full screen).
related resources:
3. Web Speech API
Web Speech API 提供了將語音合成和語音識(shí)別添加到 Web 應(yīng)用程序的功能。使用此 API,我們將能夠向 Web 應(yīng)用程序發(fā)出語音命令,就像在 Android 上通過其 Google Speech 或在 Windows 中使用 Cortana 一樣。
下面來看一個(gè)簡(jiǎn)單的例子,使用 Web Speech API 實(shí)現(xiàn)文字轉(zhuǎn)語音和語音轉(zhuǎn)文字:
????<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 = "此設(shè)備不支持 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>
第一個(gè)演示 Demo - Text to Speech 演示了使用這個(gè) API 和一個(gè)簡(jiǎn)單的輸入字段,接收輸入文本和一個(gè)按鈕來執(zhí)行語音操作。
function?speak()?{ ??const?speech?=?new?SpeechSynthesisUtterance() ??speech.text?=?textToSpeech.value ??speech.volume?=?1 ??speech.rate?=?1 ??speech.pitch?=?1 ??window.speechSynthesis.speak(speech) }
它實(shí)例化了 SpeechSynthesisUtterance()
對(duì)象,將文本設(shè)置為從輸入框中輸入的文本中朗讀。 然后,使用 speech
對(duì)象調(diào)用 SpeechSynthesis#speak
函數(shù),在揚(yáng)聲器中說出輸入框中的文本。
第二個(gè)演示 Demo - Speech to Text 將語音識(shí)別為文字。 點(diǎn)擊 Tap and Speak into Mic 按鈕并對(duì)著麥克風(fēng)說話,我們說的話會(huì)被翻譯成文本輸入框中的內(nèi)容。
點(diǎn)擊 Tap and Speak into Mic 按鈕會(huì)調(diào)用 tapToSpeak 函數(shù):
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() }
這里實(shí)例化了 SpeechRecognition
,然后注冊(cè)事件處理程序和回調(diào)。語音識(shí)別開始時(shí)調(diào)用 onstart
,發(fā)生錯(cuò)誤時(shí)調(diào)用 onerror
。 每當(dāng)語音識(shí)別捕獲一條線時(shí),就會(huì)調(diào)用 onresult
。
在 onresult
回調(diào)中,提取內(nèi)容并將它們?cè)O(shè)置到 textarea
中。 因此,當(dāng)我們對(duì)著麥克風(fēng)說話時(shí),文字會(huì)出現(xiàn)在 textarea
內(nèi)容中。
相關(guān)資源:
4. Web Bluetooth API
Bluetooth API 讓我們可以訪問手機(jī)上的低功耗藍(lán)牙設(shè)備,并使用它將網(wǎng)頁上的數(shù)據(jù)共享到另一臺(tái)設(shè)備。
基本 API 是 navigator.bluetooth.requestDevice
。 調(diào)用它將使瀏覽器提示用戶使用設(shè)備選擇器,用戶可以在其中選擇一個(gè)設(shè)備或取消請(qǐng)求。navigator.bluetooth.requestDevice
需要一個(gè)強(qiáng)制對(duì)象。 此對(duì)象定義過濾器,用于返回與過濾器匹配的藍(lán)牙設(shè)備。
下面來看一個(gè)簡(jiǎn)單的例子,使用 navigator.bluetooth.requestDevice
API 從 BLE 設(shè)備檢索基本設(shè)備信息:
??<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>
這里會(huì)顯示設(shè)備信息。 單擊 Get BLE Device 按鈕會(huì)調(diào)用 bluetoothAction
函數(shù):
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
函數(shù)調(diào)用帶有 acceptAllDevices:true
選項(xiàng)的 navigator.bluetooth.requestDevice
API,這將使其掃描并列出所有附近的藍(lán)牙活動(dòng)設(shè)備。 它返回了一個(gè) promise
,所以將它解析為從回調(diào)函數(shù)中獲取一個(gè)參數(shù) device,這個(gè) device 參數(shù)將保存列出的藍(lán)牙設(shè)備的信息。這是我們使用其屬性在設(shè)備上顯示信息的地方。
相關(guān)資源:
5. Vibration API
Vibration API 可以使我們的設(shè)備振動(dòng),作為對(duì)我們應(yīng)該響應(yīng)的新數(shù)據(jù)或信息的通知或物理反饋的一種方式。
執(zhí)行振動(dòng)的方法是 navigator.vibrate(pattern)
。pattern
是描述振動(dòng)模式的單個(gè)數(shù)字或數(shù)字?jǐn)?shù)組。
這將使設(shè)備振動(dòng)在 200 毫秒之后停止:
navigator.vibrate(200) navigator.vibrate([200])
這將使設(shè)備先振動(dòng) 200 毫秒,再暫停 300 毫秒,最后振動(dòng) 400 毫秒并停止:
navigator.vibrate([200,?300,?400])
可以通過傳遞 0、[]、[0,0,0] 來消除振動(dòng)。
下面來看一個(gè)簡(jiǎn)單的例子:
??<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>
這里有一個(gè)輸入框和一個(gè)按鈕。 在輸入框中輸入振動(dòng)的持續(xù)時(shí)間并按下按鈕。我們的設(shè)備將在輸入的時(shí)間內(nèi)振動(dòng)。
相關(guān)資源:
6. Broadcast Channel API
Broadcast Channel API 允許從同源的不同瀏覽上下文進(jìn)行消息或數(shù)據(jù)的通信。其中,瀏覽上下文指的是窗口、選項(xiàng)卡、iframe、worker 等。
BroadcastChannel
類用于創(chuàng)建或加入頻道:
const?politicsChannel?=?new?BroadcastChannel("politics")
politics
是頻道的名稱,任何使用 politics
始化 BroadcastChannel
構(gòu)造函數(shù)的上下文都將加入 politics
頻道,它將接收在頻道上發(fā)送的任何消息,并可以將消息發(fā)送到頻道中。
如果它是第一個(gè)具有 politics
的 BroadcastChannel
構(gòu)造函數(shù),則將創(chuàng)建該頻道??梢允褂?BroadcastChannel.postMessage API
來將消息發(fā)布到頻道。使用 BroadcastChannel.onmessage
API 要訂閱頻道消息。
下面來看一個(gè)簡(jiǎn)單的聊天應(yīng)用:
??<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>
這里有一個(gè)簡(jiǎn)單的文本和按鈕。 輸入消息,然后按按鈕發(fā)送消息。下面初始化了politicalChannel
,并在 politicalChannel
上設(shè)置了一個(gè) onmessage
事件監(jiān)聽器,這樣它就可以接收和顯示消息。
點(diǎn)擊按鈕就會(huì)調(diào)用sendMsg
函數(shù)。 它通過 BroadcastChannel#postMessage
API 將消息發(fā)送到 politics
頻道。任何初始化此腳本的選項(xiàng)卡、iframe 或工作程序都將接收從此處發(fā)送的消息,因此此頁面將接收從其他上下文發(fā)送的消息。相關(guān)資源:
7. Clipboard API
復(fù)制、剪切和粘貼等剪貼板操作是應(yīng)用程序中最常見的一些功能。 Clipboard API 使 Web 用戶能夠訪問系統(tǒng)剪貼板并執(zhí)行基本的剪貼板操作。
以前,可以使用 document.execCommand
與系統(tǒng)剪貼板進(jìn)行交互。 現(xiàn)代異步剪貼板 API 提供了直接讀取和寫入剪貼板內(nèi)容的訪問權(quán)限。
從剪貼板讀取內(nèi)容:
navigator.clipboard.readText().then(clipText?=> ??document.getElementById("outbox").innerText?=?clipText );
將內(nèi)容寫入剪貼板:
function?updateClipboard(newClip)?{ ??navigator.clipboard.writeText(newClip).then(function()?{ ????/*?clipboard?successfully?set?*/ ??},?function()?{ ????/*?clipboard?write?failed?*/ ??}); }
相關(guān)資源:
8. Web Share API
Share API 可幫助我們?cè)?web 應(yīng)用上實(shí)現(xiàn)共享功能。它給人以移動(dòng)原生共享的感覺。它使共享文本、文件和指向設(shè)備上其他應(yīng)用程序的鏈接成為可能。
可通過 navigator.share
方法訪問 Web Share API:
if?(navigator.share)?{ ??navigator.share({ ????title:?'百度', ????text:?'百度一下', ????url:?'<https:></https:>', ??}) ????.then(()?=>?console.log('分享成功')) ????.catch((error)?=>?console.log('分享失敗',?error)); }
上面的代碼使用原生 JavaScript 實(shí)現(xiàn)了文本共享。需要注意,我們只能使用 onclick
事件調(diào)用此操作:
function?Share({?label,?text,?title?})?{ ??const?shareDetails?=?{?title,?text?}; ??const?handleSharing?=?async?()?=>?{ ????if?(navigator.share)?{ ??????try?{ ????????await?navigator.share(shareDetails).then(()?=>?console.log("Sent")); ??????}?catch?(error)?{ ????????console.log(`Oops!?I?couldn't?share?to?the?world?because:?${error}`); ??????} ????}?else?{ ??????//?fallback?code ??????console.log( ????????"Web?share?is?currently?not?supported?on?this?browser.?Please?provide?a?callback" ??????); ????} ??}; ??return?( ????<button> ??????<span>{label}</span> ????</button> ??); }
相關(guān)資源:
更多編程相關(guān)知識(shí),請(qǐng)?jiān)L問:編程視頻??!
The above is the detailed content of 8 Web APIs you may not know about but are very useful. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

Combination of Golang and front-end technology: To explore how Golang plays a role in the front-end field, specific code examples are needed. With the rapid development of the Internet and mobile applications, front-end technology has become increasingly important. In this field, Golang, as a powerful back-end programming language, can also play an important role. This article will explore how Golang is combined with front-end technology and demonstrate its potential in the front-end field through specific code examples. The role of Golang in the front-end field is as an efficient, concise and easy-to-learn
