Topic 41 of 48 · Full Stack Essentials

JavaScript BOM

Lesson TL;DRTopic 4: JavaScript BOM 📖 15 min read · 🎯 intermediate · 🧭 Prerequisites: divpositioning, formbuttons Why this matters Up until now, you've been working inside the page — changing text, adding elem...
15 min read·intermediate·javascript · bom · browser-api · window-object

Topic 4: JavaScript BOM

📖 15 min read · 🎯 intermediate · 🧭 Prerequisites: div-positioning, form-buttons

Why this matters

Up until now, you've been working inside the page — changing text, adding elements, responding to clicks. But the browser is bigger than just the page. It has a history of where you've been, it knows the size of the screen, it can read the current URL, and it can even navigate you somewhere new. All of that is controlled through the Browser Object Model — the BOM. Think of the DOM as the room you're decorating, and the BOM as the entire building around it. Once you understand the BOM, you can start building things that actually talk to the browser, not just the document inside it.

What You'll Learn

  • What the Browser Object Model (BOM) is and how it differs from the DOM
  • How to use the window object's properties and dialog methods
  • How to read browser and OS information from the navigator object
  • How to query screen dimensions with the screen object
  • How to read and change the current URL with the location object
  • How to programmatically move through browser history with the history object
  • How to wire BOM objects together in a practical HTML + JS example

The Analogy

Think of a web page as a painting hanging on a wall inside a gallery. The DOM is the painting itself — every brushstroke, every frame, every colour you can reach in and change. The BOM is everything else in the gallery: the lights, the walls, the exit signs, the visitor counter at the door. The window is the gallery building, navigator is the security guard who knows what device you arrived on, screen is the physical size of the wall the painting hangs on, location is the address plaque outside the door, and history is the guest-book showing every room the visitor walked through before arriving here. You can't repaint the gallery walls by editing the painting — you need the BOM for that.

Chapter 1: What Is the BOM?

The Browser Object Model (BOM) is a collection of objects the browser exposes to JavaScript so scripts can interact with the browser environment — not just the HTML document. There is no formal W3C standard for the BOM (unlike the DOM), but every major browser implements the same core objects, making it reliably usable in practice.

The BOM's top-level object is window. Every other BOM object hangs off it:

ObjectWhat it represents
windowThe browser window / global JS scope
navigatorBrowser identity and environment info
screenPhysical display properties
locationThe current URL; allows navigation
historyThe session history stack

BOM vs. DOM in one sentence: the DOM is about the document content; the BOM is about the browser container that document lives inside.

graph TD
    window --> navigator
    window --> screen
    window --> location
    window --> history
    window --> document["document (DOM)"]

Chapter 2: The window Object

window is the global object in a browser context. Every global variable and function you declare automatically becomes a property of window. You can omit the window. prefix for most calls — alert() is the same as window.alert() — but being explicit is clearer.

Key properties

  • window.innerWidth — inner width of the viewport in pixels (excludes browser chrome)
  • window.innerHeight — inner height of the viewport in pixels

Key methods

  • window.open(url, target, features) — opens a new browser window or tab
  • window.close() — closes the current window (only works on windows opened via window.open)
  • window.alert(message) — displays a blocking alert dialog
  • window.confirm(message) — displays a yes/no dialog; returns true or false
  • window.prompt(message, default) — displays a text-input dialog; returns the string entered or null
// Viewport dimensions
console.log("Width: " + window.innerWidth);
console.log("Height: " + window.innerHeight);

// Open a new window and close it after 5 seconds
let newWindow = window.open("https://www.example.com", "_blank", "width=600,height=400");
setTimeout(() => {
    newWindow.close();
}, 5000);

// Alert dialog — blocks until dismissed
window.alert("Hello, Vizag!");

// Confirm dialog — returns boolean
let userConfirmed = window.confirm("Do you confirm this action?");
console.log("User confirmed:", userConfirmed);

// Prompt dialog — returns string or null
let userInput = window.prompt("Please enter your name:", "Alice");
console.log("User input:", userInput);

Note on window.open features string: the third argument is a comma-separated string of window features (width, height, top, left, resizable, etc.). Modern browsers restrict pop-ups unless they're triggered directly by a user gesture.

Chapter 3: The navigator Object

The navigator object holds read-only information about the browser and the user's operating environment. It is useful for feature detection and for logging diagnostics.

