Welcome back to the future! This is the second article on futuristic JavaScript Web APIs, so if you haven't read the first one, you are recommended to do so here
Here are the 7 more cutting-edge JavaScript Web APIs to add an enchanting touch to your projects to make users part with their money 💰
1. Web Speech
The Web Speech API enables you to incorporate voice data into web apps. The Web Speech API has two parts:
SpeechSynthesis
(Text-to-Speech), andSpeechRecognition
(Asynchronous Speech Recognition)
// 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) => {
const speechToText = event.results[0][0].transcript;
console.log(speechToText);
};
NOTES
Even though Speech Synthesis is supported by all major browsers with 96% coverage, Speech Recognition is still a bit early to use in production with only 86% coverage.
The API CANNOT be used without the user interaction (eg:
click
,keypress
, etc).
2. Page Visibility
The Page Visibility API allows you to check if the page is visible to the user or not. This is useful when you want to pause a video.
There are 2 methods to perform this check:
// Method 1
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") {
document.title = "Visible";
return;
}
document.title = "Not Visible";
});
// Method 2
window.addEventListener("blur", () => {
document.title = "Not Visible";
});
window.addEventListener("focus", () => {
document.title = "Visible";
});
The difference between the two methods is that the second one will be triggered if you switch over to another app OR a different tab, while the first one will be triggered only if you switch over to another tab.
3. Accelerometer
The Accelerometer API allows you to access the acceleration data from the device.
This can be used to create games that use the device's motion control or add interaction if the user shakes the device, the possibilities are endless!
const acl = new Accelerometer({ frequency: 60 });
acl.addEventListener("reading", () => {
const vector = [acl.x, acl.y, acl.z];
const magnitude = Math.sqrt(vector.reduce((s, v) => s + v * v, 0));
if (magnitude > THRESHOLD) {
console.log("I feel dizzy!");
}
});
acl.start();
You can ask for Accelerometer permission using:
navigator.permissions.query({ name: "accelerometer" }).then((result) => {
if (result.state === "granted") {
// now you can use accelerometer api
}
});
4. Geo-location
The Geolocation API allows you to access the user's location.
This can be extremely useful if you are building anything related to maps or location-based services.
navigator.geolocation.getCurrentPosition(({ coords }) => {
console.log(coords.latitude, coords.longitude);
});
You can ask for Geolocation permission using:
navigator.permissions.query({ name: "geolocation" }).then((result) => {
if (result.state === "granted") {
// now you can use geolocation api
}
});
5. Web worker
Web Workers makes it possible to run a script operation in a background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.
// main.js
const worker = new Worker("worker.js");
worker.onmessage = (e) => console.log(e.data);
worker.postMessage([5, 3]);
// worker.js
onmessage = (e) => {
const [a, b] = e.data;
postMessage(a + b);
};
6. Resize Observer
The Resize Observer API allows you to observe the size of an element and handle the changes with ease.
It is exceptionally useful when you have a resizable sidebar.
const sidebar = document.querySelector(".sidebar");
const observer = new ResizeObserver((entries) => {
const sidebar = entries[0];
//Do something with the element's new dimensions
});
observer.observe(sidebar);
7. Notification
Ah, Notifications! The annoying little popups (or bubbles of dopamine, based on where you lie on the spectrum).
The Notification API, just as the name suggests, allows you to send notifications to annoy users (bundle it with the Page Visibility API to annoy them even more 😈)
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
new Notification("Hi there!", {
body: "Notification body",
icon: "https://tapajyoti-bose.vercel.app/img/logo.png",
});
}
});
Side Note
Some of the APIs mentioned above are still in the experimental stage and are not supported by all browsers. So, if you want to use them in production, you should check if the browser supports them
For example:
if ("SpeechRecognition" in window || "webkitSpeechRecognition" in window) {
// Speech Recognition is supported
}
That's all folks! 🎉
Finding personal finance too intimidating? Checkout my Instagram to become a Dollar Ninja
Thanks for reading
Need a Top Rated Front-End Development Freelancer to chop away your development woes? Contact me on Upwork
Want to see what I am working on? Check out my Personal Website and GitHub
Want to connect? Reach out to me on LinkedIn
Follow me on Instagram to check out what I am up to recently.
Follow my blogs for bi-weekly new Tidbits on Dev
FAQ
These are a few commonly asked questions I get. So, I hope this FAQ section solves your issues.
-
I am a beginner, how should I learn Front-End Web Dev?
Look into the following articles: Would you mentor me?
Sorry, I am already under a lot of workload and would not have the time to mentor anyone.
Top comments (17)
Never heard of the web speech API.
I will try to learn more about it and use it in my projects.
Thanks for sharing, Tapajyoti.
JSYK, the recognition model does not run in your browser; it is sent to an external (albeit free) service to process.
Tell me more
The docs have more info. By the way, this isn't available in Firefox.
Very nice, thank you🙂
Great, thank you for sharing!
Best JavaScript web API . Thanks for sharing.
Cool to see web workers covered here. Would be interested to hear the types of things people use them for
Never heard of the Accelerometer API. Mind blown 🤯
Thank you for sharing Tapajyoti 👍
These are the posts I like. Simple, fast and, above all, useful. Thank you so much.
Got to know a lot of api's which i didn't know. Thanks for this post
Thanks for sharing the APIs. Appreciate it.
What is I did know all of them? 🤣