RemixNode's Blog

TwitterGitHub
10 lesser-known Web APIs you may want to use

10 lesser-known Web APIs you may want to use

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.

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:

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 website, just by typing the name of it. image.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

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.

full_screen.gif

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

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.

<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,

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/

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

image.png

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

clip_board.gif

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

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,

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,

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() function as it is obsolete now.

Direct link to the demo: 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.

resizer.gif

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

<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.

<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.

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.

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/

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.

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

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

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.

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.

const videoOff = () => {
   track.stop();
 }

chrome_Umvi16wUlu.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/

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),

broadcast.gif

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

 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.

const sendMessage = () => {
   bc.postMessage(message);
}

At the receiving end, whoever is listening to the broadcast will be notified with the message sent.

 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/

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,

console.log(performance.memory);

image.png

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

const [entry] = performance.getEntriesByType("navigation");
console.table(entry)

image.png

Direct link to the demo: 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,

battery.gif

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

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/

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.

console.log(navigator.connection);

image.png

Direct link to the demo: 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.

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/

10. 🤙 Bluetooth API

This web API allows you to connect to the bluetooth devices.

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/

...and there are more

  • Payment Request API: Provides a consistent user experience for both merchants and users for payments.
  • 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: Provides events you can watch for to know when a document becomes visible or hidden
  • 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 sooner.

Further reading


If it was useful to you, please Like/Share so that, it reaches others as well. To get email notification on my latest posts, please subscribe to my blog by hitting the Subscribe button at the top of the page. The cover image is an improvisation on top of a cool work from freepik.

Follow me on twitter @tapasadhikary for updates and technical discussions.