Skip to main content
Course/Module 7/Topic 3 of 3Intermediate

JavaScript Browser Object Model (BOM)

Learn about the Browser Object Model, window object, location, history, and browser-specific APIs for building cross-browser applications

40 minBy Priygop TeamLast updated: Feb 2026

BOM Overview

The Browser Object Model (BOM) provides objects and methods for interacting with the browser window and browser-specific features. It includes the window object, location, history, and other browser APIs.

Window Object

Example
// Window object properties and methods
// Window dimensions
console.log('Window width:', window.innerWidth);
console.log('Window height:', window.innerHeight);
console.log('Screen width:', window.screen.width);
console.log('Screen height:', window.screen.height);

// Window scrolling
window.scrollTo(0, 100); // Scroll to specific position
window.scrollBy(0, 50);  // Scroll by specific amount
window.scrollTo({
    top: 200,
    left: 0,
    behavior: 'smooth'
});

// Window opening and closing
const newWindow = window.open('https://example.com', '_blank', 'width=500,height=400');
// newWindow.close(); // Close the window

// Window focus and blur
window.addEventListener('focus', () => {
    console.log('Window gained focus');
});

window.addEventListener('blur', () => {
    console.log('Window lost focus');
});

// Window resize
window.addEventListener('resize', () => {
    console.log('Window resized to:', window.innerWidth, 'x', window.innerHeight);
});

// Window beforeunload
window.addEventListener('beforeunload', (e) => {
    e.preventDefault();
    e.returnValue = ''; // Show confirmation dialog
});

// Window load
window.addEventListener('load', () => {
    console.log('Page fully loaded');
});

// Window online/offline
window.addEventListener('online', () => {
    console.log('Browser is online');
});

window.addEventListener('offline', () => {
    console.log('Browser is offline');
});

Location Object

Example
// Location object properties and methods
console.log('Current URL:', window.location.href);
console.log('Protocol:', window.location.protocol);
console.log('Hostname:', window.location.hostname);
console.log('Port:', window.location.port);
console.log('Pathname:', window.location.pathname);
console.log('Search:', window.location.search);
console.log('Hash:', window.location.hash);

// URL parsing
const url = new URL(window.location.href);
console.log('URL object:', url);
console.log('Search params:', url.searchParams);

// Getting query parameters
const searchParams = new URLSearchParams(window.location.search);
const id = searchParams.get('id');
const name = searchParams.get('name');
console.log('ID:', id);
console.log('Name:', name);

// Setting query parameters
searchParams.set('page', '2');
searchParams.set('sort', 'name');
const newUrl = window.location.pathname + '?' + searchParams.toString();
console.log('New URL:', newUrl);

// Navigation methods
// window.location.href = 'https://example.com'; // Navigate to new URL
// window.location.assign('https://example.com'); // Navigate to new URL
// window.location.replace('https://example.com'); // Navigate without adding to history
// window.location.reload(); // Reload current page
// window.location.reload(true); // Force reload from server

// Hash navigation
window.addEventListener('hashchange', () => {
    console.log('Hash changed to:', window.location.hash);
});

// Example: Simple router
function handleRoute() {
    const hash = window.location.hash.slice(1) || 'home';
    
    switch(hash) {
        case 'home':
            showHome();
            break;
        case 'about':
            showAbout();
            break;
        case 'contact':
            showContact();
            break;
        default:
            show404();
    }
}

window.addEventListener('hashchange', handleRoute);
window.addEventListener('load', handleRoute);

History Object

Example
// History object methods
console.log('History length:', window.history.length);

// Navigation methods
// window.history.back(); // Go back one page
// window.history.forward(); // Go forward one page
// window.history.go(-2); // Go back 2 pages
// window.history.go(1); // Go forward 1 page

// History state management
const state = {
    page: 'home',
    data: { id: 123, name: 'John' }
};

// Push new state
window.history.pushState(state, 'Home Page', '/home');

// Replace current state
window.history.replaceState(state, 'Home Page', '/home');

// Listen for popstate
window.addEventListener('popstate', (event) => {
    console.log('State:', event.state);
    handleRoute(event.state);
});

// Example: Single Page Application (SPA) router
class SPARouter {
    constructor() {
        this.routes = {
            '/': this.showHome,
            '/about': this.showAbout,
            '/contact': this.showContact
        };
        
        this.init();
    }
    
    init() {
        window.addEventListener('popstate', (e) => this.handleRoute());
        this.handleRoute();
    }
    
    navigate(path) {
        const state = { path, timestamp: Date.now() };
        window.history.pushState(state, '', path);
        this.handleRoute();
    }
    
    handleRoute() {
        const path = window.location.pathname;
        const handler = this.routes[path] || this.show404;
        handler.call(this);
    }
    
    showHome() {
        document.getElementById('app').innerHTML = '<h1>Home Page</h1>';
    }
    
    showAbout() {
        document.getElementById('app').innerHTML = '<h1>About Page</h1>';
    }
    
    showContact() {
        document.getElementById('app').innerHTML = '<h1>Contact Page</h1>';
    }
    
    show404() {
        document.getElementById('app').innerHTML = '<h1>404 - Page Not Found</h1>';
    }
}

// Usage
// const router = new SPARouter();
// router.navigate('/about');

Storage APIs

Example
// Local Storage
// Setting data
localStorage.setItem('user', JSON.stringify({
    name: 'John Doe',
    email: 'john@example.com',
    preferences: {
        theme: 'dark',
        language: 'en'
    }
}));

// Getting data
const user = JSON.parse(localStorage.getItem('user'));
console.log('User:', user);

// Removing data
localStorage.removeItem('user');

// Clearing all data
localStorage.clear();

