Topic 4: JavaScript BOM
📖 7 min read · 🎯 intermediate · 🧭 Prerequisites: div-positioning, form-buttons
Why this matters
Up until now, you've been working inside the page — selecting elements, changing text, updating styles. That's the DOM. But here's the thing — the browser is a much bigger place than just the page content. JavaScript can also talk to the browser itself: read the current URL, know the screen size, go back in history, or pop up an alert. That's what the Browser Object Model — the BOM — gives you. Think of the DOM as the room you've been decorating, and the BOM as the rest of the building. Let's walk through it.
What You'll Learn
- Understand what the Browser Object Model (BOM) is and how it differs from the DOM
- Use the
windowobject to read dimensions and control browser dialogs - Read browser and OS metadata from the
navigatorobject - Inspect screen dimensions with the
screenobject - Navigate and read URLs using the
locationobject - Traverse session history using the
historyobject - Build a practical page that combines BOM objects into real user-facing features
The Analogy
Think of a web page as a painting hanging inside a museum. The DOM is the painting itself — every brushstroke, color, and frame. The BOM is everything around the painting: the room dimensions, the lighting sensor, the door you walked through to get in, the exit signs pointing back to where you came from. JavaScript can manipulate the painting all day long, but the BOM is how it talks to the museum — asking "how wide is this room?", "which door did the visitor come from?", "can you put up a sign asking them to confirm before they leave?" Without the BOM, your code is trapped inside the canvas; with it, you control the whole gallery.
Chapter 1: What Is the BOM?
The Browser Object Model (BOM) is a collection of objects provided by the browser that expose the browser environment to JavaScript. Unlike the DOM — which models the content of an HTML document — the BOM models the context the document lives inside.
the trainer summarized it cleanly: "The BOM gives you objects and methods to interact with the browser window itself, not just what's rendered on the page."
The BOM is not formally standardized by W3C the way the DOM is, but all major browsers implement it consistently. It includes five core objects:
| Object | What it represents |
|---|---|
window | The browser window itself (also the global scope) |
navigator | Browser identity and environment metadata |
screen | Physical display properties of the user's screen |
location | The current URL and navigation controls |
history | The browser's session history stack |
Chapter 2: The window Object
The window object is the global object in a browser environment. Every global variable, function, and object you declare automatically becomes a property of window. When you write alert(), you are actually calling window.alert().
Window Properties
window.innerWidth— inner width of the browser viewport (in pixels)window.innerHeight— inner height of the browser viewport (in pixels)
Window Methods
window.open()— opens a new browser window or tabwindow.close()— closes the current browser windowwindow.alert()— displays a blocking alert dialogwindow.confirm()— displays a yes/no confirmation dialog; returnstrueorfalsewindow.prompt()— displays a text input dialog; returns the entered string ornull
// Read viewport dimensions
console.log("Width: " + window.innerWidth);
console.log("Height: " + window.innerHeight);
// Open a new window at a specific size
let newWindow = window.open("https://www.example.com", "_blank", "width=600,height=400");
// Close it automatically after 5 seconds
setTimeout(() => {
newWindow.close();
}, 5000);
// Show a simple alert
window.alert("Hello, Vizag!");
// Ask the user to confirm an action — returns boolean
let userConfirmed = window.confirm("Do you confirm this action?");
console.log("User confirmed:", userConfirmed);
// Ask the user for input — second argument is the default value
let userInput = window.prompt("Please enter your name:", "Alice");
console.log("User input:", userInput);
window.confirm()returnstruewhen the user clicks OK andfalsewhen they click Cancel.window.prompt()returnsnullif the user dismisses the dialog without input.
Chapter 3: The navigator Object
The navigator object contains information about the browser and the operating environment the user is running. It is read-only — you can inspect it, but you cannot change what the browser reports.
Navigator Properties
navigator.userAgent— the full user-agent string (browser name, version, engine, OS)navigator.platform— the operating system platform (e.g.,"MacIntel","Win32")navigator.language— the browser's configured language (e.g.,"en-US")navigator.onLine—trueif the browser has network connectivity,falseif offline
// Log all navigator properties
console.log("User Agent: " + navigator.userAgent);
console.log("Platform: " + navigator.platform);
console.log("Language: " + navigator.language);
console.log("Online: " + navigator.onLine);
navigator.userAgent is commonly used for feature detection, analytics, and rendering conditional UI based on the detected environment, though its values can be spoofed and should not be used as a hard security boundary.
Chapter 4: The screen Object
The screen object holds information about the user's physical display — independent of what the browser window is currently sized to.
Screen Properties
screen.width— total width of the screen in pixelsscreen.height— total height of the screen in pixelsscreen.availWidth— width available to the browser (excludes OS taskbars, docks)screen.availHeight— height available to the browser (excludes OS taskbars, docks)screen.colorDepth— number of bits used to represent the color of a single pixel
// Log physical screen dimensions
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);
The difference between screen.width and window.innerWidth matters: screen.width is the monitor's full resolution; window.innerWidth is how wide the current browser viewport is.
Chapter 5: The location Object
The location object gives you everything you need to read and manipulate the current URL. It is simultaneously a property of window and a standalone global — window.location and location refer to the same object.
Location Properties
location.href— the complete current URL (readable and writable)location.hostname— just the domain name (e.g.,"www.example.com")location.pathname— the path after the domain (e.g.,"/products/shoes")location.search— the query string including?(e.g.,"?sort=price&page=2")location.hash— the anchor fragment including#(e.g.,"#section-3")
Location Methods
location.assign(url)— navigate to a new URL (adds to history)location.reload()— reload the current pagelocation.replace(url)— navigate to a new URL without adding to history (cannot go back)
// Read the current URL breakdown
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 use)
// location.assign("https://www.example.com");
// Reload the current document (uncomment to use)
// location.reload();
// Replace the current document without adding to history (uncomment to use)
// location.replace("https://www.example.com");
The key difference between assign() and replace(): assign() pushes the new URL onto the history stack so the user can press Back; replace() overwrites the current entry so Back skips it entirely.
Chapter 6: The history Object
The history object provides programmatic access to the browser's session history — the list of pages visited in the current tab.
History Methods
history.back()— navigate to the previous URL in the history list (equivalent to clicking Back)history.forward()— navigate to the next URL in the history list (equivalent to clicking Forward)history.go(n)— jumpnsteps through history;go(-1)is back,go(1)is forward,go(-2)jumps back two pages
// Navigate through history (uncomment lines to use in a real page context)
// history.back(); // Go back one page
// history.forward(); // Go forward one page
// history.go(-2); // Go back two pages
history.length returns the number of entries in the session history, which can be useful for conditionally showing a Back button only when there is history to return to.
Chapter 7: Putting It Together — Navigation and User Info
The class decided to consolidate everything into a working page. The goal: display real user environment data pulled from BOM objects, and wire up Back/Forward buttons to history navigation.
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 live 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();
});
This example draws from five BOM objects — navigator, screen, location, history, and implicitly window via document.getElementById — demonstrating how they work together in a real page context.
graph TD
W[window] --> N[navigator]
W --> S[screen]
W --> L[location]
W --> H[history]
W --> D[document - DOM]
N -->|userAgent, platform, language, onLine| N1[Browser & OS info]
S -->|width, height, availWidth, colorDepth| S1[Display info]
L -->|href, hostname, pathname, search, hash| L1[URL info]
L -->|assign, reload, replace| L2[URL navigation]
H -->|back, forward, go| H1[Session navigation]
🧪 Try It Yourself
Task: Build a "live environment card" that updates whenever the browser window is resized.
- Create an HTML file with a
<div id="info"></div>and a linked script. - Write a function
updateInfo()that sets the div'sinnerHTMLto a table showing:window.innerWidth,window.innerHeight,screen.width,screen.height,navigator.language,navigator.onLine, andlocation.href. - Call
updateInfo()on page load, then attach it to theresizeevent onwindow.
Starter snippet:
function updateInfo() {
document.getElementById("info").innerHTML = `
<table border="1" cellpadding="6">
<tr><th>Property</th><th>Value</th></tr>
<tr><td>Viewport Width</td><td>${window.innerWidth}px</td></tr>
<tr><td>Viewport Height</td><td>${window.innerHeight}px</td></tr>
<tr><td>Screen Width</td><td>${screen.width}px</td></tr>
<tr><td>Screen Height</td><td>${screen.height}px</td></tr>
<tr><td>Language</td><td>${navigator.language}</td></tr>
<tr><td>Online</td><td>${navigator.onLine}</td></tr>
<tr><td>Current URL</td><td>${location.href}</td></tr>
</table>
`;
}
updateInfo();
window.addEventListener("resize", updateInfo);
Success criterion: Open the page, resize the browser window, and watch the Viewport Width and Height rows update live without a page reload.
🔍 Checkpoint Quiz
Q1. What is the fundamental difference between the BOM and the DOM?
A) The BOM is part of the HTML specification; the DOM is not
B) The DOM models document content; the BOM models the browser environment around it
C) The BOM only works in Chrome; the DOM works in all browsers
D) The DOM is JavaScript-only; the BOM is CSS-accessible
Q2. Given this code, what does the variable result hold if the user clicks "Cancel"?
let result = window.confirm("Are you sure?");
console.log(result);
A) null
B) undefined
C) false
D) "Cancel"
Q3. A user navigates: Page A → Page B → Page C. They are currently on Page C. What does history.go(-2) do?
A) Takes them to Page B
B) Takes them to Page A
C) Reloads Page C
D) Clears the history and stays on Page C
Q4. You want to redirect a user to a login page, and you do not want them to be able to press Back to return to the page they came from. Which location method should you use?
A) location.assign("/login")
B) location.href = "/login"
C) location.reload()
D) location.replace("/login")
A1. B — The DOM is concerned with the document's structure and content (HTML nodes). The BOM is concerned with the browser window and environment (history, screen, URL, etc.).
A2. C — window.confirm() returns false when the user clicks Cancel (or dismisses the dialog), and true when they click OK. It never returns null or "Cancel".
A3. B — history.go(-2) moves two steps backward in the session history. Starting at Page C, one step back is Page B, two steps back is Page A.
A4. D — location.replace() navigates to the new URL by overwriting the current history entry, so the Back button cannot return the user to the previous page. assign() and direct href assignment both add a new entry and allow Back navigation.
🪞 Recap
- The BOM is the set of browser-provided objects that let JavaScript interact with the environment around the document, not just the document itself.
- The
windowobject is the global scope in browsers — its methods (alert,confirm,prompt,open,close) control browser dialogs and windows, andinnerWidth/innerHeightexpose the current viewport size. - The
navigatorobject surfaces browser and OS metadata:userAgent,platform,language, andonLine. - The
screenobject reports physical display dimensions (width,height,availWidth,availHeight,colorDepth), distinct from viewport size. - The
locationobject exposes every part of the current URL and providesassign(),reload(), andreplace()for programmatic navigation — withreplace()being the choice when you want to prevent Back-button return. - The
historyobject lets you move through the session history stack withback(),forward(), andgo(n).
📚 Further Reading
- MDN Web Docs — Window — the source of truth for all
windowproperties and methods - MDN Web Docs — Navigator — full reference for browser detection and environment metadata
- MDN Web Docs — History API — covers
pushStateandreplaceStatefor SPA-style navigation beyond basicback()/forward() - MDN Web Docs — Location — complete breakdown of every
locationproperty and navigation method - ⬅️ Previous: Form Buttons
- ➡️ Next: JavaScript DOM