29. JavaScript Browser APIs

What you will learn

  • What a browser API is
  • Timers with setInterval
  • Saving data with Web Storage
  • Reading and building web addresses
  • Checking for features before using them

What is a browser API?

A browser API is a ready-made set of tools that the browser gives your JavaScript. You have already used some: the DOM, fetch, and timers. Others let you store data, read the address bar, detect screen settings, or ask for the visitor’s location. They are not part of the JavaScript language itself, they are features of the browser.

Timers: setInterval

setInterval repeats a function every so many milliseconds. clearInterval stops it. Always keep the value it returns so you can stop it.

Example

<p id="demo">Starting...</p>
<button id="stop" type="button">Stop</button>

<script>
  let seconds = 0;
  const out = document.getElementById("demo");

  const timer = setInterval(function () {
    seconds++;
    out.textContent = "Seconds passed: " + seconds;
  }, 1000);

  document.getElementById("stop").addEventListener("click", function () {
    clearInterval(timer);
    out.textContent += " (stopped)";
  });
</script>

What you see (the number grows every second)

Seconds passed: 3

Web Storage: localStorage and sessionStorage

Web Storage saves small pieces of text in the visitor’s browser.

Kind Lasts
localStorage Until it is cleared. It survives closing the browser
sessionStorage Until the tab is closed

Syntax

localStorage.setItem("theme", "dark");        // save
const theme = localStorage.getItem("theme");  // read ("dark", or null if missing)
localStorage.removeItem("theme");             // delete one item
localStorage.clear();                         // delete everything for this site

Storage holds strings only. To save an object or array, convert it with JSON:

Syntax

const settings = { theme: "dark", fontSize: 18 };

localStorage.setItem("settings", JSON.stringify(settings));

const saved = JSON.parse(localStorage.getItem("settings")) || {};

Practise with pretend storage

The real storage cannot run in the editor, so this example fakes it with the same method names. Press Try it Yourself and change the values. On a real page you would replace fakeStorage with localStorage.

Example

<p id="demo"></p>

<script>
  // A pretend storage with the same methods as localStorage
  const fakeStorage = {
    data: {},
    setItem(key, value) { this.data[key] = String(value); },
    getItem(key) { return key in this.data ? this.data[key] : null; },
    removeItem(key) { delete this.data[key]; }
  };

  const settings = { theme: "dark", fontSize: 18 };
  fakeStorage.setItem("settings", JSON.stringify(settings));

  const saved = JSON.parse(fakeStorage.getItem("settings"));
  const missing = fakeStorage.getItem("nothing");

  document.getElementById("demo").textContent =
    "Saved theme: " + saved.theme + ", size: " + saved.fontSize +
    " | missing item: " + missing;
</script>

Output (after the script runs)

Saved theme: dark, size: 18 | missing item: null

Storage is not safe for secrets. Any script on your page can read it, and visitors can edit it. Never store passwords, tokens, or personal data there. It can also be blocked or full, so wrap it in try...catch and let your page work without it.

Reading and building addresses: URL and URLSearchParams

These tools read the parts of a web address and build query strings safely, including encoding special characters.

Example

<p id="demo"></p>

<script>
  const address = new URL("https://example.com/search?q=html+tables&page=2#results");

  const params = new URLSearchParams({ q: "css & grid", level: "beginner" });

  document.getElementById("demo").innerHTML =
    "Host: " + address.hostname + "<br>" +
    "Path: " + address.pathname + "<br>" +
    "q = " + address.searchParams.get("q") + "<br>" +
    "page = " + address.searchParams.get("page") + "<br>" +
    "Built query: " + params.toString();
</script>

Output (after the script runs)

Host: example.com
Path: /search
q = html tables
page = 2
Built query: q=css+%26+grid&level=beginner

On a real page, new URL(window.location.href) reads the address of the current page.

Information about the visitor’s setup

You can ask the browser about the screen and preferences, and then adapt. Results differ from person to person.

Example

<p id="demo"></p>

<script>
  const dark = window.matchMedia("(prefers-color-scheme: dark)").matches;
  const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  document.getElementById("demo").innerHTML =
    "Language: " + navigator.language + "<br>" +
    "Window width: " + window.innerWidth + "px<br>" +
    "Prefers dark mode: " + dark + "<br>" +
    "Prefers reduced motion: " + reduced;
</script>

Output

Shows your own language, window width, and display preferences. Press Try it Yourself to see them.

APIs that ask permission

Some features touch private things, so the browser asks the visitor first, and they only work on secure (HTTPS) pages. Always handle a “no” answer gracefully.

Syntax

// Copy text to the clipboard (after a click)
async function copyText(text) {
  try {
    await navigator.clipboard.writeText(text);
    console.log("Copied");
  } catch (error) {
    console.log("Copying was not allowed");
  }
}

// Ask for the visitor's location (they must agree)
navigator.geolocation.getCurrentPosition(
  function (position) { console.log(position.coords.latitude); },
  function (error) { console.log("Location not shared"); }
);

Only ask for permission when the visitor does something that clearly needs it, such as clicking a “Use my location” button.

Check that a feature exists

Browsers differ in what they support. Test before you use a feature, so older browsers do not break your page.

Example

<p id="demo"></p>

<script>
  const features = {
    "fetch": "fetch" in window,
    "IntersectionObserver": "IntersectionObserver" in window,
    "clipboard": "clipboard" in navigator,
    "geolocation": "geolocation" in navigator
  };

  document.getElementById("demo").innerHTML = Object.entries(features)
    .map(([name, ok]) => name + ": " + (ok ? "available" : "not available"))
    .join("<br>");
</script>

Output

Lists whether each feature exists in your browser. Press Try it Yourself to see it.

More APIs to explore

  • IntersectionObserver: know when an element scrolls into view (lazy loading, animations).
  • History API: change the address without reloading.
  • Canvas: draw graphics and charts.
  • Web Audio and Media: sound and video control.
  • Service workers: offline pages and caching.

The MDN Web Docs list every API with examples and support tables. See the Resources page for the link.

Common mistakes

  • Storing objects without JSON.stringify, which saves “[object Object]”.
  • Forgetting that stored values are strings, so numbers come back as text.
  • Saving sensitive data in storage.
  • Not handling a blocked or full storage.
  • Never clearing an interval, so it keeps running.
  • Asking for permissions on page load instead of after a clear action.

Exercise

Use setInterval to count down from 5 to 1, showing one number per second. When the count reaches 0, show Go! and stop the timer with clearInterval.

Show solution
<p id="demo">Starting...</p>

<script>
  let count = 5;
  const out = document.getElementById("demo");
  out.textContent = count;

  const timer = setInterval(function () {
    count--;
    if (count === 0) {
      out.textContent = "Go!";
      clearInterval(timer);
    } else {
      out.textContent = count;
    }
  }, 1000);
</script>

Knowledge check

1. What type of data can Web Storage hold?

Strings only. Convert objects with JSON.stringify.

2. Which function stops a setInterval timer?

clearInterval()

3. Why check for a feature before using it?

Not every browser supports every API, and the page should not break.

Summary

  • Browser APIs are tools the browser gives your JavaScript.
  • Web Storage saves strings, never secrets, and needs error handling.
  • Use URL and URLSearchParams for addresses, and check features and permissions.
Scroll to Top