Chapter 28 of 31

JavaScript Browser APIs

So far, we've learned how JavaScript works with variables, functions, objects, the DOM, and events.

But JavaScript can do much more than manipulate HTML.

A browser gives JavaScript access to many built-in features that let us interact with things like:

  • The browser window

  • URLs and page history

  • Local storage

  • The clipboard

  • Timers

  • Network requests

  • The user's location

  • Notifications

  • Device features

These features are provided through Browser APIs.

What are Browser APIs?

Browser APIs are interfaces provided by web browsers that allow JavaScript to interact with browser features and capabilities outside the core JavaScript language.

For example:

console.log(window.innerWidth);

Here, innerWidth tells us the width of the browser's viewport.

The important thing to understand is that things like document, localStorage, fetch(), and setTimeout() aren't part of the core JavaScript language itself. They are provided by the browser environment.

Think of it like this:

JavaScript
    ↓
Runs inside a browser
    ↓
Browser provides additional APIs
    ↓
JavaScript can interact with the web page and browser

The window Object

The window object represents the browser window and acts as a major entry point to many browser APIs.

For example:

console.log(window.innerWidth);
console.log(window.innerHeight);

These give the width and height of the browser viewport.

Because window is the global object in a browser, you can often omit window.:

console.log(innerWidth);

instead of:

console.log(window.innerWidth);

The window object also provides access to things like:

document
localStorage
location
history
navigator

Timers

Browsers provide timer APIs that allow us to execute code later or repeatedly.

setTimeout()

setTimeout() runs a function after a specified delay.

setTimeout(() => {
    console.log("Hello after 2 seconds");
}, 2000);

The delay is specified in milliseconds.

1000 milliseconds = 1 second

setInterval()

setInterval() repeatedly executes a function at a specified interval.

setInterval(() => {
    console.log("Hello!");
}, 1000);

This prints "Hello!" approximately every second until the interval is stopped.

We can stop it using clearInterval():

const timer = setInterval(() => {
    console.log("Hello!");
}, 1000);

clearInterval(timer);

Timers are commonly used for clocks, countdowns, animations, polling, and similar features.


Local Storage

The browser provides localStorage for storing small amounts of data on the user's device.

For example:

localStorage.setItem("username", "John");

We can retrieve it later:

const username = localStorage.getItem("username");

console.log(username);

Output:

John

We can remove it with:

localStorage.removeItem("username");

And clear everything stored by that origin with:

localStorage.clear();

Storing Objects in Local Storage

localStorage stores values as strings.

So if we want to store an object:

const user = {
    name: "John",
    age: 25
};

we can convert it to JSON:

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

Then retrieve and convert it back:

const data = JSON.parse(localStorage.getItem("user"));

console.log(data.name);

Output:

John

This is a very common pattern when using localStorage.


Session Storage

The browser also provides sessionStorage.

It works similarly to localStorage:

sessionStorage.setItem("username", "John");

console.log(sessionStorage.getItem("username"));

The main difference is how long the data is kept.

localStorage

sessionStorage

Persists across browser sessions

Usually lasts for the current page session

Remains until removed

Cleared when the relevant browsing session ends

Good for persistent preferences

Good for temporary session data

Neither should be treated as a secure place to store sensitive information.


Fetch API

One of the most important browser APIs is the Fetch API.

It allows JavaScript to make HTTP requests to servers and APIs.

For example:

fetch("https://example.com/data")
    .then(response => response.json())
    .then(data => {
        console.log(data);
    });

With modern JavaScript, we can use async and await:

async function getData() {
    const response = await fetch("https://example.com/data");
    const data = await response.json();

    console.log(data);
}

This is how JavaScript applications communicate with backend services and external APIs.

We'll explore fetch(), promises, and asynchronous JavaScript in much more detail later.


The location API

The location object provides information about the current URL.

For example:

console.log(location.href);

This gives the complete current URL.

We can also access individual parts:

console.log(location.hostname);
console.log(location.pathname);
console.log(location.protocol);

For example, for:

https://example.com/products

we might get:

hostname → example.com
pathname → /products
protocol → https:

We can also navigate to another page:

location.href = "https://example.com";

The History API

The History API lets JavaScript work with the browser's session history.

For example:

history.back();

This is similar to pressing the browser's Back button.

We can move forward:

history.forward();

Modern web applications can also use methods such as pushState() to change the URL without performing a traditional page navigation.

For example:

history.pushState({}, "", "/profile");

