DEV Community

Cover image for 15 Javascript Browser APIs
Hidayt Rahman
Hidayt Rahman

Posted on

15 Javascript Browser APIs

The features provided by the browser.

1. Service Workers

Service workers essentially act as proxy servers that sit between web applications, the browser, and the network (when available). They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs.

Service Workers

What Are Service Workers and How to Use Them?

2. Intl

The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. The Intl object provides access to several constructors as well as functionality common to the internationalization constructors and other language sensitive functions.

Intl

3. WebGL

WebGL (Web Graphics Library) is a JavaScript API for rendering high-performance interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins. WebGL does so by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML elements. This conformance makes it possible for the API to take advantage of hardware graphics acceleration provided by the user's device.
WebGL

4. Web Animations

The Web Animations API allows for synchronizing and timing changes to the presentation of a Web page, i.e. animation of DOM elements. It does so by combining two models: the Timing Model and the Animation Model.

Web Animations

Complexity With Web Animations API

5. WebRTC

WebRTC (Web Real-Time Communication) is a technology that enables Web applications and sites to capture and optionally stream audio and/or video media, as well as to exchange arbitrary data between browsers without requiring an intermediary. The set of standards that comprise WebRTC makes it possible to share data and perform teleconferencing peer-to-peer, without requiring that the user install plug-ins or any other third-party software.

WebRTC

6. Web Speech API

The Web Speech API enables you to incorporate voice data into web apps. The Web Speech API has two parts: SpeechSynthesis (Text-to-Speech), and SpeechRecognition (Asynchronous Speech Recognition.)

Web Speech API

7. WebSocket

The WebSocket API is 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.

WebSocket

8. Custom Elements

One of the key features of the Web Components standard is the ability to create custom elements that encapsulate your functionality on an HTML page, rather than having to make do with a long, nested batch of elements that together provide a custom page feature. This article introduces the use of the Custom Elements API.

Custom Elements

9. Shadow DOM

An important aspect of web components is encapsulation — being able to keep the markup structure, style, and behavior hidden and separate from other code on the page so that different parts do not clash, and the code can be kept nice and clean. The Shadow DOM API is a key part of this, providing a way to attach a hidden separated DOM to an element. This article covers the basics of using the Shadow DOM.

// Create spans
const wrapper = document.createElement("span");
wrapper.setAttribute("class", "wrapper");
const icon = document.createElement("span");
icon.setAttribute("class", "icon");
icon.setAttribute("tabindex", 0);
const info = document.createElement("span");
info.setAttribute("class", "info");

// Take attribute content and put it inside the info span
const text = this.getAttribute("data-text");
info.textContent = text;

// Insert icon
const img = document.createElement("img");
img.src = this.hasAttribute("img")
  ? this.getAttribute("img")
  : "img/default.png";
img.alt = this.hasAttribute("alt")
  ? this.getAttribute("alt")
  : "";
icon.appendChild(img);

Enter fullscreen mode Exit fullscreen mode

Shadow DOM

10. Page Visibility API

The Page Visibility API provides events you can watch for to know when a document becomes visible or hidden, as well as features to look at the current visibility state of the page.

This is especially useful for saving resources and improving performance by letting a page avoid performing unnecessary tasks when the document isn't visible.

Pausing audio on page hide
This example pauses audio when the user switches to a different tab, and plays when they switch back.

HTML

<audio
  controls
  src="https://mdn.github.io/webaudio-examples/audio-basics/outfoxing.mp3"></audio>
Enter fullscreen mode Exit fullscreen mode

JavaScript

const audio = document.querySelector("audio");

// Handle page visibility change:
// - If the page is hidden, pause the video
// - If the page is shown, play the video
document.addEventListener("visibilitychange", () => {
  if (document.hidden) {
    audio.pause();
  } else {
    audio.play();
  }
});
Enter fullscreen mode Exit fullscreen mode

Page Visibility API

11. Broadcast Channel API

The Broadcast Channel API allows basic communication between browsing contexts (that is, windows, tabs, frames, or iframes) and workers on the same origin.

// Connection to a broadcast channel
const bc = new BroadcastChannel("test_channel");
Enter fullscreen mode Exit fullscreen mode

Broadcast Channel API

12. Geolocation API

The Geolocation API allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information.

WebExtensions that wish to use the Geolocation object must add the "geolocation" permission to their manifest. The user's operating system will prompt the user to allow location access the first time it is requested.

Geolocation API

13. File System Access API

The File System Access API allows read, write and file management capabilities.

Accessing files
The below code allows the user to choose a file from the file picker and then tests to see whether the handle returned is a file or directory

// store a reference to our file handle
let fileHandle;

async function getFile() {
  // open file picker
  [fileHandle] = await window.showOpenFilePicker();

  if (fileHandle.kind === 'file') {
    // run file code
  } else if (fileHandle.kind === 'directory') {
    // run directory code
  }

}
Enter fullscreen mode Exit fullscreen mode

The following asynchronous function presents a file picker and once a file is chosen, uses the getFile() method to retrieve the contents.

const pickerOpts = {
  types: [
    {
      description: 'Images',
      accept: {
        'image/*': ['.png', '.gif', '.jpeg', '.jpg']
      }
    },
  ],
  excludeAcceptAllOption: true,
  multiple: false
};

async function getTheFile() {
  // open file picker
  [fileHandle] = await window.showOpenFilePicker(pickerOpts);

  // get file contents
  const fileData = await fileHandle.getFile();
}
Enter fullscreen mode Exit fullscreen mode

File System Access API

14. Web Share API

The Web Share API provides a mechanism for sharing text, links, files, and other content to an arbitrary share target selected by the user.

The code below shows how you can share a link using navigator.share(), triggered off a button click.

const shareData = {
  title: 'MDN',
  text: 'Learn web development on MDN!',
  url: 'https://developer.mozilla.org'
}

const btn = document.querySelector('button');
const resultPara = document.querySelector('.result');

// Share must be triggered by "user activation"
btn.addEventListener('click', async () => {
  try {
    await navigator.share(shareData)
    resultPara.textContent = 'MDN shared successfully'
  } catch (err) {
    resultPara.textContent = `Error: ${err}`
  }
});
Enter fullscreen mode Exit fullscreen mode

Web Share API

16. WebXR Device API

WebXR is a group of standards which are used together to support rendering 3D scenes to hardware designed for presenting virtual worlds (virtual reality, or VR), or for adding graphical imagery to the real world, (augmented reality, or AR). The WebXR Device API implements the core of the WebXR feature set, managing the selection of output devices, render the 3D scene to the chosen device at the appropriate frame rate, and manage motion vectors created using input controllers.

WebXR Device API

Top comments (1)

Collapse
 
davboy profile image
Daithi O’Baoill

Excellent, thank you.