Page Content

Posts

How to Use the JavaScript Browser Object Model Effectively

JavaScript Browser Object Model

One fundamental idea in client side JavaScript that allows your code to communicate with the web browser is the Browser Object Model (BOM). It’s frequently referred to as the “amazing ‘magic’ element” that links the browser and JavaScript code. The BOM contains all of the attributes and methods required for this interaction, such as window size information, visited page history, and HTML content (through the DOM).

It is noteworthy that the BOM does not have an established standard. As a result, how it is implemented can differ depending on the browser and version.

All of the client-side JavaScript features and APIs are accessed primarily through the window object. It symbolises the active tab or window in the browser and has all the characteristics and functions required to work with it. This includes the size of the window and the history of the webpages that have been seen. Global variables and functions are also contained in the window object. You can use the identifier window to refer to the window object.

Access to more important BOM objects is possible within the window object:

  • History: Shows what the user has browsed in the window that is currently open. Scripts can traverse the history with its help, and it offers attributes like length to determine how many entries there are. You use window.history to retrieve it.
  • Navigator: Offers details about the user’s browser. This contains information on the operating system platform (platform), language (language), browser name (appName), version (appVersion), cookie enabled (cookieEnabled), and user agent string (userAgent). The Netscape Navigator browser was the first to use it.
  • Location: Contains the URL of the current page. By modifying the location object’s properties, JavaScript can use it to load new sites. It can be accessed by window.location.
  • Screen: Information regarding the user’s display screen is provided by the screen. It has attributes like colorDepth, width, height, and availWidth and availHeight. Although not standard, this object has a lot of support.
  • Document (DOM): Denotes the HTML document that has been loaded. The web page’s HTML elements are contained within, and JavaScript can pick and modify certain areas of the page to make them interactive. The document object can be accessed by window.document and is technically nested inside the window object.

The console.dir() method can be used to examine the entire window object (and hence the BOM) structure in the developer console of your browser.

<h1>JavaScript BOM Objects as Properties of `window`</h1>
<p>This page demonstrates that common Browser Object Model (BOM) objects are directly accessible as properties of the global `window` object.</p>

<div class="section">
    <h2>1. `window.navigator` (Browser Information)</h2>
    <pre id="navigatorInfo"></pre>
    <div class="note">
        The `navigator` object provides information about the browser (e.g., user agent, platform, online status).
    </div>
</div>

<div class="section">
    <h2>2. `window.screen` (User's Screen Information)</h2>
    <pre id="screenInfo"></pre>
    <div class="note">
        The `screen` object provides details about the user's display screen (e.g., width, height, color depth).
    </div>
</div>

<div class="section">
    <h2>3. `window.location` (Current URL Information)</h2>
    <pre id="locationInfo"></pre>
    <button onclick="changeLocation()">Change Location (via window.location.assign)</button>
    <div class="note">
        The `location` object holds information about the current URL and allows programmatic navigation.
    </div>
</div>

<div class="section">
    <h2>4. `window.history` (Browser History)</h2>
    <pre id="historyInfo"></pre>
    <button onclick="goBack()">Go Back (via window.history.back)</button>
    <button onclick="goForward()">Go Forward (via window.history.forward)</button>
    <div class="note">
        The `history` object allows navigation through the browser's session history. (Try navigating to another page and then coming back to see its effect).
    </div>
</div>

<div class="section">
    <h2>5. `window.localStorage` & `window.sessionStorage` (Web Storage)</h2>
    <h3>Local Storage</h3>
    <button onclick="setLocalStorage()">Set Local Storage Item</button>
    <button onclick="getLocalStorage()">Get Local Storage Item</button>
    <button onclick="clearLocalStorage()">Clear Local Storage</button>
    <pre id="localStorageInfo"></pre>

    <h3>Session Storage</h3>
    <button onclick="setSessionStorage()">Set Session Storage Item</button>
    <button onclick="getSessionStorage()">Get Session Storage Item</button>
    <button onclick="clearSessionStorage()">Clear Session Storage</button>
    <pre id="sessionStorageInfo"></pre>
    <div class="note">
        `localStorage` persists data across browser sessions. `sessionStorage` clears data when the tab is closed. Both are accessed through `window`.
    </div>
</div>

<div class="section">
    <h2>6. Global Functions/Methods (implicitly `window.`)</h2>
    <button onclick="showAlert()">Show Alert (via window.alert)</button>
    <button onclick="setTimeExample()">Set Timeout Example (via window.setTimeout)</button>
    <div class="note">
        Common global functions like `alert()` and `setTimeout()` are also properties of the `window` object.
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        // Function to display info for each BOM object
        function displayBOMInfo() {
            // 1. window.navigator
            document.getElementById('navigatorInfo').textContent = `
                appName: ${window.navigator.appName}
                appCodeName: ${window.navigator.appCodeName}
                platform: ${window.navigator.platform}
                userAgent: ${window.navigator.userAgent}
                cookieEnabled: ${window.navigator.cookieEnabled}
                onLine: ${window.navigator.onLine}
            `;

            // 2. window.screen
            document.getElementById('screenInfo').textContent = `
                width: ${window.screen.width}px
                height: ${window.screen.height}px
                availWidth: ${window.screen.availWidth}px
                availHeight: ${window.screen.availHeight}px
                colorDepth: ${window.screen.colorDepth} bits
                pixelDepth: ${window.screen.pixelDepth} bits
            `;

            // 3. window.location
            document.getElementById('locationInfo').textContent = `
                href: ${window.location.href}
                protocol: ${window.location.protocol}
                host: ${window.location.host}
                hostname: ${window.location.hostname}
                port: ${window.location.port}
                pathname: ${window.location.pathname}
                search: ${window.location.search}
                hash: ${window.location.hash}
            `;

            // 4. window.history
            document.getElementById('historyInfo').textContent = `
                length: ${window.history.length}
            `;

            // 5. window.localStorage and window.sessionStorage
            updateStorageDisplays();
        }

        function updateStorageDisplays() {
            let localItems = [];
            for (let i = 0; i < window.localStorage.length; i++) {
                const key = window.localStorage.key(i);
                localItems.push(`${key}: "${window.localStorage.getItem(key)}"`);
            }
            document.getElementById('localStorageInfo').textContent = localItems.length > 0 ? localItems.join('\n') : 'No items in Local Storage.';

            let sessionItems = [];
            for (let i = 0; i < window.sessionStorage.length; i++) {
                const key = window.sessionStorage.key(i);
                sessionItems.push(`${key}: "${window.sessionStorage.getItem(key)}"`);
            }
            document.getElementById('sessionStorageInfo').textContent = sessionItems.length > 0 ? sessionItems.join('\n') : 'No items in Session Storage.';
        }

        // --- Event Handlers for Buttons ---

        // Location
        window.changeLocation = function() {
            // Using window.location.assign() to navigate
            const confirmChange = window.confirm("This will navigate to Example.com. Continue?");
            if (confirmChange) {
                window.location.assign("https://www.example.com");
            }
        };

        // History
        window.goBack = function() {
            // Using window.history.back()
            window.history.back();
        };

        window.goForward = function() {
            // Using window.history.forward()
            window.history.forward();
        };

        // Local Storage
        window.setLocalStorage = function() {
            window.localStorage.setItem('myLocalStorageKey', 'Hello from LocalStorage!');
            updateStorageDisplays();
            window.alert('Local Storage item set. Open developer tools (Application tab) to verify.');
        };

        window.getLocalStorage = function() {
            const value = window.localStorage.getItem('myLocalStorageKey');
            window.alert(`Value from Local Storage: ${value || 'Not found'}`);
        };

        window.clearLocalStorage = function() {
            window.localStorage.clear();
            updateStorageDisplays();
            window.alert('Local Storage cleared!');
        };

        // Session Storage
        window.setSessionStorage = function() {
            window.sessionStorage.setItem('mySessionStorageKey', 'Hello from SessionStorage!');
            updateStorageDisplays();
            window.alert('Session Storage item set. It will disappear when this tab is closed.');
        };

        window.getSessionStorage = function() {
            const value = window.sessionStorage.getItem('mySessionStorageKey');
            window.alert(`Value from Session Storage: ${value || 'Not found'}`);
        };

        window.clearSessionStorage = function() {
            window.sessionStorage.clear();
            updateStorageDisplays();
            window.alert('Session Storage cleared!');
        };

        // Global Functions
        window.showAlert = function() {
            window.alert("This alert was called via window.alert()!");
        };

        window.setTimeExample = function() {
            const messageDiv = document.getElementById('screenInfo'); // Re-using for temporary message
            messageDiv.textContent = "Setting a timeout... Message will appear in 2 seconds.";
            window.setTimeout(() => {
                window.alert("Timeout completed! This was set via window.setTimeout().");
                displayBOMInfo(); // Refresh display after alert
            }, 2000);
        };


        // Initial display when the page loads
        displayBOMInfo();
    });
