As developers, we frequently use APIs (Application Programming Interfaces) to implement complex functionalities easily or create them to abstract complexity. APIs are what allow services to talk to each other and do things like post a Tweet or display a map.
We can classify web APIs into two categories for building client-side web applications:
Let’s go through some of the popular Web APIs:
Document
interface, Window
interface, and so on<canvas>
element, which is useful for HTML games and chartsIn this article, I’ll be exploring some of my favorite APIs that provide mobile-friendly functionality. This can include anything from social media shares and clipboard operations to contact, speech, and notifications functionalities.
So far, we’ve discussed some common APIs that you’ve made use of directly or indirectly through JavaScript libraries.
In this section, we’ll explore five unique APIs that you might need for your next project. These APIs are important because they bring mobile native functionalities to the web.
This API helps you implement sharing functionality on your websites. It gives that mobile native-sharing feel. It makes it possible to share text, files, and links to other applications on the device.
The Web Share API is accessible through the navigator.share
method:
if (navigator.share) { navigator.share({ title: 'Logrocket alert here', text: 'Check out Logrocket', url: '<https://logrocket.com/>', }) .then(() => console.log('Successful share')) .catch((error) => console.log('Error sharing', error)); }
The code snippet above exemplifies how to share text using vanilla JavaScript. One important thing to take note of is that you can only invoke this action with 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> ); }
The code snippet above is a basic example of how to use the API with React to implement sharing options on your app. You can check out this demo on CodeSandbox.
N.B., as of today, Web Share is not supported by the Chrome desktop browser, but it works on the Android browser.
<template> <div id="app"> <div v-if="webShareApiSupported" class="refer-wrapper"> <p class="refer-text"> Share your referal code: <span class="theCode">{{ referralCode }}</span> with a friend and earn when they sign up </p> <button @click="shareNow">Share</button> </div> </div> </template> <script> export default { name: "App", data() { return { referralCode: "Fss4rsc", }; }, computed: { webShareApiSupported() { return navigator.share; }, }, methods: { shareNow() { navigator.share({ title: "Refferal Code", text: this.referralCode, }); }, }, }; </script>
If you’re working with Vue, the code snippet above shows a basic implementation of the Web Share API. Check the full demo.
Most mobile apps tend to request access to your contacts or phonebook. This is yet another mobile functionality that’s also available on the web.
Let’s say you’re implementing an airtime recharge feature for a fintech web app. You would want the user to select a contact or multiple contacts. This can be implemented using navigator.contacts
. It accepts two arguments: properties
, an array containing the property you want to access, and options
:
const props = ['name', 'tel',]; const opts = { multiple: true }; async function getContacts() { try { const contacts = await navigator.contacts.select(props, opts); handleResults(contacts); } catch (ex) { // Handle any errors here. } }
If you’re working with React, you can implement the contact picker feature like this:
export default function Contact({ label }) { const properties = ["name", "tel"]; const options = { multiple: true }; const handleGetContacts = () => { try { const contacts = navigator.contacts.select(properties, options); return contacts; } catch (ex) { console.log(ex); } }; return ( <> <button onClick={handleGetContacts}> <span>{label}</span> </button> </> ); }
You can check the React Contact Picker demo on CodeSandbox.
Working with Vue? You’re not left out. This is how you could implement this feature with Vue:
<template> <div id="app"> <div v-if="contactApiSupported"> <div class="contact-wrapper"> <h4>Select Contacts</h4> <button @click="pickContact">Select Contact</button> </div> </div> </div> </template> <script> export default { name: "App", computed: { contactApiSupported() { return "contacts" in navigator && "ContactsManager" in window; }, }, methods: { pickContact() { const properties = ["name", "tel"]; const options = { multiple: true }; try { const contacts = navigator.contacts.select(properties, options); return contacts; } catch (ex) { console.log(ex); } }, }, }; </script>
You can check the Contact Picker demo for Vue on CodeSandbox.
N.B., this API will only work on mobile browsers.
Clipboard operations such as copying, cutting, and pasting are some of the most common features in mobile apps. The Clipboard API enables a web user to access the system clipboard and perform basic clipboard operations.
Previously, you could interact with the system clipboard using the DOM document.execCommand
; some libraries still use this method. However, the modern asynchronous Clipboard API provides access to read and write the clipboard contents directly.
Let’s see how it works with JavaScript.
Reading from the Clipboard:
navigator.clipboard.readText().then(clipText => document.getElementById("outbox").innerText = clipText);
Writing to the Clipboard:
function updateClipboard(newClip) { navigator.clipboard.writeText(newClip).then(function() { /* clipboard successfully set */ }, function() { /* clipboard write failed */ }); }
Check out this post if you’re trying to implement the Clipboard API with React.
For Vue developers, you can implement the copying text with the API like this:
<template> <div id="app"> <p>Copy this:</p> <input v-model="code" /> <button v-if="supportCBApi" @click="copyMessage">Copy</button> <div v-if="message">{{ message }}</div> </div> </template> <script> export default { name: "App", data() { return { message: "", code: "FC Barcelona for ever", supportCBApi: false, }; }, created() { if (navigator.clipboard) { this.supportCBApi = true; } }, methods: { copyMessage() { navigator.clipboard .writeText(this.code) .then(() => { console.log("Text is on the clipboard."); this.message = "Code copied to clipboard."; }) .catch((err) => console.error(err)); }, }, }; </script>
Most mobile apps nowadays incorporate speech recognition and text-to-speech features to improve accessibility and user experience. The Web Speech API brings these functionalities to the browser. In this article, we’ll just discuss the SpeechRecognition
interface.
Speech recognition is accessible using the SpeechRecognition
interface, and it makes use of the default speech recognition system of the device:
const SpeechRecognition = SpeechRecognition || webkitSpeechRecognition; const recognition = new SpeechRecognition(); //new SpeechRecognition object recognition.continuous = false; recognition.lang = 'en-US'; recognition.interimResults = false; recognition.onstart = function() { console.log("Speak into the microphone"); }; recognition.onspeechend = function() { // when user is done speaking recognition.stop(); } // This runs when the speech recognition service returns result recognition.onresult = function(event) { var transcript = event.results[0][0].transcript; var confidence = event.results[0][0].confidence; }; // start recognition recognition.start();
Source: MDN Speech Recognition
Let’s go through the code snippet above.
Firstly, we create a speech recognition object by assigning new SpeechRecognition
. The SpeechRecognition
object has some properties such as:
recognition.continuous
: Listens to a single result (word or phrase) when speech recognition starts. If set to true
, the speechRecognition
service keeps listening unless you stop itrecognition.lang
: The user’s language preferencerecognition.interimResults
: Returns interim results alongside final results when set to true
Also, to get our speech recognition service to work, we need to provide a callback for events such as onstart
, onspeechend
, and onresult
.
recognition.onstart
: When a user triggers this event, the speech recognition service startsrecognition.onspeechend
: This stops the speech recognition service from runningrecognition.onresult
: This event is fired once a successful result is receivedIf you want to implement this in React, go through this tutorial that shows you how to use the React Speech Recognition Hook for voice assistance.
The Web Notification API is often interchanged with the Web Push API, but they differ. The goal of the Notification API is to display information to the user while the Push API allows the service worker to handle push messages from the server even when the device is inactive.
This is now widely used by blogs and web applications to notify users when there’s a change or update to a service. One common use case for this API is when your app is a PWA (progressive web application) and you need the user to refresh the browser to get new updates to the app.
To create a notification, JavaScript has a Notification
constructor:
const message = 'Refresh to get new features'; var notification = new Notification('Savings PWA app', { body: text });
You can implement this API with your desired web framework.
So far, we’ve discussed APIs that bring that native mobile feel to the web. A similarity with all those APIs is that they’re widely supported by popular modern browsers.
In this section, I’ll highlight three APIs that should have widespread support among browsers in the future.
Most apps need access to your device’s power status. If you’ve noticed, mobile apps like YouTube will pause if your screen is locked; some other apps like Spotify will continue playing even if the screen is locked.
On the web, the Screen Wake Lock API allows the developer to control the power state of the device when the web app is running. However, it’s not yet supported by Firefox, Safari, and Opera Mini browsers.
Mixed reality is becoming popular nowadays thanks to the likes of Pokemon Go and Google Translate. The WebXR Device API enables developers to build awesome mixed-reality applications for the web as the range of devices that can support XR keeps on increasing.
Browsers such as Android, Opera, Safari, and Firefox still don’t support this API.
On mobile devices, NFC helps users make secure transactions and connect with other devices within a certain radius.
On the web, Web NFC will allow sites the ability to read and write to NFC tags when they are in close proximity to the user. So far, it’s only supported by Chrome for Android.
In this article, we discussed Web APIs that add mobile functionality to your project and some other APIs that should have widespread support in the future.
Building for the web means building for all types of users and devices that have access to a web browser. This is why APIs that mimic mobile functionalities are becoming a must for web developers.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowLearn how to implement one-way and two-way data binding in Vue.js, using v-model and advanced techniques like defineModel for better apps.
Compare Prisma and Drizzle ORMs to learn their differences, strengths, and weaknesses for data access and migrations.
It’s easy for devs to default to JavaScript to fix every problem. Let’s use the RoLP to find simpler alternatives with HTML and CSS.
Learn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
One Reply to "5 web APIs that add mobile functionality to your project"
Thanks for sharing a valuable information.