Browser Object Model Basics

Get started with the browser object model and learn about windows, page URLs, timers, and more.

🎯 Introduction

The browser object model is a key foundation of front-end development. It helps you work with the browser window and page environment, including reading the current URL, navigating history, displaying dialogs, and managing timers. These capabilities let your pages interact with the browser environment and improve the user experience.


🌐 What Is the Browser Object Model?

The Browser Object Model (BOM) is a group of browser-provided objects for working with the browser window and environment. It is distinct from HTML and the DOM, but closely connected to the environment in which a page runs.

Think of the BOM as a remote control for the browser: it gives you access to windows, the address bar, navigation history, and timers.


🧭 window: The Core BOM Object

Browser BOM functionality is exposed through the window object.

For example:

<!DOCTYPE html>
<html>
    <head>
        <title>BOM example</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                line-height: 1.6;
                padding: 20px;
            }
            pre {
                background: #f4f4f4;
                padding: 10px;
                border-radius: 5px;
                overflow-x: auto;
            }
        </style>
    </head>
    <body>
        <h2>View the current page title</h2>
        <button onclick="alert(window.document.title)">Show the page title</button>
    </body>
</html>

window.document.title accesses the current page title through window. You can also write document.title directly because document is available through the browser’s global window object.


🌍 Common BOM Objects and Properties

1. location: Read and Update the URL

window.location contains information about the current page’s address. Use it to read the URL or navigate to another page.

Common properties:

  • location.href: The full page URL
  • location.hostname: The domain name, such as www.example.com
  • location.pathname: The path, such as /index.html
  • location.protocol: The protocol, such as https:

Example:

console.log(location.href); // Print the full URL
console.log(location.hostname); // Print the domain name
console.log(location.pathname); // Print the path

Navigate to another page:

// Navigate to Baidu
location.href = 'https://www.baidu.com';

2. history: Browser Navigation History

window.history lets you navigate the browser’s session history, including going backward, going forward, and reloading the current entry.

Common methods:

  • history.back(): Go back one entry
  • history.forward(): Go forward one entry
  • history.go(n): Move n entries relative to the current entry; n can be positive or negative

Example:

// Go back one entry
history.back();

// Go forward one entry
history.forward();

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

3. alert, confirm, and prompt: Dialogs

These three BOM methods provide simple ways to interact with users.

  • alert(message): Display an alert dialog
  • confirm(message): Display a confirmation dialog and return true or false
  • prompt(message, default): Display an input dialog and return the entered text

Example:

alert('Welcome!');

if (confirm('Are you sure you want to leave?')) {
    alert('Goodbye!');
}

let name = prompt('Enter your name', 'Alex');
alert('Hello, ' + name);

4. navigator: Browser Information

window.navigator exposes information about the browser, including its name, version, and platform.

Example:

console.log('Browser name: ' + navigator.appName);
console.log('Browser version: ' + navigator.appVersion);
console.log('Operating system: ' + navigator.platform);

5. screen: Screen Information

window.screen exposes information about the user’s screen, including its dimensions and available display area.

Example:

console.log('Screen width: ' + screen.width);
console.log('Screen height: ' + screen.height);
console.log('Available width: ' + screen.availWidth);
console.log('Available height: ' + screen.availHeight);

⏰ BOM Timers: setTimeout and setInterval

Web pages often need delayed or repeated operations. The BOM provides two useful timer functions:

  • setTimeout(fn, delay): Run a function once after a delay
  • setInterval(fn, interval): Run a function repeatedly at a specified interval

Example:

// Show an alert after 2 seconds
setTimeout(function () {
    alert('2 seconds have passed!');
}, 2000);

// Print the current time every second
setInterval(function () {
    console.log(new Date().toLocaleTimeString());
}, 1000);
Cancel timers with clearTimeout and clearInterval when they are no longer needed to avoid unnecessary work and retained resources.

❓ Knowledge Check

Q1: What is the BOM, and how does it differ from the DOM?

The BOM provides interfaces for the browser window and environment, primarily through window. The DOM represents the page’s content and structure. They address different concerns but are often used together.

Q2: How do you navigate to another page using the BOM?

Set window.location.href to the new URL, for example location.href = "https://www.baidu.com";.

Q3: When would you use setInterval?

Use setInterval to repeat an operation at a fixed interval, such as updating a clock every second or automatically advancing a carousel.


🧪 Exercises

Exercise 1: Display the Current URL’s Domain Name and Path

<!DOCTYPE html>
<html>
    <head>
        <title>BOM exercise 1</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                padding: 20px;
            }
            #info {
                margin-top: 20px;
                font-size: 16px;
                color: #333;
            }
        </style>
    </head>
    <body>
        <h3>Display the current page’s domain name and path</h3>
        <button id="btn">Show URL information</button>
        <div id="info"></div>

        <script>
            document.getElementById('btn').onclick = function () {
                // Display the page’s domain name and path here
            };
        </script>
    </body>
</html>

Exercise 2: Display the Time Every Second and Add a Stop Button

<!DOCTYPE html>
<html>
    <head>
        <title>BOM exercise 2</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                padding: 20px;
            }
            #time {
                font-size: 20px;
                color: #007acc;
            }
            button {
                margin-top: 10px;
                padding: 5px 10px;
                font-size: 16px;
            }
        </style>
    </head>
    <body>
        <h3>Display the time every second; click the button to stop</h3>
        <div id="time">--:--:--</div>
        <button id="stopBtn">Stop displaying the time</button>

        <script>
            var timer = setInterval(function () {
                var now = new Date();
                document.getElementById('time').textContent = now.toLocaleTimeString();
            }, 1000);

            // Stop the time updates here
        </script>
    </body>
</html>

🎉 You now know the basics of the BOM, including window, location, history, navigator, screen, setTimeout, and setInterval. Keep practicing to build your front-end development skills!