Need a Website or app? Hire an experienced team of Web and Mobile developers with us.
Free Consultation

5 Useful Web APIs Every Front End Developer Should Know | Browser APIs

Learn about these 5 useful web apis that we believe every developer should know about.

Posted by Abdul Rahman on 03 Jun 2022
5 Useful Web APIs Every Front End Developer Should Know | Browser APIs

Application Programming Interface abbreviated as API operates as a mediator between two software or computer programs. It is a software interface that allows developers to interact with other software. Contrary to the user interface, it is supposed to be used by a developer or programmer, not by the end-user. APIs make it easy for developers to add complex functionalities to their apps without having to work with all the complex code.

In web development, an API is a set of code that let the developers interconnect to a web browser or a web server. Web APIs usually refer to the Browser APIs which are built into our web browsers. These APIs are built on top of JavaScript and allow developers to interact with the user’s browser and the computer environment. There are a lot of web APIs available that we can use to enhance the functionality and user experience of our web applications. I’ve picked a few of them which will enhance your front-end skills amazingly. So, let’s go through these web APIs

1. Web Speech API

Web Speech API provides a mechanism for developers to work with voice data in their web apps. It lets developers improve the functionality of their apps by implementing features like Voice Web Search, Speech Translation, Voice Activity Detection, etc without having to work with the low-level code. It has two main functionalities: Speech Recognition (speech to text) and Speech Synthesis (Text-to-Speech).

The SpeechRecognition interface of the Web Speech API allows us to convert voice data into text. It collects audio input from the device's microphone, processes it in the background, and eventually returns a text as the result. There's also a SpeechGrammar interface, which enables us to define a set of words or pattern of words as grammar which will be used during the speech recognition to validate the voice input.

Here’s a basic example of speech recognition.

<body>
  <div id="div" style="background-color: aquamarine; width: 500px; height: 500px"></div>
  <button id="button" onclick="toggle()"></button>

  <script type="text/javascript">
    window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
    let isRecognizing
    let recognition = new SpeechRecognition()
    recognition.continuous = true
    reset()
    recognition.addEventListener('end', reset)
    recognition.addEventListener('result', (e) => {
      for (let i = e.resultIndex; i < e.results.length; ++i) {
        if (e.results[i].isFinal) {
          div.textContent += e.results[i][0].transcript
        }
      }
    })

    function reset() {
      isRecognizing = false
      button.innerHTML = "Click to Speak"
    }

    function toggle() {
      if (isRecognizing) {
        recognition.stop()
        reset()
      } else {
        recognition.start()
        isRecognizing = true
        button.innerHTML = "Click to Stop"
      }
    }
  </script>
</body>

On the other hand, the SpeechSynthesis interface can be used to convert text content into audio. It receives a piece of text as input and plays it out of a device's speaker in the form of audio. There’s a SpeechSynthesis.getVoices() method which returns the list of voices available on the device. We can select the voice of our own choice from the list to read out the given text.

Here’s an example of SpeechSynthesis which reads out the entered text.

<body>
  <textarea id="textarea" cols="30" rows="10"></textarea>
  <button onclick="speak()">Read</button>

  <script type="text/javascript">
    const speak = () => {
      speechSynthesis.speak(new SpeechSynthesisUtterance(textarea.value));
    }
  </script>
</body>

2. Push API

The Push API enables developers to send asynchronous push messages to their web apps from a server even when the app isn't running in the foreground on the user's device. This way users can get notified about the time-sensitive information even without opening the app. These notifications are shown to the user outside of the app on the system level.

The push notification flow consists of multiple steps which are as follows:

  • The web app should have an active service worker in order to receive push notifications. A service worker is a kind of web worker. It is usually a JavaScript file that operates as a proxy between your web app and the webserver. It runs independently from the main web app in a different thread in the background. It's responsible for handling network requests and pushing the notification. So, First of all, a service worker needs to be registered.
  • Once the service worker is registered, the web app should ask for the user's permission to push the notifications. The user needs to grant permission to the app in order to receive the notifications.
  • If the user grants permission, subscribe to the push notification by using PushManager.subscribe(). For this, an application server key also known as the VAPID key is needed which is basically a string. The key is used for security reasons so that only your server can push notifications to your web app. Calling PushManager.subscribe() creates a PushSubscription object which contains all the information required to send the notification. Basically, it includes an endpoint and the encryption key. All of these are done on the client-side only.
  • Now, the above-created PushSubscription object needs to be sent to the server where it'll be stored in the database for later use.
  • Now that all the required details are stored on the server, the push message can be sent by the server. The server makes an API call with all the required data which triggers the push event to the client.
  • Now, the service worker that already has a push event listener will handle the push event and will display the message to the end-user. The service worker can do anything with all the available data and display the notification to the user.

Here’s a basic example of what the client-side code would look like.

//service-worker.js file
this.onpush = event => {
  console.log(event.data)
  // display notification
}

// app.js file
const subscribe = async () => {
  try {
    const APP_SERVER_KEY = "XYZ-ABC-MUI"
    const serviceWorkerRegistration = await navigator.serviceWorker.register(
      "service-worker.js"
    )
    const pushSubscription =
      await serviceWorkerRegistration.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(APP_SERVER_KEY),
      })
    // pushSubscription object to be sent to the setver
    console.log(pushSubscription)
  } catch (err) {
    console.log(err)
  }
}

// copied urlBase64ToUint8Array function from web-push docs
const urlBase64ToUint8Array = base64String => {
  const padding = "=".repeat((4 - (base64String.length % 4)) % 4)
  const base64 = (base64String + padding).replace(/\-/g, "+").replace(/_/g, "/")

  const rawData = window.atob(base64)
  const outputArray = new Uint8Array(rawData.length)

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i)
  }
  return outputArray
}

subscribe()

3. Geolocation API

Web applications often need access to the user's location for various reasons. To get the location of a user the Geolocation API is used. Using the API, we can retrieve a user's geographical location data quite easily. Since the location carries sensitive information, browsers can't get access to the user's location without his consent. The user needs to grant permission to the web application in order to share his location. The Geolocation API has a couple of methods that are of great use. Two of its main methods are: getCurrentPosition() and watchPosition() method.

As the name suggests, the getCurrentPosition() method is used to obtain the current location of the user. While the watchPosition method is used to watch the changes in the current location of the user. It registers a handler function which gets called every time user's location changes. The watchPosition method returns a unique ID that is associated with the handler function. Calling the Geolocation.clearWatch() method with the ID unregisters the handler.

Both of the above-mentioned methods take three parameters:

  • A success callback function that takes the GeolocationPosition object as its only parameter. It's a required parameter.
  • An optional error callback function that accepts the GeolocationPositionError object as its only parameter.
  • An optional options object that can have these three fields: enableHighAccuracy, timeout, maximumAge
// calling the getCurrentPosition method will ask for user's permission first
navigator.geolocation.getCurrentPosition(
  location => console.log(location.coords),
  err => console.log(err.message)
)

// if the user grants the permission
// Output: {
//   accuracy: 8526.421985939747;
//   altitude: null;
//   altitudeAccuracy: null;
//   heading: null;
//   latitude: 324.8466937;
//   longitude: 93.946166;
//   speed: null;
// }

// if the user denies the request
// Output: User denied Geolocation

// watchPosition watches user's current location and logs the new locations coords whenever location changes
const watcherId = navigator.geolocation.watchPosition(location =>
  console.log(location.coords)
)

// clearWatch will remove the above registered watcher
navigator.geolocation.clearWatch(watcherId)

4. Fullscreen API

There are often scenarios when we want to show something to the user in full-screen mode whether it be a game, a video, or anything else. The Fullscreen API lets developers do exactly the same as it's used to display an HTML element and its descendants in full-screen mode hiding all the browser UI components.

The Fullscreen API doesn't have an interface of its own, rather it adds some very useful methods and properties to the Document and Element interfaces that make it easy for developers to work with it. These methods and properties are as follows:

document.fullscreenEnabled: The fullscreenEnabled property is used to check whether the content can be displayed in the fullscreen mode or not.

document.fullscreenElement: The property returns the element which is being shown in the Fullscreen mode. It returns null if the fullscreen mode isn't enabled.

Element.requestFullscreen(): This method is used to display the element in fullscreen mode.

Document.exitFullscreen(): This method is used to exit the Fullscreen mode.

<body>
  <video
    src="https://rr3---sn-4g5e6nsd.googlevideo.com/videoplayback?expire=1654028762&ei=eiWWYqnmFdbn1gbwzKOYBA&ip=154.55.88.174&id=o-ACJ3MeBCLgGimloNCaXahVJNQQd6O0dOmapkfS2zYtYx&itag=22&source=youtube&requiressl=yes&mh=T7&mm=31%2C29&mn=sn-4g5e6nsd%2Csn-4g5edndz&ms=au%2Crdu&mv=m&mvi=3&pl=25&initcwndbps=472500&spc=4ocVCy0C_R650rBfQETC39HI01XN&vprv=1&mime=video%2Fmp4&ns=JhmIn8-oIcAOrnwdh8VnkG4G&cnr=14&ratebypass=yes&dur=88.723&lmt=1638276430700030&mt=1654006154&fvip=5&fexp=24001373%2C24007246&c=WEB&txp=6211224&n=ItO4AWVMAMwkX2Mn35r4&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cspc%2Cvprv%2Cmime%2Cns%2Ccnr%2Cratebypass%2Cdur%2Clmt&sig=AOq0QJ8wRQIhAPJ3ZQjoYH2oXmEauFgGfRopMopA9cfA11LxiRsjSzmRAiBrFfWqm2Y1Qs3zgVeNK_4lfJBeD0mFSIRYgdqHh7QHdQ%3D%3D&lsparams=mh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=AG3C_xAwRQIhAPooWF4QFZ0AXFy6PibNXQ3mI9RdjdtHYgozGrnMkyQEAiA2c3bp7RFi2tmgWrqL6pQ4mcDhKGuBv2LSBzgWsRUyiw%3D%3D"
    id="video"
    autoplay
  ></video>
  <button id="button">Enter Full-screen mode</button>
  <script type="text/javascript">
    button.addEventListener('click', () => video.requestFullscreen())
  </script>
</body>

5. Permissions API

As we discussed earlier in the blog, there are some web APIs that need the user's permission in order to operate. What if want to check whether the permission has been granted or not to a particular API. So here, we have the solution, The permissions API can be used to get the current status of the API permissions. The API also lets us watch for permission state changes.

Earlier when Permissions API wasn't available, different APIs used to handle their own permission. Let's say, if we want to know the permission state of the Geolocation API, we needed to call the getCurrentPosition method. On the other hand, we could directly check the permission state of the Notifications API. All the APIs had their own way of handling the permissions. There are tons of web APIs available, and it's not easy for developers to remember how each API works. But now, with the Permissions API, we can manage the API permissions in one place without having to remember how each and every API handles its permission.

Permissions API is still in its early stages. So, developers need to be careful and should check for browser compatibility before using it in production. As of now, only Permissions.query() method can be used. The query method accepts a permissionDescriptor object as its only parameter. The permissionDescriptor object contains a name field. The value of the name field is the name of the API whose permission we want to obtain. The query method returns a promise that resolves to a PermissionStatus object. The PermissionStatus object has two fields: name and status. It also has a change event that gets triggered whenever the state changes.

navigator.permissions.query({ name: "geolocation" }).then(permissionStatus => {
  console.log(permissionStatus.state) // Possible outputs: granted || denied || prompt
  permissionStatus.onchange = function (e) {
    const newState = e.target.state
    if (newState === "granted") {
      // perform any action which requires user's location
    } else if (newState === "promt") {
      // ask user to share location, then perform any action which requires user's location
    } else {
      console.log("Access denied")
    }
  }
})

That's all for this blog. Hope you got to learn something.


Need a Website or app? Hire an experienced team of Web and Mobile developers with us.
Free Consultation

Related Services.



Hire ReactJS Developers
Hire Gatsby Developers
Hire NextJS Developers

We support the Open Source community.



Have a Project in mind?