10 lesser-known Web APIs you may want to use
Tags: javascript, webdev, react, beginners
Published: 2020-09-04 16:35:04

`API` is the acronym for Application Programming Interface which defines interactions between multiple software architecture layers. Programmers carry out complex tasks easily using APIs in software development. Without APIs, a programmer's life would have been miserable with no proper(security, for example) access to data,  knowing unnecessary low level details etc.

When it comes to Web APIs, there are extremely useful  objects, properties and functions available to perform tasks as minor as accessing DOM to as complex as managing audios, videos, graphics, etc. 

# Some Well Known Web APIs
If you are from the web development background, you are using many of them already. Here is the list of very well known web APIs.

- [Canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API)
- [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
- [History](https://developer.mozilla.org/en-US/docs/Web/API/History_API) 
- [Geolocation](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) 
- [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model)
- [Console](https://developer.mozilla.org/en-US/docs/Web/API/Console_API)
- [Drag & Drop API](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API)

In this article, I am going to talk about 10 more web APIs that are not so popular. Lesser popular doesn't mean, they are not useful. You can use them in various use-cases of your project. Please have a look.

# tl;dr
If you would like to jump into the source code or see the demonstration immediately, here are the quick links to them:

> - [Link to the Source Code @GitHub]( https://github.com/atapas/demolab/tree/master/code/src/demos/web-apis)
- [Link to the Web API DemoLab](https://demo.greenroots.info/categories/web-apis/)
- You can follow me on twitter [@tapasadhikary](https://twitter.com/tapasadhikary) for discussions and updates.

Note: Web APIs are nothing but the interfaces, functions, objects, properties written and exposed using vanilla JavaScript. However the usage of the web APIs is not limited to the vanilla JavaScript based application alone. It is very straightforward to use them with an Angular, React or Vue based applications as well.

All the examples I have used to demonstrate the web apis in this article are written using reactjs. You can find them in the github link mentioned above. Please feel free to fork, change and use!

# A big point about Web APIs
A big (pain) point about  using a web API is, most of them are not standardized yet. It means, the support for a web API  may differ from one browser vendor to another. For example, You may find an API working with the Chrome browser but, not supported by Firefox or Edge browsers yet.

I would suggest a couple of ways to have a check on this,
- Check for the support of a web api from [Can I Use](https://caniuse.com/) website, just by typing the name of it.
 ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598949690069/-FSS3H82n.png)
- Implement a fallback or feedback if a certain web API is not supported. Most of the web APIs provide method to check if the API is supported. You can chose to implement a fallback when it is not supported or at least, inform your users by proving a feedback message.
 ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598949910284/3p-xu2oYI.png)

# Lesser Known but, Useful Web APIs
Alright, time to get started knowing them. Hope you also find these useful.
 
## 1. 📺 Fullscreen API
Do you have the need to show any of the DOM elements in full-screen mode? The full-screen use-case is very demanding for gaming applications, online video platforms(like, youtube) etc. 

The `Fullscreen API` provides methods to present a specific Element (and its children) in a full-screen mode. There is a method available to exit full-screen mode once it is no longer needed. Not only that, this API can also help to perform any actions when a DOM element transition into a full-screen mode or comes out of it.

In the example below, my favorite Santa Claus can get into the full-screen mode and come out of it with ease.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vgrbkk7gzovlrwh5g7m9.gif)

In the code below, the `manageFullScreen()` function uses  the `requestFullscreen()` API on an element which is having an id called, `fs_id`. 

```js
const manageFullscreen = () => {
   document.getElementById('fs_id').requestFullscreen();
}
```
 
This element with id, `fs_id` is a `DIV` with a child element, i.e, the Santa Clause image.

```js
<div className="column">
  <div id="fs_id">
    <Img fixed={imageData.image.childImageSharp.fixed} alt="santa" />
   </div>
                    
    <StyledButton 
         onClick={manageFullscreen}>
            Enter Fullscreen with Santa
    </StyledButton>
 </div>
```
You can check if the `Fullscreen API` is supported by the browser,

```js
if (document.fullscreenEnabled) {
   setSupported(true);
} else {
   setSupported(false);
}
```

Also watch out for the useful handlers like,
- `onfullscreenchange`: An event handler for the fullscreenchange event.
- `onfullscreenerror`: An event handler for the fullscreenerror event.

Direct link to the demo: [https://demo.greenroots.info/web-apis/web-apis-fullscreen/](https://demo.greenroots.info/web-apis/web-apis-fullscreen/)

## 2. 📋 Clipboard Async API 
What is a clipboard in comuping?

> The clipboard is a buffer that some operating systems provide for short-term storage and transfer within and between application programs.

There are mainly three operations you can perform with the clipboard. They are, `copy`, `cut` and `paste`. The Clipboard API provides the ability to respond to these three operations. 

Interestingly, copying content to the clipboard is open as in, there is no need of a user permission. However, for pasting the content from the clipboard to the user application, the user needs to grant permission for it. It is achieved using another web API called, [Permission API](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API)

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598716493747/PwPwDDK8Y.png)

Here is a simple example of the copy-paste operation,

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/q0qbmo0lhbmnw0t5w9wo.gif)

This is how to check if the feature is supported by the browser,

```js
if (navigator.clipboard 
     && navigator.clipboard.read 
     && navigator.clipboard.write) {
   setSupported(true);
} else {
   setSupported(false);
}
```
Here is the async API function for writing the content to the clipboard,

```js
async function performCopy(event) {
   event.preventDefault();
   try {
      await navigator.clipboard.writeText(copyText);
      console.log(`${copyText} copied to clipboard`);
   } catch (err) {
      console.error('Failed to copy: ', err);
   }
}
```
The Async API function to read the content from the clipboard and do something with it,

```js
async function performPaste(event) {
   event.preventDefault();
   try {
       const text = await navigator.clipboard.readText();
       setPastetext(text);
       console.log('Pasted content: ', text);
   } catch (err) {
      console.error('Failed to read clipboard contents: ', err);
   }
}
```
Note: With the inclusion of the `Clipboard Async API`, you can get rid of the usage of [document.execCommad()](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand) function as it is obsolete now.

Direct link to the demo: [https://demo.greenroots.info/web-apis/web-apis-clipboard-apis/](https://demo.greenroots.info/web-apis/web-apis-clipboard-apis/)

## 3. 🧐 Resize Observer API 
Do you want to take some actions based on the changes to the content or border box of a DOM element? Are you thinking of writing a handler by yourself? What if I tell you, there is already one provided by the web API implementation?

Here is a story about a dumb button. We use a range slider to resize the button. While the button gets resized, we also want to control the text color, without letting the button know much about it. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3ph07muigfurs92oo4u0.gif)

First, create a button and specify an id so that, we can access the button later using the id.

```js
<StyledButton id="dumbBtnId">
   I am a Dumb Button
</StyledButton>
```
Now we create a slider using the `range` input type from HTML5. A `resize()` function is invoked when the slider value changes.

```js
<div>
   <input 
         onChange={(event) => resize(event)} 
         type="range" 
         min={minRange} 
         max={maxRange} 
         defaultValue={rangeValue} />
</div>
```
The `resize()` function simply sets the width of the button as the slider range value so that, it can be resized dynamically.

```js
const resize = event => {
   const value = event.target.valueAsNumber;
   setRangeValue(value);
   let dumbBtn = document.getElementById('dumbBtnId');
   dumbBtn.style.width = `${value}px`;
 }
```
So far, so good? Now for every range value change, the button gets resized. We have a `ResizeObserver` observing this change and change the color of the button text.

```js
useEffect(() => {
   try {
            let dumbBtn = document.getElementById('dumbBtnId');
            var resizeObserver = new ResizeObserver(entries => {
                for(const entry of entries) {
                    // Get the button element and color it
                    // based on the range values like this,
                   entry.target.style.color = 'green`;
                }
      });
      resizeObserver.observe(dumbBtn);
   } catch(e) {
            setSupported(false);
            console.log(e);      
   }
}, [rangeValue]);
```
Direct link to the demo: [https://demo.greenroots.info/web-apis/web-api-resize-observer/](https://demo.greenroots.info/web-apis/web-api-resize-observer/)

## 4. 📷 Image Capture API
There are some cool and useful APIs around user media like, audio, video etc. I love the `Image Capture API` which helps us to capture an image or grab a frame from the video devices(like webcam). Not only that, you can also perform actions on capturing an image or grabbing a frame.

First, get the user media access. In this case we are getting the webcam access.

```js
navigator.mediaDevices.getUserMedia({video: true})
  .then(mediaStream => {
     document.querySelector('video').srcObject = mediaStream;
     const track = mediaStream.getVideoTracks()[0];
     setTrack(track);
  }).catch(error => {
     console.error(` ${error} is not yet supported`);
     setError(error);
});
```
Just like the clipboard paste operation, a webcam media access permission has to be granted by the user.

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598717565379/MCRNY49Tl.png)

Now Grab a frame and do something. In this example, I am just drawing the frame on a Canvas.

```js
const imageCapture = new ImageCapture(track);
    imageCapture.grabFrame()
      .then(imageBitmap => {
          const canvas = document.querySelector('#grabFrameCanvas');
          drawCanvas(canvas, imageBitmap);
    }).catch(error => {
          console.log(error);
          setError(error);
});
```
I can also take a picture and do the similar thing.

```js
const imageCapture = new ImageCapture(track);
    imageCapture.takePhoto().then(blob => createImageBitmap(blob))
      .then(imageBitmap => {
          const canvas = document.querySelector('#takePhotoCanvas');
          drawCanvas(canvas, imageBitmap);
    }).catch(error => {
          console.log(error);
          setError(error);
});
```
To stop the video streaming from the webcam, just call he method `stop()` on the running video track.

```js
const videoOff = () => {
   track.stop();
 }
