Explore Browser Object Model (BOM) Methods in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

Introduction

In this lab, participants will explore the Browser Object Model (BOM) methods in JavaScript by creating a comprehensive demonstration project. The lab guides learners through setting up a basic HTML and JavaScript environment, and then systematically introduces key BOM interaction methods such as alert(), prompt(), confirm(), and window manipulation techniques.

Participants will progressively build a practical project that showcases different browser interaction methods, starting with creating a project structure, implementing user notification dialogs, and experimenting with window control functions. By following the step-by-step instructions, students will gain hands-on experience in using JavaScript's browser-related methods to create interactive web experiences and understand how to communicate with users through various dialog types and window management techniques.

Set Up HTML Project for BOM Demonstration

In this step, you'll set up a basic HTML project to demonstrate Browser Object Model (BOM) methods in JavaScript. We'll create a simple project structure that will serve as the foundation for exploring various BOM interactions.

First, navigate to the project directory:

cd ~/project

Create a new directory for the BOM demonstration project:

mkdir bom-demo
cd bom-demo

Now, use the WebIDE to create an index.html file with a basic HTML structure:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>BOM Methods Demonstration</title>
  </head>
  <body>
    <h1>Browser Object Model (BOM) Methods</h1>
    <div id="output"></div>

    <script src="bom-methods.js"></script>
  </body>
</html>

Create a corresponding JavaScript file bom-methods.js in the same directory:

// This file will contain our BOM method demonstrations
console.log("BOM Methods Project Initialized");

Verify that the files are created correctly:

ls

Example output:

index.html
bom-methods.js

Open the index.html file in a web browser to ensure everything is set up correctly. You should see the page title and be able to open the browser's developer console to view the initial log message.

This project structure provides a clean, simple environment to explore and demonstrate various Browser Object Model (BOM) methods in the upcoming steps of the lab.

Implement Alert Method for Basic User Notification

In this step, you'll learn about the window.alert() method, which is a fundamental Browser Object Model (BOM) method for displaying simple notification messages to users. The alert method creates a popup dialog that pauses script execution and requires user acknowledgment.

Navigate to the project directory:

cd ~/project/bom-demo

Open the bom-methods.js file in the WebIDE and add the following JavaScript code:

// Demonstrate window.alert() method
function showBasicAlert() {
  window.alert("Welcome to BOM Methods Demonstration!");
}

// Create a button to trigger the alert
function createAlertButton() {
  const button = document.createElement("button");
  button.textContent = "Show Alert";
  button.onclick = showBasicAlert;
  document.body.appendChild(button);
}

// Call the function to add button when page loads
createAlertButton();

Modify the index.html file to ensure the JavaScript is properly linked:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>BOM Methods Demonstration</title>
  </head>
  <body>
    <h1>Browser Object Model (BOM) Methods</h1>
    <div id="output"></div>

    <script src="bom-methods.js"></script>
  </body>
</html>

When you open the index.html file in a web browser, you'll see a "Show Alert" button. Clicking this button will trigger a popup alert dialog with the message "Welcome to BOM Methods Demonstration!".

Key points about window.alert():

  • It's a method of the window object
  • Creates a blocking dialog that pauses script execution
  • Requires user to click "OK" to continue
  • Typically used for simple notifications or debugging

Example alert dialog appearance:

[Alert Dialog]
Welcome to BOM Methods Demonstration!
                [OK]

Create Prompt Dialog for User Input Interaction

In this step, you'll explore the window.prompt() method, which allows interactive user input through a dialog box. This BOM method enables you to collect simple text input from users directly in the browser.

Navigate to the project directory:

cd ~/project/bom-demo

Open the bom-methods.js file in the WebIDE and add the following JavaScript code:

// Demonstrate window.prompt() method
function showPromptDialog() {
  // Prompt user for their name with a default value
  let userName = window.prompt("What is your name?", "Guest");

  // Check if user entered a name
  if (userName !== null && userName !== "") {
    const outputDiv = document.getElementById("output");
    outputDiv.textContent = `Hello, ${userName}! Welcome to BOM Methods.`;
  } else {
    const outputDiv = document.getElementById("output");
    outputDiv.textContent = "No name entered.";
  }
}

// Create a button to trigger the prompt
function createPromptButton() {
  const button = document.createElement("button");
  button.textContent = "Enter Name";
  button.onclick = showPromptDialog;
  document.body.appendChild(button);
}

// Call the function to add button when page loads
createPromptButton();

Update the index.html file to include an output div:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>BOM Methods Demonstration</title>
  </head>
  <body>
    <h1>Browser Object Model (BOM) Methods</h1>
    <div id="output"></div>

    <script src="bom-methods.js"></script>
  </body>
</html>

Key points about window.prompt():

  • Returns the text entered by the user
  • Allows an optional default value
  • Returns null if the user cancels the prompt
  • Blocks script execution until user responds

Example prompt dialog interaction:

[Prompt Dialog]
What is your name? [Guest]
        [OK]   [Cancel]

When you open the index.html file in a web browser:

  1. Click the "Enter Name" button
  2. A prompt will appear asking for your name
  3. Enter a name or click OK with the default value
  4. The output div will display a personalized greeting

