Adewale Abati Web engineer, tech lifestyle YouTuber, public speaker, building communities & open source #ForTheNextBillionUsers

Modern browser APIs to use today

4 min read 1318

Modern Browser APIs To Use Today

The web has become increasingly powerful in recent times, and developers and users alike benefit from these advancements. In particular, many things have been made significantly easier to implement thanks to the plethora of modern browser APIs that are available.

What are APIs?

Application programming interfaces, more commonly known as APIs, are sets of instructions or features that specify how various software components should interact. There are multiple types of APIs that help developers carry out various tasks or make use of various services. Examples include the GitHub API, which can be used to access repos, users, and more, and the Twitter API, which helps send tweets.

In this article, we will be focusing on APIs that help us do amazing things on our browsers.

What are browser APIs?

On the web today, we can build applications that make use of features that only native apps were previously known for. We can now build web apps that use native dialogs, system notifications, and much more. All these are made possible by the addition of modern browser APIs by browser makers.

Let’s check out a few of them.

Page Visibility API

The Page Visibility API provides us with the ability to detect when a user has left the current tab, either by switching to another tab, window, or application. We can also detect when the user returns to the page.

This API sends a visibilitychange event to let event listeners know that the state of the page has changed, and any actions or instructions can be carried out depending on the state. In a scenario where you only want to carry out a task when a user is actively viewing a page, this can come in handy, e.g., polling a server for updates only when the user is on the page.

function pageChanged() {
        if (document.hidden) {
            console.log('User is on some other tab/out of focus') // line #1
        } else {
            console.log('Hurray! User returned') // line #2
        }
    }
document.addEventListener("visibilitychange", pageChanged);

Fetch API

The Fetch API helps us make network requests and replaces XMLHttpRequest(). Whether you’re trying to request or send data to a server, the Fetch API comes in handy. The Fetch API is very customizable; we can include our own headers in the requests, and it returns a promise so we can chain .then() and .catch()methods to the requests.

// url (required), options (optional)
fetch('/foo/bar', { method: 'get' }).then(function(response) {
//Do something with your response
}).catch(function(err) {
//Handle any errors here
});

Broadcast Channel API

The Broadcast Channel API provides the ability for basic communication between multiple browser contexts — across tabs, windows, or frames — and workers with the same origin. Consider the following use case.

You have multiple tabs of the same origin open (e.g., Google Docs). If you log out on one tab, upon switching to another tab of the same origin, it’ll notify you that you are logged out and need to log back in. These multiple tabs join the same broadcast by creating a BroadcastChannel object of the same name.

We made a custom demo for .
No really. Click here to check it out.

const bc = new BroadcastChannel('my_channel');

//sending a message across connected clients
bc.postMessage("This is an example message");

A handler is available to listen to the triggered event anytime a message is posted. This is the onmessage() event handler.

bc.onmessage = function (event) { console.log(event); }

Service Workers API

Service workers are changing the way we build applications for the web. They basically serve as proxy servers that sit between web applications, the network, and the browser. They help take actions depending on network availability, like delivering effective offline experiences, intercepting network requests, push notifications, etc.

The service worker is immediately downloaded, installed, and activated when a user visits a service worker-controlled website or page for the first time.

More APIs

Of course, there are many other browser APIs that help us get stuff done, making it easier to build and implement features into our web applications that were previously impossible. These APIs cover different categories, as listed below:

APIs for manipulating document structure

A bunch of these APIs have been created to help us manipulate and present documents in a more unique and efficient way.

APIs such as the Document Object Model (DOM) provide nodes to connect webpages to scripts and direct programmable access to the document tree. The CSS Object Model (CSSOM) allows the manipulation of CSS from JavaScript. With the CSSOM, we can update CSS on the fly and programmatically, just like we do with the DOM.

In the past, drag and drop interfaces also used to require use of third party libraries like jQuery. This is now made possible using the HTML Drag and Drop API.

APIs for drawing and manipulating graphics

The web was initially designed for just text. But we’ve come a long way since then. The browser now has more support for drawing graphics on the browser. The WebGL API and Canvas API both provide a means for drawing graphics using JavaScript and HTML.

The Canvas API focuses largely on 2D graphics, while the WebGL API draws hardware-accelerated 2D and 3D graphics.

Device APIs

We can access the web from various devices today, from desktop PCs to our mobile phones and even watches. A number of APIs have been developed to help extend and shape the functionality of the web to match the capabilities of these myriad modern devices.

APIs like the Geolocation API take advantage of the device’s capability to pinpoint the user’s location. The Vibration API allows developers to provide non-audible feedback to the user by harnessing the device’s vibration function.

// vibrate the device for 500ms
window.navigator.vibrate(500);

Another API is the Ambient Light Events API. This is still experimental, but it allows you to detect a change in the light intensity. This can come in handy when trying to implement switching automatically between day and night modes in your application.

if ('ondevicelight' in window) {
        window.addEventListener('devicelight', function(event) {
            // Get the ambient light level in lux.
            console.log(event.value);
        });
    } else {
        console.log('devicelight event not supported');
    }

Storage APIs

The storage standard provides a shared storage system meant to be used by all technologies that store data for web applications. This system is utilized by APIs like the Web Storage API, which allows browsers to store key-value pairs in a much more intuitive fashion than using cookies.

The Web Storage API makes use of sessionStorage, which keeps data for the duration of the session, and localStorage, which retains the data even after the browser or tab is closed and reopened. Other APIs include the Cache API and also the IndexedDB API, which provides a solution to store larger amounts of structured data.

Video and audio APIs

As in all other aspects, the web’s ability to manage, display, and create different media types, including video and audio, has grown at an exponential pace. Quite a number of APIs have been made available to effectively carry out operations related to media.

The Web Audio API provides a powerful system for controlling audio and allowing developers to choose audio sources, add effects to audio, create audio visualizations, and much more. The WebRTC (Web Real-Time Communication) API makes it possible to stream live audio and video — as well as transfer arbitrary data — between two peers over the internet without requiring an intermediary.

You can also capture local media using local cameras and microphones to capture video, audio, and still images via the Media Capture and Streams API.

Conclusion

This is not an exhaustive list, but aims to show you the current and potential capabilities available to us as developers to build powerful web experiences with today’s APIs.

To learn more about the various browser APIs, including some that are still under development and are not yet available, you can check out the MDN Web API docs for specifications that might make it easier to achieve your dream features for your app.

You come here a lot! We hope you enjoy the LogRocket blog. Could you fill out a survey about what you want us to write about?

    Which of these topics are you most interested in?
    ReactVueAngularNew frameworks
    Do you spend a lot of time reproducing errors in your apps?
    YesNo
    Which, if any, do you think would help you reproduce errors more effectively?
    A solution to see exactly what a user did to trigger an errorProactive monitoring which automatically surfaces issuesHaving a support team triage issues more efficiently
    Thanks! Interested to hear how LogRocket can improve your bug fixing processes? Leave your email:

    : Full visibility into your web apps

    LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

    In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

    .
    Adewale Abati Web engineer, tech lifestyle YouTuber, public speaker, building communities & open source #ForTheNextBillionUsers

    Leave a Reply