</script>

JavaScript makes use of the BOM, specifically the window object, to manage the creation, resizing, and moving of windows, the display of dialogue boxes, and history navigation.

The alert(), prompt(), and confirm() methods are included in the window object to display basic modal dialogue windows. The reason they are named modal is that they halt the execution of the script and stop the user from interacting with the rest of the page until the dialogue is closed. The browser controls the look and precise location of the plain text messages in these dialogues, which are not HTML. Despite being helpful for basic tasks or troubleshooting, their disruptive behaviour and lack of customisation make them often unsuitable for production use.

  1. window.alert(message): A modal box containing a given message and a “OK” button is displayed via window.alert(message). Before the script executes further, it waits for the user to click “OK”. Plain text is shown for the message argument.
  2. window.prompt(message, default): Shows a modal box asking for input from the user. A message, input area (optionally pre-filled), and “OK” and “Cancel” buttons are included. If the user clicks “OK” or “Cancel” or “Escape,” the procedure returns the input as a string or null. The default argument is optional but suggested for compatibility.
  3. window.confirm(question): A modal box with a question and “OK” and “Cancel” buttons is displayed via window.confirm(question). A boolean value is returned: true if the user selects “OK” and false if they select “Cancel.” This is frequently used to get user confirmation before taking action.

<!DOCTYPE html>
<html>
<head>
<title>Window Object Example</title>
<style>
body { font-family: Arial, sans-serif; }
div { margin-bottom: 10px; }
</style>
</head>
<body>

<h1>Window Object Properties & Methods</h1>

<div>
<button onclick=”showAlert()”>Show Alert</button>
<button onclick=”showConfirm()”>Show Confirm</button>
<button onclick=”showPrompt()”>Show Prompt</button>
</div>


<script>

function showAlert() {
window.alert(“This is a simple alert message!”);
}

function showConfirm() {
const result = window.confirm(“Do you want to proceed?”);
alert(`You clicked: ${result ? ‘OK’ : ‘Cancel’}`);
}

function showPrompt() {
const name = window.prompt(“Please enter your name:”, “Guest”);
if (name !== null) { // User clicked OK
alert(`Hello, ${name}!`);
} else { // User clicked Cancel
alert(“You cancelled the prompt.”);
}
}

</script>
</body>
</html>

In conclusion, JavaScript needs the BOM, which is centred on the window object, to manage and communicate with the browser environment. This interface is separate from but connected to the DOM, which manages the content of the page. The alert(), prompt(), and confirm() methods are straightforward BOM tools for modal dialogue box based user interaction.