跪拜 Guibai
← Back to the summary

JavaScript BOM Explained: The Browser APIs That Power Frontend Apps

JavaScript BOM Explained: From Basic Concepts to React in Practice

Target audience: developers with backend experience who are learning JavaScript, React, and TypeScript.

Learning objectives: understand the role of BOM, and master common APIs such as window, location, history, navigator, browser storage, and timers.

1. What is BOM?

BOM stands for Browser Object Model.

In simple terms:

BOM is a set of objects and APIs that JavaScript uses to access and manipulate the browser window and browser features.

If you have previously learned about the DOM, you can distinguish them like this:

Comparison DOM BOM
Full name Document Object Model Browser Object Model
Main purpose Operating on page content Accessing browser features
Core object document window
Typical operations Modify HTML, operate on nodes Page navigation, history, storage
Example document.querySelector() window.location.href

For example:

// DOM: modify page content
document.querySelector("h1").textContent = "Hello";

// BOM: get the current page URL
console.log(window.location.href);

To remember in one sentence:

DOM manages page content; BOM manages browser features.

Note that BOM is a historical umbrella term, not a unified standard defined independently like the DOM.


2. The core object of BOM: window

window is the global object in a browser page and the most important entry point for learning BOM.

It provides or associates with many common features:

window
├── document         # DOM document
├── location         # Current URL, page navigation
├── history          # Browser history
├── navigator        # Browser environment information
├── screen           # Screen information
├── localStorage     # Local persistent storage
├── sessionStorage   # Session storage
├── setTimeout()     # Delayed execution
├── setInterval()    # Timed repeated execution
├── alert()          # Alert dialog
└── innerWidth       # Browser viewport width

1. Basic usage of window

// Browser viewport width
console.log(window.innerWidth);

// Browser viewport height
console.log(window.innerHeight);

// Show alert dialog
window.alert("Hello BOM");

// Current page URL
console.log(window.location.href);

2. Why can window be omitted?

For example:

window.alert("Hello");

It can usually also be written as:

alert("Hello");

Because many global functions and properties in the browser can be accessed through window.

Similarly:

window.document === document; // true

Key point: window is the global object of the browser, and document is a property of it.


3. location: URL and Page Navigation (P0)

location is one of the most commonly used browser APIs in daily work.

Assume the current page URL is:

https://example.com:8080/tasks/list?id=123&status=running#detail

You can get URL information like this:

console.log(window.location.href);
// Full URL

console.log(window.location.protocol);
// https:

console.log(window.location.hostname);
// example.com

console.log(window.location.port);
// 8080

console.log(window.location.pathname);
// /tasks/list

console.log(window.location.search);
// ?id=123&status=running

console.log(window.location.hash);
// #detail

1. URL parameter parsing

In actual development, you often need to get query parameters from the URL.

For example:

https://example.com/tasks?id=123&status=running

Code:

const params = new URLSearchParams(
  window.location.search
);

const taskId = params.get("id");
const status = params.get("status");

console.log(taskId); // "123"
console.log(status); // "running"

Note: URLSearchParams.get() returns a string or null.

2. Page navigation

// Method 1: Direct assignment
window.location.href = "/login";

// Method 2: Navigate to a new address
window.location.assign("/login");

// Method 3: Replace the current history entry
window.location.replace("/login");

// Refresh the current page
window.location.reload();

The difference between assign() and replace():

Business scenario:

function logout() {
  // Clean up login state...

  window.location.replace("/login");
}

4. history: Browser History (P1)

history is used to manipulate the browser's session history.

1. Forward and backward

// Go back to the previous page
window.history.back();

// Go forward one page
window.history.forward();

// Go back two steps
window.history.go(-2);

2. Modify the URL without refreshing the page

window.history.pushState(
  { taskId: 123 },
  "",
  "/tasks/detail/123"
);

After execution, the URL in the address bar changes, but pushState does not automatically reload the page.

You can also use:

window.history.replaceState(
  { taskId: 123 },
  "",
  "/tasks/detail/123"
);

Differences:

Note: These two methods usually require the target URL to be same-origin as the current page, and modifying the URL itself does not automatically update the page content.

3. Relationship between React Router and history

In React single-page applications (SPAs):

import { useNavigate } from "react-router";

function TaskPage() {
  const navigate = useNavigate();

  return (
    <button onClick={() => navigate("/tasks")}>
      View Tasks
    </button>
  );
}

React Router can use the browser History API to manage route navigation and page rendering.

In actual React development, internal navigation within an app usually prioritizes using a routing library instead of directly manipulating window.location.


5. localStorage and sessionStorage (P0)

Browsers provide two common client-side storage APIs.

Comparison localStorage sessionStorage
Storage location Browser local Browser session
Refresh page Usually retained Usually retained
Close tab Usually retained Usually cleared
Data type String String
Common uses Theme, user preferences Temporary state for a single tab

1. localStorage

// Store
localStorage.setItem("theme", "dark");

// Read
const theme = localStorage.getItem("theme");

console.log(theme); // dark

// Delete specific data
localStorage.removeItem("theme");

// Clear all localStorage for the current origin
localStorage.clear();

Note: localStorage is mainly for non-sensitive client-side data; it is not recommended to store passwords or sensitive identity credentials directly.

2. Storing objects

Storage can only directly store strings.

If you need to store objects:

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

// Store object
localStorage.setItem(
  "user",
  JSON.stringify(user)
);

// Read object
const raw = localStorage.getItem("user");

const savedUser = raw ? JSON.parse(raw) : null;

console.log(savedUser?.name);

Two methods are involved here:

In real business, when reading untrusted or possibly corrupted data, handle JSON parsing errors with try/catch.

3. sessionStorage

Usage is similar:

sessionStorage.setItem("taskId", "123");

const taskId = sessionStorage.getItem("taskId");

sessionStorage.removeItem("taskId");

It is usually used for temporary data during the tab's session.


6. Timers: setTimeout and setInterval (P0)

1. setTimeout: run once after a delay

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

Here:

You can cancel it:

const timer = setTimeout(() => {
  console.log("Execute task");
}, 2000);

clearTimeout(timer);

2. setInterval: run repeatedly at intervals

const timer = setInterval(() => {
  console.log("Check task status periodically");
}, 5000);

This executes the callback roughly every 5 seconds.

Stop the timer:

clearInterval(timer);

3. Practical scenario: polling task status

For example, check the task status every 5 seconds:

async function getTaskStatus() {
  const response = await fetch("/api/task/status");

  if (!response.ok) {
    throw new Error("Query failed");
  }

  return response.json();
}

const timer = setInterval(async () => {
  try {
    const data = await getTaskStatus();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}, 5000);

Note: If a request takes longer than 5 seconds, setInterval may cause overlapping requests.

In real projects, you can schedule the next poll with setTimeout after the previous request finishes, or use data-fetching tools like SWR or TanStack Query.


7. navigator: Getting Browser Environment Information (P1)

navigator provides information about the browser runtime environment.

For example:

// Whether the browser reports being online
console.log(navigator.onLine);

// Browser language
console.log(navigator.language);

// User agent information
console.log(navigator.userAgent);

Practical usage scenarios:

For example:

await navigator.clipboard.writeText("Task ID: 123");

This attempts to write text to the clipboard.

Note: The Clipboard API usually requires a secure context (like HTTPS) and is subject to browser permissions and user interaction restrictions.

Also, navigator.onLine cannot reliably prove that your backend API is accessible.


8. How to Use BOM in React

React essentially runs in a JavaScript environment, so you can use browser APIs.

For example:

import { useEffect, useState } from "react";

function WindowInfo() {
  const [width, setWidth] = useState(
    () => window.innerWidth
  );

  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth);
    }

    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  return <div>Window width: {width}px</div>;
}

Core flow:

  1. Get the window width via window.innerWidth.
  2. Listen for window changes with addEventListener().
  3. Update React state with setWidth().
  4. React re-renders the page based on the new state.
  5. Remove the listener in the useEffect cleanup function.

Note: The example above is for client-side rendering in the browser. If the project uses SSR, window may not be available during the initial render, requiring additional handling.


9. Common Questions

1. What is the difference between window and document?

window is the global object of a browser page.

document represents the current HTML document and provides DOM manipulation capabilities.

For example:

window.location.href; // BOM
document.querySelector("div"); // DOM

2. Are BOM and DOM independent?

They can be distinguished conceptually, but the actual APIs are related.

For example:

window.document

accesses the DOM document through window.

3. What is the difference between BOM and Node.js?

Node.js is not a browser environment.

For example:

console.log(window);

In a typical Node.js environment, window usually does not exist.

Node.js and browsers both support JavaScript, but the runtime APIs they provide are not identical.

4. Do you need to manipulate window directly in React?

Yes, but choose based on the scenario:


10. Learning Key Points Summary

Knowledge point Priority What to master
window P0 Meaning of the global object
location P0 URL retrieval, page navigation
localStorage P0 setItem, getItem
setTimeout P0 Delayed execution
setInterval P0 Timed execution and cleanup
history P1 pushState, back
sessionStorage P1 Temporary session storage
navigator P1 Common environment APIs
screen P2 Just understand

Final Summary

BOM mainly solves the problem of how JavaScript accesses browser features.

The most worth remembering are:

// Current address
window.location.href;

// Page navigation
window.location.assign("/login");

// Browser storage
localStorage.setItem("key", "value");

// Delayed execution
setTimeout(() => {}, 1000);

// Timed execution
setInterval(() => {}, 5000);

// Get window width
window.innerWidth;

For React + TypeScript business development, focus on window, location, localStorage, timers, and browser events.

As for other BOM APIs, look them up when you encounter them in real work; you don't need to learn them all at once.