This technique is commonly used by single-page applications (SPAs).


The Clipboard API

The Clipboard API allows webpages to interact with the user's clipboard, subject to browser permissions and security requirements.

For example, copying text:

navigator.clipboard.writeText("Hello World");

We can also read clipboard text when the browser allows it:

const text = await navigator.clipboard.readText();

console.log(text);

A practical example:

const button = document.querySelector("#copy");

button.addEventListener("click", async () => {
    await navigator.clipboard.writeText("Hello World");

    console.log("Copied!");
});

This is commonly used for Copy buttons.


The navigator Object

The navigator object provides information about the browser and its environment.

For example:

console.log(navigator.language);

This might return:

en-US

We can also check whether the browser appears to be online:

console.log(navigator.onLine);

This returns a boolean:

true

or:

false

The navigator object exposes many APIs, but information provided by it shouldn't automatically be treated as perfectly reliable or as proof of a user's exact device or identity.


Geolocation API

The browser can request the user's geographical location through the Geolocation API.

For example:

navigator.geolocation.getCurrentPosition(
    position => {
        console.log(position.coords.latitude);
        console.log(position.coords.longitude);
    },
    error => {
        console.log("Unable to get location.");
    }
);

The browser will normally ask the user for permission.

This API can be used for applications such as:

  • Maps

  • Nearby services

  • Weather applications

  • Location-based features

Always explain clearly why your application needs location access.


Notifications API

Browsers can also support desktop notifications.

For example:

Notification.requestPermission();

If permission is granted:

new Notification("Hello!");

The browser controls whether notifications are available and may require user permission.


Web Storage vs Cookies

You may also hear about cookies when working with browser data.

Cookies can be accessed through:

document.cookie;

But cookies are different from localStorage and sessionStorage.

Feature

localStorage

sessionStorage

Cookies

Stores strings

Automatically sent with HTTP requests

Can be

Typical capacity

Larger

Larger

Small

Expiration

Until removed

Session-based

Configurable

Common use

Preferences/client data

Temporary data

Sessions and server-related state

Cookies have important security considerations, especially when they're used for authentication.


Browser APIs vs JavaScript

This distinction is important for beginners.

Some features are part of the JavaScript language, while others are provided by the environment.

For example:

const numbers = [1, 2, 3];

numbers.map(number => number * 2);

Array and map() are JavaScript language features.

But:

document.querySelector("#title");

uses the DOM API provided by the browser.

Similarly:

fetch("/api/users");

uses the Fetch API.

So you can think of it as:

JavaScript

Browser APIs

Variables

DOM

Functions

Fetch

Objects

Local Storage

Arrays

Clipboard

Promises

Geolocation

Classes

Notifications

JavaScript provides the programming language, while the browser provides additional capabilities.


A Practical Example

Let's combine a few browser APIs into a small example.

Suppose we want to remember a user's preferred name.

const input = document.querySelector("#name");
const button = document.querySelector("#save");
const message = document.querySelector("#message");

button.addEventListener("click", () => {
    const name = input.value.trim();

    if (name === "") {
        message.textContent = "Please enter your name.";
        return;
    }

    localStorage.setItem("username", name);

    message.textContent = `Welcome, ${name}!`;
});

When the user enters their name and clicks Save, we store it in localStorage.

When the page loads, we can retrieve it:

const savedName = localStorage.getItem("username");

if (savedName) {
    console.log(`Welcome back, ${savedName}!`);
}

Here we're combining:

DOM API
   ↓
Get input and button
   ↓
DOM Events
   ↓
Handle click
   ↓
Local Storage API
   ↓
Save the user's name

That's the real power of browser APIs—they let JavaScript interact with the environment around the webpage.

Conclusion

Browser APIs give JavaScript access to capabilities that go beyond the core language.

Some important ones to know are:

DOM API          → Work with HTML
Window API       → Work with the browser window
Timers           → Run code later/repeatedly
Local Storage    → Store client-side data
Session Storage  → Store session data
Fetch API        → Make network requests
Location API     → Work with URLs/navigation
History API      → Work with browser history
Clipboard API    → Copy/read clipboard data
Geolocation API  → Access location with permission
Notifications    → Display browser notifications

You don't need to memorize all of these APIs right away. The important idea is to understand that the browser provides JavaScript with powerful APIs for interacting with the webpage, browser, network, and certain device capabilities.

Once you combine these APIs with DOM manipulation and events, you can move from writing simple JavaScript programs to building genuinely useful web applications.