8 Web APIs you may not know about but are very useful

青灯夜游
Release: 2022-08-19 20:18:04
forward
2414 people have browsed it

8 Web APIs you may not know about but are very useful

In 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, a video/audio source file, or an audio network stream. [Related recommendations:javascript learning tutorial]

Let’s look at an example:

Web APIs

Demo - Audio
Vol: Pan:
Copy after login

In this example, the audio is removed from theelement Transferred toAudioContext, sound effects (such as panning) are added to the audio source before being output to the audio output (speaker).

Button Init calls theinitfunction when clicked. This will create anAudioContextinstance and set it toaudioContext. Next, it creates a media sourcecreateMediaElementSource(audio), passing the audio element as the audio source. Volume nodevolNodeis created bycreateGainand can be used to adjust the volume. Next useStereoPannerNodeto set the panning effect, and finally connect the node to the media source.

8 Web APIs you may not know about but are very useful

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:

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:

Web APIs

Demo - Fullscreen
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.
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.
Copy after login

As you can see, the video element is in the div#video-stage element, with a button Toggle Fullscreen.

8 Web APIs you may not know about but are very useful

When the button is clicked to switch to full screen, we want the elementdiv#video-stageto be displayed in full screen.toggleThe implementation of the function is as follows:

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

Here,querySelectoris used to find thediv#video-stageelement and save its HTMLDivElement instance invideoStageElon.

Then, use thedocument.fullsreenElementproperty to determine if thedocumentis full screen, sorequestFullscreen(() can be called onvideoStageEl). This will makediv#video-stageoccupy the entire device view.

If you click the Toggle Fullscreen button in full screen mode,exitFullscreenwill be called on thedocument, so that the UI view will return to normal view (exit full screen).

2-8 Web APIs you may not know about but are very useful

related resources:

3. Web Speech API

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

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

Web APIs

Demo - Text to Speech
Demo - Speech to Text
Copy after login

8 Web APIs you may not know about but are very useful

第一个演示 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) }
Copy after login

它实例化了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() }
Copy after login

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

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

相关资源:

4. Web Bluetooth API

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

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

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

Web APIs

Demo - Bluetooth
Device Name:
Device ID:
Device Connected:
Copy after login

8 Web APIs you may not know about but are very useful

这里会显示设备信息。 单击 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.") }) }
Copy after login

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

相关资源:

5. Vibration API

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

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

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

navigator.vibrate(200) navigator.vibrate([200])
Copy after login

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

navigator.vibrate([200, 300, 400])
Copy after login

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

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

Web APIs

Demo - Vibration
Copy after login

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

8 Web APIs you may not know about but are very useful

相关资源:

6. Broadcast Channel API

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

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

const politicsChannel = new BroadcastChannel("politics")
Copy after login

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

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

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

Web APIs

Demo - BroadcastChannel
Open this page in another tab, window or iframe to chat with them.
Copy after login

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

8 Web APIs you may not know about but are very useful

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

7. Clipboard API

复制、剪切和粘贴等剪贴板操作是应用程序中最常见的一些功能。 Clipboard API 使 Web 用户能够访问系统剪贴板并执行基本的剪贴板操作。

以前,可以使用document.execCommand与系统剪贴板进行交互。 现代异步剪贴板 API 提供了直接读取和写入剪贴板内容的访问权限。

从剪贴板读取内容:

navigator.clipboard.readText().then(clipText => document.getElementById("outbox").innerText = clipText );
Copy after login

将内容写入剪贴板:

function updateClipboard(newClip) { navigator.clipboard.writeText(newClip).then(function() { /* clipboard successfully set */ }, function() { /* clipboard write failed */ }); }
Copy after login

相关资源:

8. Web Share API

Share API 可帮助我们在 web 应用上实现共享功能。它给人以移动原生共享的感觉。它使共享文本、文件和指向设备上其他应用程序的链接成为可能。

可通过navigator.share方法访问 Web Share API:

if (navigator.share) { navigator.share({ title: '百度', text: '百度一下', url: '', }) .then(() => console.log('分享成功')) .catch((error) => console.log('分享失败', error)); }
Copy after login

上面的代码使用原生 JavaScript 实现了文本共享。需要注意,我们只能使用onclick事件调用此操作:

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 (  ); }
Copy after login

相关资源:

更多编程相关知识,请访问:编程视频!!

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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!