Add Confirm Dialog for User Decision Making

In this step, you'll explore the window.confirm() method, which provides a simple way to get user confirmation through a dialog box with "OK" and "Cancel" options. This BOM method is useful for creating interactive decision-making scenarios in web applications.

Navigate to the project directory:

cd ~/project/bom-demo

Open the bom-methods.js file in the WebIDE and add the following JavaScript code:

// Demonstrate window.confirm() method
function showConfirmDialog() {
  const outputDiv = document.getElementById("output");

  // Display a confirmation dialog
  const userDecision = window.confirm("Do you want to continue?");

  // Check user's response
  if (userDecision) {
    outputDiv.textContent = "User clicked OK. Proceeding with the action.";
    outputDiv.style.color = "green";
  } else {
    outputDiv.textContent = "User clicked Cancel. Action aborted.";
    outputDiv.style.color = "red";
  }
}

// Create a button to trigger the confirm dialog
function createConfirmButton() {
  const button = document.createElement("button");
  button.textContent = "Show Confirm Dialog";
  button.onclick = showConfirmDialog;
  document.body.appendChild(button);
}

// Call the function to add button when page loads
createConfirmButton();

Update the index.html file to ensure the output div is present:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>BOM Methods Demonstration</title>
  </head>
  <body>
    <h1>Browser Object Model (BOM) Methods</h1>
    <div id="output"></div>

    <script src="bom-methods.js"></script>
  </body>
</html>

Key points about window.confirm():

  • Returns true if user clicks "OK"
  • Returns false if user clicks "Cancel"
  • Blocks script execution until user makes a choice
  • Useful for simple yes/no decisions

Example confirm dialog interaction:

[Confirm Dialog]
Do you want to continue?
        [OK]   [Cancel]

When you open the index.html file in a web browser:

  1. Click the "Show Confirm Dialog" button
  2. A confirmation dialog will appear
  3. Choose either "OK" or "Cancel"
  4. The output div will display the result of your choice

Experiment with Window Open and Close Methods

In this step, you'll explore the window.open() and window.close() methods, which allow you to programmatically create and manage new browser windows or tabs.

Navigate to the project directory:

cd ~/project/bom-demo

First, create a new HTML file called popup.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Popup Window</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        text-align: center;
        padding: 20px;
      }
    </style>
  </head>
  <body>
    <h1>This is a Popup Window</h1>
    <p>Opened using window.open() method</p>
    <button onclick="window.close()">Close Window</button>
  </body>
</html>

Now, update the bom-methods.js file with window manipulation methods:

// Function to open a new window
function openNewWindow() {
  const outputDiv = document.getElementById("output");

  // Open a new window with specific dimensions
  const newWindow = window.open(
    "popup.html",
    "PopupWindow",
    "width=400,height=300,resizable=yes"
  );

  // Check if window was successfully opened
  if (newWindow) {
    outputDiv.textContent = "New window opened successfully!";
  } else {
    outputDiv.textContent = "Popup blocked. Please allow popups.";
  }
}

// Function to close the most recently opened window
function closeLastWindow() {
  const outputDiv = document.getElementById("output");

  try {
    // Attempt to close the last opened window
    const lastWindow = window.open("", "_blank");
    if (lastWindow) {
      lastWindow.close();
      outputDiv.textContent = "Last opened window closed.";
    } else {
      outputDiv.textContent = "No window to close.";
    }
  } catch (error) {
    outputDiv.textContent = "Error closing window.";
  }
}

// Create buttons for window operations
function createWindowButtons() {
  const openButton = document.createElement("button");
  openButton.textContent = "Open New Window";
  openButton.onclick = openNewWindow;

  const closeButton = document.createElement("button");
  closeButton.textContent = "Close Last Window";
  closeButton.onclick = closeLastWindow;

  document.body.appendChild(openButton);
  document.body.appendChild(closeButton);
}

// Call the function to add buttons when page loads
createWindowButtons();

Update the index.html file to ensure compatibility:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>BOM Methods Demonstration</title>
  </head>
  <body>
    <h1>Browser Object Model (BOM) Methods</h1>
    <div id="output"></div>

    <script src="bom-methods.js"></script>
  </body>
</html>

Key points about window.open() and window.close():

  • window.open() creates a new browser window or tab
  • Can specify URL, window name, and features
  • window.close() closes the current or specified window
  • Popup blockers may prevent window opening

When you open the index.html file in a web browser:

  1. Click "Open New Window" to create a new popup window
  2. Click "Close Last Window" to close the recently opened window
  3. The output div will show the status of window operations

Summary

In this lab, participants explored the Browser Object Model (BOM) methods through a hands-on JavaScript project. The lab began by setting up a structured HTML and JavaScript environment, creating a foundation for demonstrating various browser interaction techniques. Participants learned how to create project files, configure basic HTML structure, and prepare a JavaScript file for method demonstrations.

The initial steps focused on understanding fundamental BOM methods, starting with the window.alert() method for user notifications. By progressively implementing different browser interaction methods like prompts, confirmations, and window manipulation, learners gained practical experience in using JavaScript's browser-level APIs to create interactive web experiences and manage browser window behaviors.

Other JavaScript Tutorials you may like