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.
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.
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.
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);
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 });
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.
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 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.
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:
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.
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.
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'); }
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.
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.
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.
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowBuild scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.
Deno is a popular JavaScript runtime, and it recently launched version 2.0 with several new features, bug fixes, and improvements […]