5 JavaScript Web APIs To Boost Mobile User Experience For Web Apps
Tags: webdev, javascript, api
Published: 2023-07-19 09:51:10



 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/odwwny8c0d7k6ho9rzdr.png)


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.

```javascript
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
```

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

Resources:
[use Vibration API in your website](https://dev.to/bibekkakati/how-to-use-vibration-api-in-your-website-4dp4) 
[MDN Vibration API](https://developer.mozilla.org/en-US/docs/Web/API/Vibration_API)



### 2. Contact Picker API

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4aqbnh459ak7bpqa7gpt.png)


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.

```javascript 

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)
}
}
```

Resources:
[Contact Picker API](https://web.dev/contact-picker/)
[How to access contacts from the address book](https://web.dev/patterns/web-apps/contacts/)
[MDN:Contact picker](https://developer.mozilla.org/en-US/docs/Web/API/Contact_Picker_API)



### 3. Web Share API

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k9ulgzovn5kjeikz6i7k.png)


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. 

```javascript
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);
  }
};

```
Resources:
[web dev](https://web.dev/web-share/)
[MDN web share](https://developer.mozilla.org/en-US/docs/Web/API/Web_Share_API)



### 4. Media devices


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/knntu45ovkqxlskvdrkj.png)



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.

```javascript
// 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);

```

There exists libraries that wraps around this API only exposing the necessary properties for streaming video and audio, e.g [react-webcam](https://www.npmjs.com/package/react-webcam) for React applications.


[Web dev](https://web.dev/getusermedia-intro/)
[MDN Media devices](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices)




### 5. Web OTP



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1uau0hkk6elwaseide31.png)



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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/554t3dyei0ubyj4nr71a.png)

Here is a comprehensive code documentation on implementation  and the best practices of web OTP by the [Google Chrome team](https://developer.chrome.com/articles/web-otp/)


Resources:
[MDN Web OTP](https://developer.mozilla.org/en-US/docs/Web/API/WebOTP_API)

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](https://web.dev/learn/pwa/capabilities/)