Browser Object Model (window, location, history, navigator)
The BOM (Browser Object Model) provides JavaScript access to browser features beyond the document — the window dimensions, URL, navigation history, and browser info.
BOM Objects
- window — The global object. All global variables/functions are properties of window
- window.innerWidth / innerHeight — Browser viewport dimensions
- window.location — Current URL info: href, hostname, pathname, search, hash
- window.location.href = 'url' — Navigate to URL. location.reload() reloads page
- window.history — back(), forward(), go(-2). pushState() for SPA routing
- window.navigator — Browser info: userAgent, language, onLine, clipboard
- window.open() / close() — Open/close browser windows/tabs
BOM Code
// Window dimensions
console.log("Viewport:", window.innerWidth, "x", window.innerHeight);
console.log("Screen:", screen.width, "x", screen.height);
// Location — current URL info
console.log("URL:", window.location.href);
console.log("Host:", window.location.hostname);
console.log("Path:", window.location.pathname);
console.log("Query:", window.location.search);
// Navigate
// window.location.href = "https://priygop.com"; // navigate
// window.location.reload(); // refresh page
// History
// history.back(); // go back
// history.forward(); // go forward
// history.go(-2); // go back 2 pages
// Navigator — browser info
console.log("Browser:", navigator.userAgent);
console.log("Language:", navigator.language);
console.log("Online:", navigator.onLine);
// Detect mobile
const isMobile = /iPhone|iPad|Android/i.test(navigator.userAgent);
console.log("Mobile:", isMobile);
// Online/Offline detection
window.addEventListener("online", () => console.log("🟢 Back online!"));
window.addEventListener("offline", () => console.log("🔴 Went offline!"));Tip
Tip
Use window.location.hash for simple client-side routing without page reloads. Listen for the 'hashchange' event to update content based on the URL hash (#section).
Every website works on this model
Common Mistake
Warning
Accessing window properties without checking if you're in a browser environment. In SSR frameworks like Next.js, window is undefined on the server. Always check: if (typeof window !== 'undefined') { }.
Practice Task
Note
Window object exploration: (1) Log window.innerWidth and listen for resize events. (2) Use window.scrollTo with smooth behavior. (3) Open a new window with window.open and communicate with postMessage.
Quick Quiz
Key Takeaways
- The BOM (Browser Object Model) provides JavaScript access to browser features beyond the document — the window dimensions, URL, navigation history, and browser info.
- window — The global object. All global variables/functions are properties of window
- window.innerWidth / innerHeight — Browser viewport dimensions
- window.location — Current URL info: href, hostname, pathname, search, hash