Web APIs that you should use for a Better UX

Simple and useful web APIs you should be using now

Nabil Nalakath
Oct 21, 2019 · 8 min read
BG image by — Jesus Kiteque on Unsplash

Web APIs are some of the most powerful tools out there to take advantage of browser capabilities and provide users with an experience that’s as good as native apps. In this article, we’ll explore some of the most useful web APIs, which you may or may not have heard of. Either way, these are the APIs that you should definitely be using to optimize your app for improved user experience. We’re almost into the next decade; if you haven't realized it already, user experience really matters if you want your product to survive.

Note: Some of these APIs are still in development or not supported in some browsers. Make sure you read the full documentation before using them.


Page Visibility

window.addEventListener('visibilitychange', ()=>{
if(document.hidden){
console.log('Page Hidden');
} else{
console.log('Page Shown');
}
});

The visibilityState property offers four different values: visible, prerender, hidden, and unloaded. Here’s the browser compatibility:

Information provided by- caniuse.com

Speech

let synth = window.speechSynthesis;
let speakthis = new SpeechSynthesisUtterance('hello world');
synth.speak(speakthis);

And for customizations, you can set each property separately:

let voices = synth.getVoices();
speakthis.voice = voices.find( voice => voice.name === 'Monica');
speakthis.rate = 0.5;
speakthis.pitch = 0.4;
synth.speak(speakthis);

There are some voices which are available only in certain browsers; other than that, support looks good:

Information provided by- caniuse.com

Geolocation

navigator.geolocation.getCurrentPosition((position) => {
console.log(position.coords.latitude, position.coords.longitude);
});

This method will give you lat-long coordinates of the user. It also has a method called watchPosition which can be used to detect changes in position. This API can be very useful when you want to use the location of the user to give accurate information. It has some additional properties like accuracy and altitude which can be used along with lat-long. Example use cases could include showing the nearest events on a map or auto-filling location information on a form.

It has universal support across all modern browsers:

Information provided by- caniuse.com

Navigator.deviceMemory

console.log(navigator.deviceMemory);

There is a threshold of lower and upper values to protect users of very low- or high-end devices. So if you have a laptop with 16GB memory, it will return only 8. The possible values are 0.25, 0.5, 1, 2, 4, and 8. This is an experimental feature and browser support is limited as of now:

Information provided by- caniuse.com

Online State

When you want to check status on button-click on particular events, you can use a one-liner like:

console.log(navigator.onLine ? 'online' : 'offline');

Or if you want to always listen for the event:

window.addEventListener('offline',networkStatus);
window.addEventListener('online',networkStatus);
function networkStatus(e){
console.log(e.type);
}

Here’s the browser compatibility for this API:

Information provided by- caniuse.com

There is also a Network Information API that can be used to detect the type of network connection a user is currently on (wifi, cellular, etc.).


Vibration

// vibrate for one second
navigator.vibrate(1000);
// turn of vibration
navigator.vibrate(0);
// vibrate in a pattern => [vibrate,wait,vibrate,wait,vibrate]
navigator.vibrate([500,400,700,400,6000]);

Note: Calls to navigator.vibrate will immediately return false if the user hasn’t tapped on the frame or any embedded frame yet.

You can find the code for some cool theme vibrate patterns like Mario, Star Wars, and more here. Unfortunately, browser support is limited as of now:

Information provided by- caniuse.com

Orientation

The first one is DeviceOrientationEvent, which is an experimental API, and you should be careful before using it. This API gives three useful values:

  • alpha represents the motion of the device around the z-axis, represented in degrees with values ranging from 0 to 360.
  • The beta value represents the motion of the device around the x-axis, represented in degrees with values ranging from -180 to 180. This represents a front-to-back motion of the device.
  • The gamma value represents the motion of the device around the y-axis, represented in degrees with values ranging from -90 to 90. This represents a left-to-right motion of the device.

Usage is very simple:

window.addEventListener('deviceorientation', function(event) {
console.log(event.alpha + ' : ' + event.beta + ' : ' + event.gamma);
});

Warning from MDN: Currently, Firefox and Chrome do not handle coordinates the same way. Take care regarding this while using the API with them.

An example use case for this API would be rotating a 3D image or logo based on the device orientation. The browser support also looks good as of now:

Information provided by- caniuse.com

Another API that can be used for detecting orientation is the Screen.orientation API. It’s a very straightforward API that contains two main properties:

  • type returns one of portrait-primary, portrait-secondary, landscape-primary, or landscape-secondary, based on the screen orientation.
  • angle returns the angle of rotation of the device. Eg- 0°, 90°, etc.

The support for this API is limited, as you can see below:

Information provided by- caniuse.com

DeviceLightEvent

The API is very simple to use:

window.addEventListener('devicelight', function(event) {
console.log(event.value);
});

I checked it on Firefox and it did respond to events like turning off the light and moving a hand close to the webcam. If browser compatibility is improved there are tons of applications for this handy API; meanwhile, here’s the browser support as of October 2019:

Information provided by- caniuse.com

Battery Status

This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.

If you still decide to go ahead and use it, the API is pretty simple. The getBattery() method on the navigator object is a promise which will give you the battery object, on which you can set event listeners.

navigator.getBattery().then(battery =>{
console.log(`${battery.level * 100}%`);
battery.addEventListener('levelchange', ()=> {
console.log(`${this.level*100} %'`);
});
});

The API contains many other methods to detect charging, discharging, charging time, etc. But, as mentioned above, use it with caution since the API support may be revoked from browsers at any time. Here’s the browser compatibility for Battery Status. To find other battery API compatibilities, visit the link given in the image description:

Information provided by- caniuse.com

Better Programming

Advice for programmers.

Nabil Nalakath

Written by

Sapiophile. I Speak Code, love literature, binge thrillers, enjoy bibliosmia, and seek adventures.

Better Programming

Advice for programmers.

More From Medium

More from Better Programming

More from Better Programming

More from Better Programming

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade