DEV Community

loading...
Cover image for Essential JavaScript Browser APIs

Essential JavaScript Browser APIs

ageekdev profile image 🅰️ GEEK Originally published at ageek.dev ・7 min read

Browser APIs (or web APIs) are the APIs that come built-in with the browsers. There are a number of browser APIs for manipulating the DOM, making network requests, managing client-side storage, and retrieving device media streams, etc.

While the most common scripting language ECMAScript (more widely known as JavaScript) is developed by Ecma International, a great many of the APIs made available in browsers have been defined at W3C.

Browser APIs are typically used with JavaScript, although this doesn't always have to be the case. DOM API is the most popular but not efficient to touch manually, modern web frameworks will take care of that for you.

This post present you essential browser APIs you might use directly very often on daily basis according to state of JS 2020 survey.

Web Storage API

The Web Storage API introduces two related mechanisms — sessionStorage and localStorage — similar to HTTP cookies, for storing name-value pairs on the client side, and have following features:

  • Both maintain a separate storage area for each available origin for the duration of the page session.
  • Both available under window object —window.sessionStorage, window.localStorage— as read-only properties implement Storage interface.
interface Storage {
  readonly attribute unsigned long length;
  DOMString? key(unsigned long index);
  getter DOMString? getItem(DOMString key);
  setter void setItem(DOMString key, DOMString value);
  deleter void removeItem(DOMString key);
  void clear();
};
Enter fullscreen mode Exit fullscreen mode
  • Both limited to about 5MB and can contain only strings.
  • Both synchronous and will block the main thread.
  • Both not accessible from web workers or service workers.
  • Both better than cookies—restricted to 4KB, transmitted to the server in every HTTP request.

The sessionStorage mechanism is designed for scenarios where the user is carrying out a single transaction, but could be carrying out multiple transactions in different instances (per-window or per-tab) at the same time.

The localStorage mechanism is designed for storage that spans multiple instances, and lasts beyond the current session. In particular, Web applications may wish to store megabytes of user data, such as entire user-authored documents or a user's mailbox, on the client side for performance reasons.

Fetch API

The Fetch API defines interfaces for fetching resources programmatically in the browser, which exposes most of the networking functionality at a fairly low level of abstraction, similar to XMLHttpRequest but more powerful, currently implemented natively by most modern browsers.

Beside global fetch() function, Fetch API also defines Request, Response objects and other things involved with network requests. It also defines related concepts such as CORS and the HTTP Origin header semantics, supplanting their separate definitions elsewhere.

Fetch API is a simpler, easy-to-use version of XMLHttpRequest to consume resources asynchronously and return promises. Fetch lets you work with REST APIs with additional options like caching data, reading streaming responses, and more.

// An example using fetch()
fetch('/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    user: 'geek',
    fake: true
  })
})
  .then((res) => res.json())
  .then((jsonData) => console.log(jsonData))
  .catch((err) => console.log(err))
Enter fullscreen mode Exit fullscreen mode

The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally, and it will only reject on network failure or if anything prevented the request from completing.

Outside browsers implemented WHATWG Fetch standard, you can use Fetch API with whatwg-fetch polyfill in browser or node-fetch in NodeJS. Both of them don't implement the entire WHATWG Fetch standard, since some of the standard features would be non-trivial or otherwise unfeasible to implement.

Service Worker API

The Service Worker API describes a method that enables applications to take advantage of persistent background processing, including hooks to enable bootstrapping of web applications while offline.

A service worker is a type of web worker. It's essentially a JavaScript file that runs separately from the main browser thread, intercepting network requests, caching or retrieving resources from the cache, and delivering push messages.

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js')
}
Enter fullscreen mode Exit fullscreen mode

Service workers depend on two APIs to make an app work offline: Fetch API (a standard way to retrieve content from the network) and Cache API (a persistent content storage for application data). This cache is persistent and independent from the browser cache or network status.

Service workers are a new browser feature that provide event-driven scripts that run independently of web pages. Unlike other workers, service workers can be shut down at the end of events, note the lack of retained references from documents, and they have access to domain-wide events such as network fetches.

Service workers also have scriptable caches. Along with the ability to respond to network requests from certain web pages via script, this provides a way for applications to “go offline”.

Service workers are meant to replace the (oft maligned) HTML5 Application Cache. Unlike AppCache, service workers are comprised of scriptable primitives with an extensive use of Promises that make it possible for application developers to build URL-friendly, always-available applications in a sane and layered way.

WebSocket API

The WebSocket API defines a communication protocol which provides a two-way (“full-duplex”) and low-latency channel between the server and the browser.

With WebSocket, both the client and the server can trigger communication with one another, and both can send messages, at the same time.

HTTP request-response works just fine when you need to load a static page, but it’s insufficient when your communication is time-sensitive.

Both HTTP and WebSockets send messages over a TCP (Transmission Control Protocol) connection, which is a transport-layer standard that ensures streams of bytes, sent over in packets, are delivered reliably and predictably from one computer to another. So, HTTP and WebSockets use the same delivery mechanism at the packet/byte level, but the protocols for structuring the messages are different.

Creates an open connection between a client and a server, allowing persistent two-way communication over a single connection. Ideal for any situation where you currently use long-polling such as chat apps, online games, or sports tickers. Can directly interact with the DOM. Communication is handled through the WebSocket’s send method.

Use WebSocket whenever you need a truly low latency, near realtime connection between the client and the server. Keep in mind that this might involve rethinking how you build your server side applications with a new focus on technologies such as event queues.

Web Components APIs

Web Components is a new browser feature that provides a standard component model for the Web, consisting of several pieces maintained in different places:

  • Shadow DOM: Most of the parts are now maintained in DOM Standard, called shadow trees.
  • Custom Elements: Were upstreamed into the HTML Standard (and bits in the DOM Standard) and are maintained there.
  • HTML Templates: were upstreamed into the HTML Standard and are fully maintained there

Because Web Components APIs are low-level primitives, it's not always clear how best to combine them to create a component that is robust and works well in many different environments, while you really can do just about anything with these APIs.

Summary

There are many browser APIs that enhance JavaScript capabilities in browser environment. This post only scratches the surface and introduces you essential APIs you might use very often according to state of JS 2020 survey.

  • Web Storage API: Before HTML5, application data had to be stored in cookies, included in every server request. Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance.

  • WebSocket API: An advanced technology that makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.

  • Service Worker API: A script that your browser runs in the background, separate from a web page, opening the door to features that don't need a web page or user interaction.

  • Fetch API: This API allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.

  • Web Components APIs: A suite of different technologies allowing you to create reusable custom elements with their functionality encapsulated away from the rest of your code and utilize them in your web apps.

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.

Discussion (2)

pic
Editor guide
Collapse
tolambiasapna profile image
Sapna T

UP to mark!!!
Thanks for this awesome post.

Collapse
thelamb profile image
LambCreative

Thank you! Great post.