Modern browser APIs to use today
Tags: webdev
Published: 2020-04-06 17:37:49

---
title: Modern browser APIs to use today
published: true
date: 2020-03-17 16:00:32 UTC
tags: webdev
canonical_url: https://blog.logrocket.com/modern-browser-apis-to-use-today/
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/c7ehb9km9165dlutakuy.png
---
**Written by [Adewale Abati](https://blog.logrocket.com/author/adewaleabati/)**✏️

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.

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

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

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

```jsx
// 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.

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

```jsx
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)](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) provide nodes to connect webpages to scripts and direct programmable access to the document tree. The [CSS Object Model (CSSOM)](https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model) 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](https://developer.mozilla.org/en-US/docs/Web/API/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](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API) and [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/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](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) take advantage of the device’s capability to pinpoint the user’s location. The [Vibration API](http://www.w3.org/TR/vibration/) allows developers to provide non-audible feedback to the user by harnessing the device’s vibration function.

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

Another API is the [Ambient Light Events API](https://developer.mozilla.org/en-US/docs/Web/API/Ambient_Light_Events). 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.

```jsx
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](https://developer.mozilla.org/en-US/docs/Web/API/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](https://developer.mozilla.org/en-US/docs/Web/API/Cache) and also the [IndexedDB API](https://developer.mozilla.org/en-US/docs/Web/API/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](https://developer.mozilla.org/en-US/docs/Web/API/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](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_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](https://developer.mozilla.org/en-US/docs/Web/API/Media_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](https://developer.mozilla.org/en-US/docs/Web/API) for specifications that might make it easier to achieve your dream features for your app.

* * * 
## Plug: [LogRocket](https://logrocket.com/signup/), a DVR for web apps
 
![LogRocket Dashboard Free Trial Banner](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png?resize=1200%2C677&ssl=1)
 
[LogRocket](https://logrocket.com/signup/) is a frontend logging tool 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.
 
[Try it for free](https://logrocket.com/signup/).
* * *

The post [Modern browser APIs to use today](https://blog.logrocket.com/modern-browser-apis-to-use-today/) appeared first on [LogRocket Blog](https://blog.logrocket.com).