```
![chrome_Umvi16wUlu.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598717833234/MPOxVZ92M.png)

Also watch out for the methods,
- `getPhotoCapabilities()`: To get the ranges of available configuration options.
- `getPhotoSettings()`: To get the current photo configuration settings.

Direct link to the demo: [https://demo.greenroots.info/web-apis/web-apis-image-capture/](https://demo.greenroots.info/web-apis/web-apis-image-capture/)

## 5. 📡 Broadcast Channel API
The `Broadcast Channel API` allows communication between browsing contexts (windows, tabs, iframes) and workers on the **same origin**. Think of a use-case like, once you logout from an app running in a browser tab, you want to broadcast it to the app instances opened in other tabs of the same browser.

Here is an example where a sender is sending a message to the receiver and the same is being broad-casted to its browsing context(it is tab in this case),

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/s6f4i5ssusf6s8acymde.gif)

First step is to create a broadcast channel by giving it a unique name. Also define the content(message) you want to broadcast.

```js
 const CHANNEL_NAME = "greenroots_channel";
 const bc = new BroadcastChannel(CHANNEL_NAME);
 const message = 'I am wonderful!';
```
To broadcast a message, call the method `postMessage()` on the channel by passing the message.

```js
const sendMessage = () => {
   bc.postMessage(message);
}
```
At the receiving end, whoever is listening to the broadcast will be notified with the message sent.

```js
 const CHANNEL_NAME = "greenroots_channel";
 const bc = new BroadcastChannel(CHANNEL_NAME);
    
 bc.addEventListener('message', function(event) {
    console.log(`Received message, "${event.data}", on the channel, "${CHANNEL_NAME}"`);
    const output = document.getElementById('msg');
    output.innerText = event.data;
 });
