DEV Community

Cover image for 5 JavaScript Web APIs To Boost Mobile User Experience For Web Apps
Vincent Kipyegon
Vincent Kipyegon

Posted on

5 JavaScript Web APIs To Boost Mobile User Experience For Web Apps

In this article we will look at some JavaScript APIs that can bolster web applications leverage mobile native features. Additionally, these APIs have a simple and straightforward syntax implementation. We will use WhatsApp as a point of reference between native apps and web apps.

The web APIs in question include:

  1. Vibration API
  2. Contact picker API
  3. Web Share API
  4. Media devices
  5. Web OTP

1. Vibration API

Image description

Vibration provides a haptic trigger that notifies a user of certain call to action or feedback. This API is dominant across most mobile OS. On WhatsApp, Vibration can be felt whenever a new message arrives, on the web, vibration is only supported on mobile device operating systems and ignored in computer OS.

The syntax is one line of code that gets your device vibrating.

navigator.vibrate(300) //vibrates for 3 milliseconds
navigator.vibrate([200,100,200])// vibrates for 2 milliseconds, pauses for a millisecond then vibrates for another 2 milliseconds
Enter fullscreen mode Exit fullscreen mode

Feature detection is not necessary as the API is ignored on devices that do not support it

Resources:
use Vibration API in your website
MDN Vibration API

2. Contact Picker API

Image description

The contact picker API allows a user to access, select and share one or multiple contacts from the phone’s contact book. The API picks the users phone name, telephone,email, address and icons. This is a common feature available on mobile device OS, WhatsApp allows users to share contacts or create chats by selecting users from the contacts list.

Its usage on the web begins with feature detection then opening of the contact book; the contact object of the navigator window object has a select method that takes 2 parameters (an arrays of values to return from contact book and optional object for indicating whether to return single or multiple contacts) and returns a promise when invoked.


const getContacts= async ()=>{
const info = ['name',  'tel', 'address', 'icon'];
const options = {multiple: false};
try {
if("contacts" in navigator){
  const contacts = await navigator.contacts.select(info, options);
  console.log(contacts);
/*
[{
  "email": [],
  "name": ["John DOe"],
  "tel": ["+254-790-377-7301"]
}]*/
return contacts
}
} catch (error) {
  console.error(error.message)
}
}
Enter fullscreen mode Exit fullscreen mode

Resources:
Contact Picker API
How to access contacts from the address book
MDN:Contact picker

3. Web Share API

Image description

Mobile operating systems have robust capabalities of sharing content from one platform to another. The web share api is a seamless feature available for browsers on mobile devices that allows users to share content from a web page to other platforms such as social media, email or even other websites. It is similar to share feature on WhatsApp that allows users to share files,text and links outside of WhatsApp.

Mobile operating systems have robust capabalities of sharing content from one platform to another. The web share api is a seamless feature available for browsers on mobile devices that allows users to share content from a web page to other platforms such as social media, email or even other websites. It is similar to share feature on WhatsApp that allows users to share files,text and links outside of WhatsApp.

const shareBlog = async () => {
  let title = `5  javascript web apis to improve user experience for web apps on mobile devices`;
  let text = `check out the blog`;
  let link = `https://dev.to/kipyegonline/5-javascript-web-apis-to-boost-mobile-user-experience-for-web-apps-5h8d-temp-slug-2587123`;
  try {
    if ("share" in navigator) {
    }
    const response = await navigator.share({ title, text, url: link });
    console.log("Blog shared successfully!");
  } catch (error) {
    console.error(error.message);
  }
};

Enter fullscreen mode Exit fullscreen mode

Resources:
web dev
MDN web share

4. Media devices

Image description

Another capability provided by mobile devices operating system access to device hardware such as the camera and microphone. The media devices allows an application to receive media stream from device microphone and camera as well as sharing the screen.

On the web; the MediaDevices API requests permission from the user to access either camera or audio or the both. The API returns a promise which if it resolves returns media streams or simply blocked if rejected. As usual we perform feature detection on the window navigator object.

// assuming we have the HTML elements in place
const video = document.getElementById("video");
const myCanvas = document.getElementById("pic-canvas");

let tracks = null;

async function getUSerMediaDevices() {
  let props = { video: true, audio: false, width: 300, height: 400 };

  try {
    if ("mediaDevices" in navigator) {
      const stream = await navigator.mediaDevices.getUserMedia(props);

      video.srcObject = stream;
      tracks = stream.getTracks();
    }
  } catch (error) {
/* the user blocked the camera or their device does not support media devices */
console.error(error.message)
}
}

function stopStreamedVideo() {
  if (tracks !== null) {
    tracks.forEach((track) => {
      track.stop();
    });
    video.srcObject = null;
  }
}

startBtn.addEventListener("click", getUSerMediaDevices);
stopBtn.addEventListener("click", stopStreamedVideo);

Enter fullscreen mode Exit fullscreen mode

There exists libraries that wraps around this API only exposing the necessary properties for streaming video and audio, e.g react-webcam for React applications.

Web dev
MDN Media devices

5. Web OTP

Image description

The best is saved until last! One Time Passwords are a type of application communication that sends users a verification code by SMS. OTPs are helpful for two-step verification, user phone number verification, and online payment confirmation.

Majority of mobile applications send SMS codes to users where they can input them manually,however, some apps can automatically detect,extract and input the OTP without requiring manual input. WhatsApp sends OTP when verifying the user phone number and the OTP is automatically populated to the input field.

This is possible on the web, web application can implement this feature for mobile web apps/website to automatically autofill SMS OTPS.

The Web OTP API is simple to use and begins by detecting the OTPCredential object on the window and executing the code from navigator.credential.get window method , setting the autocomplete attribute on HTML input to "one-time-code".

Image description

Here is a comprehensive code documentation on implementation and the best practices of web OTP by the Google Chrome team

Resources:
MDN Web OTP

This is just the tip of the iceberg; there are countless ways in which a web application might benefit from native features of mobile operating systems and hardware.
Read more JavaScript Web APIs for mobile OS devices here on web Dev by Google Chrome team

Top comments (0)