Key properties

  • navigator.userAgent — the full user-agent string (browser name, version, OS)
  • navigator.platform — the operating system platform (e.g., "Win32", "MacIntel")
  • navigator.language — the browser's preferred language (e.g., "en-US")
  • navigator.onLinetrue if the browser believes it has network access, false if offline
console.log("User Agent: " + navigator.userAgent);
console.log("Platform: "   + navigator.platform);
console.log("Language: "   + navigator.language);
console.log("Online: "     + navigator.onLine);

Heads-up: navigator.userAgent can be spoofed and is increasingly unreliable for browser detection. Prefer feature detection ('serviceWorker' in navigator) over UA sniffing.

Chapter 4: The screen Object

The screen object exposes properties of the physical display the browser is running on. This is distinct from window.innerWidth / window.innerHeight, which measure the viewport (the visible content area). screen measures the entire monitor.

Key properties

  • screen.width — total screen width in pixels
  • screen.height — total screen height in pixels
  • screen.availWidth — available width (excluding OS taskbars/docks)
  • screen.availHeight — available height (excluding OS taskbars/docks)
  • screen.colorDepth — number of bits used to represent one pixel's colour (typically 24)
console.log("Screen Width: "      + screen.width);
console.log("Screen Height: "     + screen.height);
console.log("Available Width: "   + screen.availWidth);
console.log("Available Height: "  + screen.availHeight);
console.log("Color Depth: "       + screen.colorDepth);

Chapter 5: The location Object

The location object represents the URL of the current page and provides methods to navigate to other URLs. Changing location.href is the simplest way to redirect a user programmatically.

Key properties

PropertyExample valueWhat it returns
location.href"https://example.dev/bom?q=1#top"Full URL
location.hostname"example.dev"Host without port
location.pathname"/bom"Path after the host
location.search"?q=1"Query string including ?
location.hash"#top"Fragment identifier including #

Key methods

  • location.assign(url) — loads a new document; adds to history so the Back button works
  • location.reload() — reloads the current document (pass true to force a server reload)
  • location.replace(url) — replaces the current document; does not add to history (Back button skips it)
// Read current URL parts
console.log("Current URL: "  + location.href);
console.log("Hostname: "     + location.hostname);
console.log("Pathname: "     + location.pathname);
console.log("Query String: " + location.search);
console.log("Hash: "         + location.hash);

// Navigate to a new URL (uncomment to activate)
// location.assign("https://www.example.com");

// Reload the current document
// location.reload();

// Replace the current document (no history entry)
// location.replace("https://www.example.com");

assign vs replace: Use assign when you want the user to be able to navigate back. Use replace for login redirects or post-form-submit redirects where going back would re-submit.

Chapter 6: The history Object

The history object gives JavaScript access to the browser's session history stack — the list of pages visited in the current tab.

Key methods

  • history.back() — equivalent to clicking the browser Back button; loads the previous URL
  • history.forward() — equivalent to clicking the browser Forward button; loads the next URL
  • history.go(n) — jumps n steps in the history: go(-1) is the same as back(), go(2) goes forward two pages, go(0) reloads
// Navigate through session history (uncomment to activate)
// history.back();      // Go back one page
// history.forward();   // Go forward one page
// history.go(-2);      // Go back two pages
// history.go(0);       // Reload current page

Security note: history.length tells you how many entries are in the stack, but you cannot read the actual URLs for security reasons.

Chapter 7: Putting It Together — Navigation and User Info

The class's practical exercise: build a page that displays the visitor's browser/environment data and provides Back / Forward navigation buttons — all driven entirely by BOM objects.

HTML — index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BOM Example</title>
</head>
<body>
    <h1>Browser Object Model Example</h1>
    <div id="userInfo"></div>
    <button id="backButton">Back</button>
    <button id="forwardButton">Forward</button>
    <script src="bom.js"></script>
</body>
</html>

JavaScript — bom.js

// Populate the userInfo div with BOM data
let userInfoDiv = document.getElementById("userInfo");
userInfoDiv.innerHTML = `
    <p>User Agent: ${navigator.userAgent}</p>
    <p>Platform: ${navigator.platform}</p>
    <p>Language: ${navigator.language}</p>
    <p>Screen Width: ${screen.width}</p>
    <p>Screen Height: ${screen.height}</p>
    <p>Current URL: ${location.href}</p>
`;

