Skip to content
Tutorials Center
My learning

Topics

Lesson 86 of 122 Β· Web APIs

Introduction to Web APIs

Learn what browser Web APIs are, how to detect whether a feature exists, how permission prompts and secure contexts work, and how to read promise-based code.

HTML describes your content, CSS styles it and JavaScript makes it react. But JavaScript on its own can only do arithmetic and juggle strings. Everything interesting it does in a browser, such as changing the page, playing a sound, reading a dropped file or asking where the user is, it does by calling a Web API: a set of objects and functions the browser provides.

This chapter tours the most useful of these APIs. Before you meet them one by one, this lesson covers the four ideas they all share: what an API is, how to check that it exists, how browsers protect users with permissions and secure contexts, and how to read the promise-based code that most modern APIs use.

What a Web API is

An API (application programming interface) is a defined way for one piece of software to use another. A Web API is the part of the browser that your JavaScript can talk to. You have already used several without thinking of them that way:

API What it gives you Where you met it
DOM document, querySelector, classList The Document Object Model
Canvas A 2D drawing surface Canvas Basics
Media elements play(), pause(), currentTime Video, Audio
Constraint validation checkValidity(), setCustomValidity() Form Validation
Fetch Requests to servers, fetch(url) (used throughout this chapter)

Each API is described by a public standard, so it behaves the same way in Chrome, Firefox and Safari. The objects usually hang off a few well-known globals:

  • window: the browser tab itself (timers, localStorage, alert()).
  • document: the page you are on (the DOM).
  • navigator: information about the browser and device (navigator.geolocation, navigator.language, navigator.onLine).

APIs are not part of JavaScript the language. Array, Promise and JSON come from JavaScript itself and also exist in Node.js. document, navigator.geolocation and Worker come from the browser. That is why server-side JavaScript has no document.

Feature detection

Browsers add new APIs every year, and people do not update their browsers at the same speed. Before you use a newer API, check that it exists and provide a fallback when it doesn't. This is called feature detection, and it beats guessing based on the browser's name every time.

The usual checks look like this:

JavaScript
if ('geolocation' in navigator) { /* navigator.geolocation exists */ }
if (typeof Worker === 'function') { /* web workers are available */ }
if (CSS.supports('display', 'grid')) { /* the CSS feature works */ }
if (HTMLDialogElement.prototype.showModal) { /* <dialog> is modern */ }

Run the example below. It checks a list of APIs and prints a table of the results for the browser you are using right now.

Feature detection

"Exists" is not the same as "works"

Feature detection tells you that an object is there. It does not promise that calling it will succeed. The user may refuse a permission, the device may lack the hardware, or the page may run somewhere the feature is switched off.

The editors on this site are a good example. They run your code in a locked-down, sandboxed frame, so localStorage exists but throws an error the moment you touch it. The robust pattern is to detect the feature and wrap the real call in try...catch:

Exists versus works

In a normal page on your own computer, the same code reports true for both. In this sandbox the second check fails, and your code can switch to a fallback instead of crashing.

Permissions

Some APIs reveal private information (location, camera, microphone) or can annoy people (notifications). Browsers will not hand these over silently. The first time a page asks, the browser shows a permission prompt, and the user decides.

A few rules shape how you should use powerful APIs:

  • Ask in context. Request the location when the user clicks "Find stores near me", not the moment the page loads. A prompt that appears out of nowhere is usually refused, and many browsers quietly block prompts that are not triggered by a click or key press.
  • Expect "no". Every permission can be denied, revoked later in the browser settings, or blocked by the administrator. Your page must keep working.
  • The decision is remembered per site, so a refusal may stick until the user changes it.

The Permissions API lets you check the current state without triggering a prompt. navigator.permissions.query() answers with "granted", "denied" or "prompt" (meaning the browser would ask):

JavaScript
const status = await navigator.permissions.query({ name: 'geolocation' });
console.log(status.state); // "granted", "denied" or "prompt"

status.addEventListener('change', () => {
  console.log('The user changed the permission to', status.state);
});

Use the answer to adjust your interface, for example by hiding a "Locate me" button when access is already denied.

Embedded content has one more layer. A page decides which powerful features its iframes may use with the allow attribute, which you saw in the Iframes lesson:

HTML
<iframe src="https://maps.example.com/embed" allow="geolocation" title="Store map"></iframe>

Secure contexts (HTTPS)

Many APIs are available only in secure contexts: pages loaded over HTTPS. Geolocation, service workers, the clipboard, camera and microphone access, Web Crypto's subtle methods and many more refuse to work on plain HTTP. The reason is simple: on an unencrypted connection, anyone on the network could inject a script and abuse the permission the user granted to your site.

Two details make development easy:

  • http://localhost and http://127.0.0.1 count as secure, so you can test powerful APIs on your own computer without a certificate.
  • Files opened with file:// are treated differently by each browser, so a small local web server is the most reliable way to test.

You can ask the browser directly with window.isSecureContext:

JavaScript
if (!window.isSecureContext) {
  showMessage('Please open this page over HTTPS to use your location.');
}

Promises in one page

Most APIs need time: waiting for a server, a file, a permission decision or a GPS fix. Instead of freezing the page, they return a promise: an object that stands for a result that will arrive later. A promise ends in one of two ways. It is fulfilled with a value, or rejected with an error.

There are two ways to wait for a promise. The older style chains .then() and .catch():

JavaScript
fetch('/data.json')
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error('Failed:', error));

The modern style uses async and await, which reads like ordinary step-by-step code. Errors are handled with a normal try...catch:

JavaScript
async function loadData() {
  try {
    const response = await fetch('/data.json');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Failed:', error);
  }
}

await only works inside an async function (or at the top level of a module). It pauses that function until the promise settles, while the rest of the page carries on.