```
Direct link to the demo: [https://demo.greenroots.info/web-apis/web-apis-broadcast/](https://demo.greenroots.info/web-apis/web-apis-broadcast/)


## 6. ⏱️ Performance Interface API
The `Performance` interface provides access to the three major APIs, i.e, 
- Navigation
- Memory
- Timing

Here is an example of the memory usage,

```js
console.log(performance.memory);
```
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598718428077/K-JPrPyu7.png)

Here is another example of how to get several stats of a navigation performance,

```js
const [entry] = performance.getEntriesByType("navigation");
console.table(entry)
```
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598718680470/qr_lfv2hr.png)

Direct link to the demo: [https://demo.greenroots.info/web-apis/web-api-performance/](https://demo.greenroots.info/web-apis/web-api-performance/)

## 7. 🔋 Battery Status API
Do you want to know all about the battery of your laptop, PC or, devices? Yes, there is a web API for that as well, `Battery Status API`. This API helps in knowing all the information like, the battery is charging or not, how much charge is left and also the handlers to handle the charge related state changes.

Here is an example shows the state changes when I plug-in and out the charger of my laptop,

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/e329unci4gi237eto9g1.gif)

The code below explain, how to deal with the handles and work with the battery related information.

```js
navigator.getBattery().then(function (battery) {

   // handle the charging change event
   battery.addEventListener("chargingchange", function () {
      console.log("Battery charging? " + (battery.charging ? "Yes" : "No"));
   });

   // handle charge level change
   battery.addEventListener("levelchange", function () {
      console.log("Battery level: " + battery.level * 100 + "%");
   });

   // handle charging time change
   battery.addEventListener("chargingtimechange", function () {
      console.log( "Battery charging time: " + battery.chargingTime + " seconds");
   });

   // handle discharging time change
   battery.addEventListener("dischargingtimechange", function () {
      console.log("Battery discharging time: " + battery.dischargingTime + " seconds");
   });

});
```
I like this API and it is fun using it. What is not funny is, this API may get obsolete in future days.

Direct link to the demo: [https://demo.greenroots.info/web-apis/web-apis-battery/](https://demo.greenroots.info/web-apis/web-apis-battery/)

## 8. 📶 Network Information API
The `Network Information API` provides information about the network types(e.g., 'wifi', 'cellular', etc.), save data mode, bandwidth and many more.

```js
console.log(navigator.connection);
```

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598719330049/7UJuQtKra.png)

Direct link to the demo: [https://demo.greenroots.info/web-apis/web-api-network-info/](https://demo.greenroots.info/web-apis/web-api-network-info/)

## 9. 📳 Vibration API
This is another example where you can connect to the system hardware and perform operations. The `Vibration API` provides methods to start the device vibration(instant or, for a duration) and stop it.

```js
useEffect(() => {
   if (start) {
      // vibrate for 2 seconds
      navigator.vibrate(2000);
   } else {
      // stop vibration
      navigator.vibrate(0);
   }
}, [start]);
```
Direct link to the demo: [https://demo.greenroots.info/web-apis/web-apis-vibration/](https://demo.greenroots.info/web-apis/web-apis-vibration/)

## 10. 🤙 Bluetooth API
This web API allows you to connect to the bluetooth devices.

```js
navigator.bluetooth.requestDevice({
   acceptAllDevices: true
}).then(device => {            
   setDeviceName(device.name);
   setDeviceId(device.id)
   setDeviceConnected(device.connected);
}).catch(err => {
   console.log(err);
   setError(true);
})
```
Direct link to the demo: [https://demo.greenroots.info/web-apis/web-apis-bluetooth/](https://demo.greenroots.info/web-apis/web-apis-bluetooth/)

# ...and there are more

- [Payment Request API](https://developer.mozilla.org/en-US/docs/Web/API/Payment_Request_API): Provides a consistent user experience for both merchants and users for payments.
- [Touch Events](https://developer.mozilla.org/en-US/docs/Web/API/Touch_events): Provides relatively low-level APIs that can be used to support application-specific multi-touch interactions such as a two-finger gesture.
- [Page Visibility](https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API): Provides events you can watch for to know when a document becomes visible or hidden
- [Channel Messaging API](https://developer.mozilla.org/en-US/docs/Web/API/Channel_Messaging_API): Another great way of sending messages within the browsing context. However, unlike broadcasting, here it is to send 1-to-1 messages.

I shall be adding examples for each of these to the [Web API DemoLab](https://demo.greenroots.info/categories/web-apis) sooner.

# Further reading
- [Web APIs from the MDN web docs](https://developer.mozilla.org/en-US/docs/Web/API)

<hr />
If it was useful to you, please Like/Share so that, it reaches others as well. The cover image is an improvisation on top of a cool work from [freepik](https://www.freepik.com/).

- You can subscribe to my future articles from [https://blog.greenroots.info/](https://blog.greenroots.info/)
- Follow me on twitter [@tapasadhikary](https://twitter.com/tapasadhikary) for updates and technical discussions.