Simple and useful web APIs you should be using now
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
Most of us may have used blur
or focus
events on the window
object to detect whether the user is currently on the page. But this API cannot detect if the user is still seeing the page when they’re not using it, such as in the case of opening two windows on the same screen. The Page Visibility API solves this problem by telling you exactly when the page is visible or hidden. An example use case would be refreshing the page content when the page is being shown to the user, even if it’s not in focus.
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
This is a cool API that can be used to add a text-to-speech process to your web page. SpeechSynthesis is an interface of Web Speech API with multiple properties that can be customized, like an array of speaking voices, rate of speech, pitch of speech, etc. For the simplest implementation with default options, you just need three lines of code:
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
The Geolocation API is a very simple and powerful API to get the user’s current location from the browser. It gives you the latitude and longitude coordinates and can only be used in secure contexts (HTTPS). The simplest way to use it would be with the getCurrentPosition
method:
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
This API can be used to detect the amount of memory a user has on the device. Memory, in this case, refers to the installed RAM and not actual available memory. It can be very useful in cases where you want to check if the user’s device can support heavy functions and adjust user experience accordingly. And just like Geolocation, it can only be used over HTTPS. It’s very simple to use:
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
If you’re running a web app, knowing when the user has lost network connection can be really handy for providing a good user experience. For example, when a user clicks on a form’s submit button, you may want to send an email and redirect them to another page. This API can help with this situation. Imagine that the user loses their internet connection after they’ve loaded the page; they would simply be taken to the lost network connection page by the browser. You can prevent this from happening by checking if the user has network connectivity on button-click. Or even better, you may wish to show a “no network connectivity” message on your page, just like all the modern mobile apps out there.
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
The Vibration API can be used to give tactile feedback on web pages. It gives you the power to access the device’s vibration feature. This can be very useful for games that run on the browser or even for giving feedback to users in cases like an error in form fields. The API is super simple to use:
// vibrate for one second
navigator.vibrate(1000);
// turn of vibrationnavigator.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
Detecting orientation is a very helpful feature to maintain responsiveness and provide a better user experience. There are two main APIs that can help with this information.
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 ofportrait-primary
,portrait-secondary
,landscape-primary
, orlandscape-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 DeviceLightEvent API pulls information from photosensors or similar detectors about ambient light levels near the device. This can be very helpful in use cases like adjusting the brightness or changing to dark mode on your web page. But here’s another bummer from MDN: This is an experimental technology. Check the browser compatibility table carefully before using it in production.
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
The Battery Status API allows you to get the battery information of a mobile or desktop device. Example uses would be cases like alerting the user when the battery is low or saving the user’s data when the battery goes below a certain level. But here’s a disclaimer from MDN before you use it:
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