Play with the example below. wait() creates its own promise that is fulfilled after a delay, or rejected if you tick the box.

Promises with async and await

Notice that the console message appears straight away. await paused only the click handler, not the whole page. Older APIs, such as Geolocation, use callbacks instead of promises: you pass in functions that the browser calls later. You will see both styles in this chapter.

Where the APIs in this chapter run

Some APIs need things the editors on this site deliberately block: storage, a real location or a live server. In each lesson you will find:

  • Live examples for everything that can safely run in the sandbox (drag and drop, workers, error handling, simulated data).
  • Read-only code for the parts that need a normal page. Copy those into an .html file, serve it from localhost, and try them for real.

Vibration

The Vibration API is one of the smallest Web APIs, which makes it a good first example of all four ideas above. It has exactly one method, navigator.vibrate(), which shakes the device's vibration motor for a number of milliseconds:

JavaScript
navigator.vibrate(200);              // one buzz of 200 ms
navigator.vibrate([100, 50, 100]);   // buzz, pause, buzz
navigator.vibrate(0);                // stop any vibration in progress

A pattern is an array that alternates between vibrating and pausing: the first number vibrates, the second pauses, the third vibrates again, and so on. [300, 100, 300, 100, 600] is two short buzzes and a long one. Passing 0 or an empty array cancels a pattern that is still running, and a new call replaces the old pattern instead of queuing after it.

navigator.vibrate() returns true if the browser accepted the pattern and false if it refused, for example because the page isn't allowed to vibrate. It does not tell you whether anything actually shook: a laptop with no motor, a phone on silent or a battery-saver mode can all ignore the request silently.

Keep these limits in mind:

  • Support is narrow. It works mainly in Chromium-based browsers on Android phones (Chrome, Edge, Samsung Internet). Safari on iPhone and iPad has never supported it, and desktop computers rarely have a motor at all. Always feature-detect with 'vibrate' in navigator.
  • It needs a user action. Browsers ignore vibration requests until the user has tapped or clicked the page, so a page can't buzz someone's pocket the moment it loads. Call it from a click or touch handler.
  • Frames are restricted. Embedded third-party frames usually aren't allowed to vibrate. The editors on this site run code in a sandboxed frame, so the call below may return false or do nothing even on a phone. Copy the code into your own page to feel it.
  • It is a hint, never the message. Use vibration to reinforce something that is also shown on screen, such as a game hit, a timer finishing or an invalid scan. People with the motor turned off, and everyone on desktop, must still get the information.

The example detects the feature, wraps the call in try...catch for extra safety, and adds a visual "shake" so the feedback works everywhere:

Vibration patterns with a visual fallback

Note how the pattern travels: it is stored as text in a data-* attribute, split at the commas and turned into numbers with map(Number). void button.offsetWidth forces the browser to notice the class was removed, so the shake animation can replay on every click.

Gamepad

The Gamepad API reads game controllers (and some joysticks and wheels) connected to the device. The browser reports them as Gamepad objects with an array of buttons (each with pressed and a pressure value) and an array of axes (sticks, each from -1 to 1).

Two things make this API different. First, for privacy a gamepad stays invisible until the user presses a button on it. After that the page gets a gamepadconnected event (and gamepaddisconnected when it is unplugged). Second, there are no events for button presses: you read the state by polling, usually inside requestAnimationFrame, taking a fresh snapshot with navigator.getGamepads() every frame.

JavaScript
window.addEventListener('gamepadconnected', (event) => {
  console.log('Connected:', event.gamepad.id);
  requestAnimationFrame(poll);
});

function poll() {
  for (const pad of navigator.getGamepads()) {
    if (!pad) continue;
    const [x, y] = pad.axes;           // left stick
    if (pad.buttons[0].pressed) { /* A button */ }
    pad.vibrationActuator?.playEffect('dual-rumble', {
      duration: 200, strongMagnitude: 1, weakMagnitude: 0.5
    });
  }
  requestAnimationFrame(poll);
}

With the "standard" mapping (pad.mapping === 'standard'), button 0 is the bottom face button, 1 the right one, 12 to 15 the d-pad and the first two axes are the left stick. Treat tiny stick values as zero (a dead zone), because sticks rarely rest exactly at 0.

Is a gamepad connected?

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. Which of these is a browser Web API rather than a built-in part of the JavaScript language?

    navigator.geolocation is provided by the browser. Array, JSON and Promise belong to JavaScript itself and also exist outside browsers.
  2. 2. 'localStorage' in window returns true. What does that prove?

    Feature detection proves that the object exists. Privacy settings or sandboxing can still make the real call fail, so wrap it in try...catch.
  3. 3. When should a page ask for the user's location?

    Prompts tied to a user action make sense to people and are far more likely to be accepted. Many browsers also block prompts that appear without a user gesture.
  4. 4. Which address is treated as a secure context even without HTTPS?

    Browsers treat localhost and 127.0.0.1 as secure so you can test powerful APIs during development. Other plain-HTTP addresses are not secure.
  5. 5. What does await pause?

    The async function waits for the promise to settle, while the rest of the page keeps running and responding.

Summary

  • Web APIs are the objects and functions the browser gives JavaScript, such as the DOM, Canvas, Fetch and Geolocation.
  • Use feature detection ('x' in navigator, typeof X === 'function', CSS.supports()) and wrap real calls in try...catch.
  • Powerful features need the user's permission. Ask in context, expect refusals, and check the state with navigator.permissions.query().
  • Many APIs work only in secure contexts (HTTPS or localhost); check window.isSecureContext.
  • Modern APIs return promises. Wait for them with async/await and handle failures with try...catch.

Next lesson: Geolocation, where you ask the browser where the user is and handle every way that can fail.