// Wire navigation buttons to history methods
document.getElementById("backButton").addEventListener("click", function () {
    history.back();
});

document.getElementById("forwardButton").addEventListener("click", function () {
    history.forward();
});

Open this in a browser, navigate to another page, then come back — the Back/Forward buttons will move through your session history just like the browser's native controls.

🧪 Try It Yourself

Task: Build a self-describing browser info card.

Create bom-card.html with an embedded <script> block that does all of the following:

  1. Reads window.innerWidth, window.innerHeight, navigator.language, navigator.onLine, screen.colorDepth, and location.href.
  2. Injects them into a <div id="card"> as a styled HTML table (one row per property).
  3. Adds a <button>Reload</button> that calls location.reload() when clicked.
  4. After 10 seconds, calls window.alert("Still here? Time to move on!").

Success criterion: Opening the file in a browser shows a populated table with real values from your machine, the Reload button works, and the alert fires after 10 seconds.

Starter snippet:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>BOM Card</title>
</head>
<body>
    <div id="card"></div>
    <button id="reloadBtn">Reload</button>
    <script>
        const props = [
            ["innerWidth",    window.innerWidth],
            ["innerHeight",   window.innerHeight],
            ["language",      navigator.language],
            ["onLine",        navigator.onLine],
            ["colorDepth",    screen.colorDepth],
            ["href",          location.href],
        ];

        let rows = props.map(([k, v]) => `<tr><td><b>${k}</b></td><td>${v}</td></tr>`).join("");
        document.getElementById("card").innerHTML = `<table>${rows}</table>`;

        document.getElementById("reloadBtn").addEventListener("click", () => location.reload());

        setTimeout(() => window.alert("Still here? Time to move on!"), 10000);
    </script>
</body>
</html>

🔍 Checkpoint Quiz

Q1. What is the key conceptual difference between the BOM and the DOM?

A) The BOM is only available in Node.js; the DOM runs in the browser
B) The DOM focuses on document content; the BOM provides access to the browser environment surrounding the document
C) The BOM is a newer replacement for the DOM
D) The DOM exposes screen dimensions; the BOM exposes HTML elements

Q2. Given this snippet, what does it print if the user types "Ravi" into the prompt and the page URL is https://example.dev/bom?tab=2#intro?

let name = window.prompt("Your name:", "Guest");
console.log(name + " is at " + location.pathname);

A) Guest is at https://example.dev/bom?tab=2#intro
B) Ravi is at /bom
C) Ravi is at https://example.dev/bom
D) undefined is at /bom

Q3. A developer wants to redirect the user to a login page after logout, ensuring the user cannot press the Back button to return to the authenticated page. Which call is correct?

A) location.assign("/login")
B) history.go(-1)
C) location.replace("/login")
D) window.open("/login", "_self")

Q4. What does history.go(-2) do?

A) Deletes the last two entries from the history stack
B) Navigates forward two pages
C) Navigates backward two pages in the session history
D) Throws a RangeError if the history stack has fewer than two entries

A1. B — The DOM is the API for the HTML document tree; the BOM is the browser's outer shell of objects (window, navigator, screen, location, history) that exist independently of document content.

A2. B — window.prompt returns the string the user typed ("Ravi"), and location.pathname returns only the path segment of the URL ("/bom"), not the full href.

A3. C — location.replace() replaces the current history entry rather than adding a new one, so the Back button skips the authenticated page entirely. location.assign() would still allow navigating back.

A4. C — history.go(n) moves n steps through the session history. A negative value moves backward; go(-2) is two pages back. The browser silently ignores the call if fewer entries exist — it does not throw.

🪞 Recap

  • The BOM is JavaScript's interface to the browser environment, distinct from the DOM which targets document content.
  • The window object is the global scope; it provides viewport dimensions and dialog methods (alert, confirm, prompt).
  • The navigator object exposes browser identity (userAgent), platform, language, and online status.
  • The screen object reports physical display dimensions (width, height, availWidth, availHeight, colorDepth).
  • The location object reads and writes the current URL; assign() adds a history entry while replace() does not.
  • The history object navigates the session stack with back(), forward(), and go(n).

📚 Further Reading

Like this topic? It’s one of 48 in Full Stack Essentials.

Block your seat for ₹2,500 and join the next cohort.