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
Audio API allows us to operate audio streams on the Web, and it can be used to add audio sources on the Web Effects and filters. The audio source can come from <audio>
, a video/audio source file, or an audio network stream.
Let’s look at an example:
<body> <header> <h2>Web APIs<h2> </header> <div class="web-api-cnt"> <div class="web-api-card"> <div class="web-api-card-head"> Demo-Audio </div> <div class="web-api-card-body"> <div id="error" class="close"></div> <div> <audio controls src="./audio.mp3" id="audio"></audio> </div> <div> <button onclick="audioFromAudioFile.init()">Init</button> <button onclick="audioFromAudioFile.play()">Play</button> <button onclick="audioFromAudioFile.pause()">Pause</button> <button onclick="audioFromAudioFile.stop()">Stop</button> </div> <div> <span>Vol: <input onchange="audioFromAudioFile.changeVolume()" type="range" id="vol" min="1" max="2" step="0.01" value="1" /></ span> <span>Pan: <input onchange="audioFromAudioFile.changePan()" type="range" id="panner" min="-1" max="1" step="0.01" value="0" />< /span> </div> </div> </div> </div> </body> <script> const l = console.log let audioFromAudioFile = (function() { var audioContext varvolNode varpannerNode 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 = "This device does not support 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>
This example transfers audio from the <audio>
element to AudioContext
. Sound effects (such as panning) are added to the audio source before being output to the audio output (speaker).
ButtonInit calls the init
function when clicked. This will create an AudioContext
instance and set it as audioContext
. Next, it creates a media source createMediaElementSource(audio)
, passing the audio element as the audio source. The volume node volNode
is created by createGain
and can be used to adjust the volume. Next use StereoPannerNode
to set up 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:
Fullscreen API is used to enable full-screen mode in web applications , which allows you to view the page/element 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 shown).
Fullscreen API method:
requestFullscreen
: Display 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 of using full screen mode to watch a video:
<body> <header> <h2>Web APIs<h2> </header> <div class="web-api-cnt"> <div class="web-api-card"> <div class="web-api-card-head"> Demo-Fullscreen </div> <div class="web-api-card-body"> <div id="error" class="close"></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 class="video-stage"> <video id="video" src="./video.mp4"></video> <button onclick="toggle()">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> </body> <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 = "This device does not support 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.
We want the element div#video-stage
to display full screen when the button is clicked to toggle full screen. The implementation of the toggle
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 div#video-stage
element and save its HTMLDivElement instance on videoStageEl
.
Then, use the document.fullsreenElement
property to determine if 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, exitFullcreen
will be called on document
, so that the UI view will return to normal view (exit full screen).
Related resources:
Web Speech API provides speech synthesis and speech recognition Functionality added to web applications. Using this API we will be able to issue voice commands to web applications, just like on Android through its Google Speech or using Cortana in Windows.
Let's look at a simple example using the Web Speech API to implement text-to-speech and speech-to-text:
<body> <header> <h2>Web APIs<h2> </header> <div class="web-api-cnt"> <div id="error" class="close"></div> <div class="web-api-card"> <div class="web-api-card-head"> Demo - Text to Speech </div> <div class="web-api-card-body"> <div> <input placeholder="Enter text here" type="text" id="textToSpeech" /> </div> <div> <button onclick="speak()">Tap to Speak</button> </div> </div> </div> <div class="web-api-card"> <div class="web-api-card-head"> Demo - Speech to Text </div> <div class="web-api-card-body"> <div> <textarea placeholder="Text will appear here when you start speaking." id="speechToText"></textarea> </div> <div> <button onclick="tapToSpeak()">Tap and Speak into Mic</button> </div> </div> </div> </div> </body> <script> try { var speech = new SpeechSynthesisUtterance() var SpeechRecognition = SpeechRecognition; var recognition = new SpeechRecognition() } catch(e) { error.innerHTML = "This device does not support 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>
The first demo - Text to Speech demonstrates the use of this API with a simple input field that receives input text and a button to perform speech operations.
function speak() { const speech = new SpeechSynthesisUtterance() speech.text = textToSpeech.value speech.volume = 1 speech.rate = 1 speech.pitch = 1 window.speechSynthesis.speak(speech) }
It instantiates SpeechSynthesisUtterance()
object and sets the text to be spoken from the text entered in the input box. Then, use the speech
object to call SpeechSynthesis#speak
function to speak the text in the input box in the speaker.
The second demo Demo - Speech to Text recognizes speech as text. Click the Tap and Speak into Mic button and speak into the microphone, and what we say will be translated into the content in the text input box.
Clicking the Tap and Speak into Mic button will call the tapToSpeak function:
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() }
Here SpeechRecognition
is instantiated and then event handlers and callbacks are registered. onstart
is called when speech recognition starts, onerror
is called when an error occurs. Whenever speech recognition captures a line, onresult
is called.
In onresult
callback, extract the contents and set them into textarea
. So when we speak into the microphone, the text appears in textarea
content.
Related resources:
Bluetooth API allows us to access low-power devices on mobile phones Bluetooth-enhanced device and use it to share data from a web page to another device.
The basic API is navigator.bluetooth.requestDevice
. Calling this will cause the browser to prompt the user with the device selector, where the user can select a device or cancel the request. navigator.bluetooth.requestDevice
requires a mandatory object. This object defines a filter that returns Bluetooth devices that match the filter.
Let's look at a simple example using the navigator.bluetooth.requestDevice
API to retrieve basic device information from a BLE device:
<body> <header> <h2>Web APIs<h2> </header> <div class="web-api-cnt"> <div class="web-api-card"> <div class="web-api-card-head"> Demo-Bluetooth </div> <div class="web-api-card-body"> <div id="error" class="close"></div> <div> <div>Device Name: <span id="dname"></span></div> <div>Device ID: <span id="did"></span></div> <div>Device Connected: <span id="dconnected"></span></div> </div> <div> <button onclick="bluetoothAction()">Get BLE Device</button> </div> </div> </div> </div> </body> <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>
Device information will be displayed here. Clicking the Get BLE Device button will call the bluetoothAction
function:
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.") }) }
The bluetoothAction
function calls navigator.bluetooth.requestDevice
API with acceptAllDevices:true
option, which will cause it to scan and list all nearby Bluetooth active devices. It returns a promise
, so resolve it to get a parameter device from the callback function, this device parameter will hold the information of the listed Bluetooth device. This is where we use its properties to display information on the device.
Related resources:
Vibration API can make our device vibrate, as a A way in which we should respond to notifications or physical feedback of new data or information.
The method to perform vibration is navigator.vibrate(pattern)
. pattern
is a single number or an array of numbers that describes a vibration pattern.
This will cause the device to stop vibrating after 200 milliseconds:
navigator.vibrate(200) navigator.vibrate([200])
This will cause the device to vibrate for 200 ms, pause for 300 ms, and finally vibrate for 400 ms and stop:
navigator.vibrate([200, 300, 400])
can be passed 0, [], [ 0,0,0] to eliminate vibration.
Let's look at a simple example:
<body> <header> <h2>Web APIs<h2> </header> <div class="web-api-cnt"> <div class="web-api-card"> <div class="web-api-card-head"> Demo-Vibration </div> <div class="web-api-card-body"> <div id="error" class="close"></div> <div> <input id="vibTime" type="number" placeholder="Vibration time" /> </div> <div> <button onclick="vibrate()">Vibrate</button> </div> </div> </div> </div> </body> <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>
There is an input box and a button here. Enter the duration of the vibration in the input box and press the button. Our device will vibrate for the time entered.
Related resources:
Broadcast Channel API allows different browsing from the same origin Context communicates messages or data. Among them, browsing context refers to windows, tabs, iframes, workers, etc.
BroadcastChannel
class is used to create or join a channel:
const politicsChannel = new BroadcastChannel("politics")
politics
is the name of the channel. Any context that initializes BroadcastChannel
constructor using politics
will join the politics
channel. It will receive any messages sent on the channel. Messages and can send messages to the channel.
If it is the first BroadcastChannel
constructor with politics
, the channel will be created. You can use BroadcastChannel.postMessage API
to post messages to a channel. Use the BroadcastChannel.onmessage
API to subscribe to channel messages.
Let’s look at a simple chat application:
<body> <header> <h2>Web APIs<h2> </header> <div class="web-api-cnt"> <div class="web-api-card"> <div class="web-api-card-head"> Demo-BroadcastChannel </div> <div class="web-api-card-body"> <div class="page-info">Open this page in another <i>tab</i>, <i>window</i> or <i>iframe</i> to chat with them.</div> <div id="error" class="close"></div> <div id="displayMsg" style="font-size:19px;text-align:left;"> </div> <div class="chatArea"> <input id="input" type="text" placeholder="Type your message" /> <button onclick="sendMsg()">Send Msg to Channel</button> </div> </div> </div> </div> </body> <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+"</i>: "+msg+"</span></div>" 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</i>: "+input.value+"</span></div>" displayMsg.innerHTML = displayMsg.innerHTML + newHTML input.value = "" displayMsg.scrollTop = displayMsg.scrollHeight } </script>
Here is a simple text and button. Enter your message and press the button to send it. The following initializes politicalChannel
and sets an onmessage
event listener on politicalChannel
so that it can receive and display messages.
Clicking the button will call the sendMsg
function. It sends messages to the politics
channel via BroadcastChannel#postMessage
API. Any tab, iframe, or worker that initializes this script will receive messages sent from here, so this page will receive messages sent from other contexts. Related resources:
Clipboard operations such as copy, cut, and paste are applications Some of the most common features in . The Clipboard API enables web users to access the system clipboard and perform basic clipboard operations.
Previously, it was possible to use document.execCommand
to interact with the system clipboard. The modern asynchronous clipboard API provides direct access to read and write the contents of the clipboard.
Read content from the clipboard:
navigator.clipboard.readText().then(clipText => document.getElementById("outbox").innerText = clipText );
Write content to the clipboard:
function updateClipboard(newClip) { navigator.clipboard.writeText(newClip).then(function() { /* clipboard successfully set */ }, function() { /* clipboard write failed */ }); }
Related resources:
Share API can help us implement sharing functions on web applications. It gives a mobile-native sharing feel. It makes it possible to share text, files, and links to other applications on your device.
The Web Share API can be accessed through navigator.share
method:
if (navigator.share) { navigator.share({ title: 'Baidu', text: 'Baidu', url: '<https://www.baidu.com/>', }) .then(() => console.log('Sharing successful')) .catch((error) => console.log('Sharing failed', error)); }
The above code implements text sharing using native JavaScript. Note that we can only call this operation using the onclick
event:
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 onClick={handleSharing}> <span>{label}</span> </button> ); }
Related resources: