Let's talk JS ⚡: Web APIs

JavaScript allows developers to create amazing interactive experiences for users across different browsers. In fact, that's why all web content got so much more immersive in the last couple of years - because of JS! But just one programming language is not enough to harness the power of the web. No, no. You need a lot more than just that! Sure, there are tons of JS builtin types, objects, classes etc. providing different functionalities even at the low-level code. But that's still not enough. JavaScript is sandboxed inside the browser, having no access to the outside world on its own. I'm talking here about such features like multi-threading, 3D graphics, controls, computer's state (battery, connectivity, memory etc.) and counting. That's why Web APIs exist. Web APIs is a term referencing to all APIs (Application Programming Interface) provided by the browser to access different native functionalities of devices through JS code. In addition among the Web APIs, there are such individuals as DOM API for accessing DOM (HTML integration) and CSS API for, naturally, CSS. Just to note, these are APIs because they can be accessed from not only JavaScript but other languages too, such as unpopular VBScript in IE back in the day. Now, with this out of the way, you've probably used at least one of Web APIs at some point in time. You may not even know it, because of the plethora of libraries providing easier to use interfaces to great many of them. One of them could most likely be DOM, CSS, Audio, or even Canvas/WebGL API. These are big, complex APIs that may require some time to learn. But believe me, it's worth it!


Get to know each other

Besides above-listed API, there are a lot more. I would like to introduce you to some of them... at least the smaller ones. It is worth mentioning that APIs are naturally not something that can be polyfilled by e.g. Babel or other tools. That's why browser support is extremely important in this field. Some might not even be considered official and supported by only specific browsers. Only those having good cross-browser support and/or being marked officially as part of the W3C specification are included in this list. Of course, many of them are quite new and you should check something like CanIUse or other similar tools before using it in production. With this in mind let's take a look at some of the most underrated or rather not-so-popular/well-known Web APIs.


Service Worker & Push API

Service Worker (SW) and Push API are both pretty new but highly-demanded APIs. SW acts as a background process to allow for interacting between the server and web app, even when its close. It's deeply related to Push API which allows receiving messages send (pushed) by the server. You see a pattern here, right? The server sends some data, your web app through SW and Push API interacts with it and e.g. shows notification (with help from some additional SW methods provided by Notification API)  as a result. These APIs serve mainly as a big step forward in an idea to make web apps feel more native. Anyway, the whole concept might seem a little bit complex. The basic workflow requires you to download, install and activate your Service Worker. As for the Push API, you need to subscribe to server messages using e.g. Fetch API. This would require a single article on its own, so, for now, I'll leave it for you to explore this topic further. Keep in mind the browser support - you should get familiar with Safari's custom implementation of Push API.


Crypto API

Continuing on the list of complex APIs, here comes the Crypto. This API allows developers to use cryptographic primitives for, naturally, cryptographic purposes. Surprisingly, it has fairly good browser support with even IE 11 having partial (prefixed) support for it. It might be one of the most mysterious API of all. It's most likely due to its use cases. Quoting MDN Web Docs:

If you're not sure you know what you are doing, you probably shouldn't be using this API.

So, unless you're doing this cryptographic stuff, maybe it will be better to leave this one alone with just knowing that it exists.


Payment Request API

This is the point where things start to get a little more... usable. 😅 Payment Request API is an effort to provide an easy way of proceeding online purchases in a standard, unified way but only over HTTPS for obvious reasons. Sadly, this is awesome but the fresh idea doesn't have good enough cross-browser support for being considered reliable. But, as it's a W3C standard, support will grow and eventually we'll all have an easy way to make online payments. For now, let's take a look at this early API, shall we?

if (window.PaymentRequest) {
  const payment = [
    {
      supportedMethods: "basic-card",
      data: {
        supportedNetworks: ["visa", "mastercard"],
        supportedTypes: ["debit", "credit"]
      }
    }
  ];

  const cart = {
    id: "order-1",
    displayItems: [
      {
        label: "Example item",
        amount: { currency: "USD", value: "1.00" }
      }
    ],
    total: {
      label: "Total",
      amount: { currency: "USD", value: "1.00" }
    }
  };
  const request = new PaymentRequest(payment, cart);

  request
    .show()
    .then(function(response) {
      response.complete("success").then(function() {
        // Handle success
      });
    })
    .catch(function(error) {
      // Handle cancellation or failure.
    });
} else {
  // Payment Request API is unsupported
}

This is the most straight-forward example that I can think of. First, we check if API is available for use. Then there are some hard-coded data defined for later use. And finally comes the main call. Everything after that just showcases how easy it is to display the payment modal and handle different outcomes. What's left is only to wait for this to get better cross-browser support. Fingers crossed. 😁


Performance API

As the name implies, Performance API or rather User Timing API can be used to measure the performance of your JavaScript code. And, believe me, or not, it does its job quite well. With accuracy up to a thousandth of a millisecond it is probably one of the best tools for the job. Browser support is unsurprisingly good with even IE 10 supporting it. Now, this API gives you access to many small methods for benchmarking purposes. You can retrieve timings, set time-marks and observe different performance-related events. For sake of things, let's take a look at a basic example. First, let's define a function that we'll be benchmarking.

function benchmarkMe(){
    for(let i = 0; i < 1000; i++){
        console.log(i)
    }
}

Yup, standard loop with 1000 of console.log()s can be quite demanding.

const timeBefore = performance.now();
benchmarkMe()
const timeAfter = performance.now();
console.log(`BenchmarkMe() took ${timeAfter - timeBefore} ms.`);

This can be familiar to you. Let's say that it's the standard way to measure performance in JS. Now, let's try a bit more exotic way...

performance.mark("timeBefore")
benchmarkMe()
performance.mark("timeAfter")
performance.measure("time", "timeBefore", "timeAfter")
console.log(`BenchmarkMe() took ${performance.getEntriesByName("time")[0].duration} ms.`);

In this scenario, we're using time-marks to do exactly what we've done before. This technique is more useful when you're doing some larger benchmarks, it might be just too much for a simple function benchmark. But, you know the basics. 😄


Vibration API

This is probably one of the simplest Web APIs of 'em all. Naturally, it can be used to interact with the hardware responsible for vibrating a particular device, if present. It all comes just to one method.

// Vibration time in miliseconds: 200ms
window.navigator.vibrate(200);
// Vibration sequence: 200ms vibrate, 100ms stop, 200ms vibrate
window.navigator.vibrate([200, 100, 200]);
// Vibrate for a long time...
window.navigator.vibrate(999999);
// ...but stop after 1 second
setTimeout(() => {
    window.navigator.vibrate(0);
}, 1000)

That's all. Just keep in mind that Safari won't allow you to vibrate so much, or rather not at all.


Clipboard API

Maybe this API is quite young and doesn't have good cross-browser support but it provides some interesting functionalities. As the name suggests, it allows you to asynchronously interact with user's clipboard (cut, copy, paste) over HTTPS only. It mostly comes down to 4 methods: read(), readText(), write(), writeText(), from which all return a Promise with optional clipboard data for reading methods. Because of security reasons, this API requires you to have explicit permissions granted by using Permissions API.


Page Visibility API

This one comes down just to 2 properties and 1 event. It allows checking if a user has your page currently opened (not e.g. minimized) or not and if the page has already rendered or is in the process of unloading. These properties are document.hidden (boolean) and document.visibilityState (string). You can also listen to onvisibilitychange event to know when the value changes.


Fullscreen API

Fullscreen API adds methods to Document and Element interfaces, allowing them to turn into the fullscreen mode. These are requestFullscreen() and exitFullscreen(), both returning a Promise. The API additionally provides some events and properties to check if the particular element is in fullscreen mode or not and etc. Nothing fancy but can be really useful for e.g. canvas, video and image elements.


More, more and counting...

These are just a fraction, a glimpse of what Web APIs  - these now available and these planned for the future - have to offer. Some of them are nothing more than a few useful methods and properties, some are really, really complex. I encourage you to take a look and discover other Web APIs in order to become a better web developer and understand just how different libraries used to encapsulate these APIs into nice packages works. For this purpose I recommend you to take a look at sites like MDN (linked in each listed API), CanIUse (for browser support) and WhatWebCanDo (to discover some interesting APIs and their functionalities). Also, If you liked this article consider sharing it using round buttons below and following me on Twitter or on my Facebook Page for more up-to-day content. 🎉