// Session Storage (similar to localStorage but session-based)
sessionStorage.setItem('sessionId', 'abc123');
const sessionId = sessionStorage.getItem('sessionId');
sessionStorage.removeItem('sessionId');

// Storage events
window.addEventListener('storage', (e) => {
    console.log('Storage changed:', e.key);
    console.log('Old value:', e.oldValue);
    console.log('New value:', e.newValue);
    console.log('Storage area:', e.storageArea);
});

// Example: User preferences manager
class UserPreferences {
    constructor() {
        this.storageKey = 'userPreferences';
        this.defaults = {
            theme: 'light',
            language: 'en',
            notifications: true,
            autoSave: true
        };
        this.preferences = this.load();
    }
    
    load() {
        const stored = localStorage.getItem(this.storageKey);
        if (stored) {
            return { ...this.defaults, ...JSON.parse(stored) };
        }
        return { ...this.defaults };
    }
    
    save() {
        localStorage.setItem(this.storageKey, JSON.stringify(this.preferences));
    }
    
    get(key) {
        return this.preferences[key];
    }
    
    set(key, value) {
        this.preferences[key] = value;
        this.save();
    }
    
    reset() {
        this.preferences = { ...this.defaults };
        this.save();
    }
    
    getAll() {
        return { ...this.preferences };
    }
}

// Usage
const prefs = new UserPreferences();
prefs.set('theme', 'dark');
prefs.set('language', 'es');
console.log('Theme:', prefs.get('theme'));
console.log('All preferences:', prefs.getAll());

Practice Exercise: BOM

Example
// Exercise: Build a Browser Information Dashboard
class BrowserDashboard {
    constructor() {
        this.init();
    }
    
    init() {
        this.createDashboard();
        this.updateInfo();
        this.bindEvents();
    }
    
    createDashboard() {
        const dashboard = document.createElement('div');
        dashboard.id = 'browser-dashboard';
        dashboard.style.cssText = `
            position: fixed;
            top: 10px;
            right: 10px;
            background: white;
            border: 1px solid #ccc;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            font-family: Arial, sans-serif;
            font-size: 12px;
            max-width: 300px;
        `;
        
        dashboard.innerHTML = `
            <h3>Browser Info</h3>
            <div id="browser-info"></div>
            <h3>Window Info</h3>
            <div id="window-info"></div>
            <h3>Storage Info</h3>
            <div id="storage-info"></div>
            <button id="refresh-dashboard">Refresh</button>
            <button id="clear-storage">Clear Storage</button>
        `;
        
        document.body.appendChild(dashboard);
    }
    
    updateInfo() {
        this.updateBrowserInfo();
        this.updateWindowInfo();
        this.updateStorageInfo();
    }
    
    updateBrowserInfo() {
        const info = document.getElementById('browser-info');
        info.innerHTML = `
            <p><strong>User Agent:</strong> ${navigator.userAgent}</p>
            <p><strong>Platform:</strong> ${navigator.platform}</p>
            <p><strong>Language:</strong> ${navigator.language}</p>
            <p><strong>Online:</strong> ${navigator.onLine ? 'Yes' : 'No'}</p>
            <p><strong>Cookies:</strong> ${navigator.cookieEnabled ? 'Enabled' : 'Disabled'}</p>
        `;
    }
    
    updateWindowInfo() {
        const info = document.getElementById('window-info');
        info.innerHTML = `
            <p><strong>Window Size:</strong> ${window.innerWidth} x ${window.innerHeight}</p>
            <p><strong>Screen Size:</strong> ${window.screen.width} x ${window.screen.height}</p>
            <p><strong>Scroll Position:</strong> ${window.pageYOffset}px</p>
            <p><strong>URL:</strong> ${window.location.href}</p>
            <p><strong>History Length:</strong> ${window.history.length}</p>
        `;
    }
    
    updateStorageInfo() {
        const info = document.getElementById('storage-info');
        const localStorageSize = this.getStorageSize(localStorage);
        const sessionStorageSize = this.getStorageSize(sessionStorage);
        
        info.innerHTML = `
            <p><strong>Local Storage:</strong> ${localStorageSize} items</p>
            <p><strong>Session Storage:</strong> ${sessionStorageSize} items</p>
            <p><strong>Available Storage:</strong> ${this.getAvailableStorage()} MB</p>
        `;
    }
    
    getStorageSize(storage) {
        return Object.keys(storage).length;
    }
    
    getAvailableStorage() {
        if ('storage' in navigator && 'estimate' in navigator.storage) {
            return navigator.storage.estimate().then(estimate => {
                return Math.round(estimate.quota / 1024 / 1024);
            });
        }
        return 'Unknown';
    }
    
    bindEvents() {
        document.getElementById('refresh-dashboard').addEventListener('click', () => {
            this.updateInfo();
        });
        
        document.getElementById('clear-storage').addEventListener('click', () => {
            localStorage.clear();
            sessionStorage.clear();
            this.updateStorageInfo();
        });
        
        // Auto-update on window events
        window.addEventListener('resize', () => this.updateWindowInfo());
        window.addEventListener('scroll', () => this.updateWindowInfo());
        window.addEventListener('online', () => this.updateBrowserInfo());
        window.addEventListener('offline', () => this.updateBrowserInfo());
    }
}

// Initialize dashboard
// const dashboard = new BrowserDashboard();

Try It Yourself — DOM Manipulation & Events

Try It Yourself — DOM Manipulation & EventsHTML
HTML Editor
✓ ValidTab = 2 spaces
HTML|106 lines|4436 chars|✓ Valid syntax
UTF-8

Quick Quiz — DOM Manipulation & Events

Chat on WhatsApp
Priygop - Leading Professional Development Platform | Expert Courses & Interview Prep