JavaScript におけるブラウザオブジェクトモデル(BOM)メソッドを探索する

JavaScriptBeginner
オンラインで実践に進む

はじめに

この実験では、参加者は包括的なデモプロジェクトを作成することで JavaScript のブラウザオブジェクトモデル(BOM)メソッドを探索します。この実験では、学習者が基本的な HTML と JavaScript の環境をセットアップする方法を案内し、その後、alert()、prompt()、confirm() などの重要な BOM インタラクションメソッドとウィンドウ操作技術を体系的に紹介します。

参加者は、まずプロジェクト構造を作成し、ユーザ通知ダイアログを実装し、ウィンドウ制御関数を試すことから始まり、異なるブラウザインタラクション方法を紹介する実用的なプロジェクトを段階的に構築します。手順に従って、学生は JavaScript のブラウザ関連メソッドを使用してインタラクティブなウェブエクスペリエンスを作成し、さまざまなダイアログタイプとウィンドウ管理技術を通じてユーザと通信する方法を理解するための実践的な経験を得るでしょう。

BOM デモ用の HTML プロジェクトをセットアップする

このステップでは、JavaScript のブラウザオブジェクトモデル(BOM)メソッドを示すための基本的な HTML プロジェクトをセットアップします。さまざまな BOM インタラクションを探索するための基盤となる簡単なプロジェクト構造を作成します。

まず、プロジェクトディレクトリに移動します。

cd ~/project

BOM デモプロジェクト用の新しいディレクトリを作成します。

mkdir bom-demo
cd bom-demo

次に、WebIDE を使って基本的な HTML 構造を持つindex.htmlファイルを作成します。

<!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>

同じディレクトリに対応する JavaScript ファイルbom-methods.jsを作成します。

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

ファイルが正しく作成されたことを確認します。

ls

出力例:

index.html
bom-methods.js

index.htmlファイルを Web ブラウザで開き、すべてが正しくセットアップされていることを確認します。ページタイトルが表示され、ブラウザの開発者コンソールを開いて初期のログメッセージを表示できるはずです。

このプロジェクト構造は、この実験の次のステップでさまざまなブラウザオブジェクトモデル(BOM)メソッドを探索して示すためのクリーンで簡単な環境を提供します。

基本的なユーザ通知のためのアラートメソッドを実装する

このステップでは、window.alert()メソッドについて学びます。これは、ユーザに簡単な通知メッセージを表示するための基本的なブラウザオブジェクトモデル(BOM)メソッドです。alert メソッドは、ポップアップダイアログを作成し、スクリプトの実行を一時停止してユーザの承認を必要とします。

プロジェクトディレクトリに移動します。

cd ~/project/bom-demo

WebIDE でbom-methods.jsファイルを開き、次の JavaScript コードを追加します。

// 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();

JavaScript が適切にリンクされるようにindex.htmlファイルを修正します。

<!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>

index.htmlファイルを Web ブラウザで開くと、「Show Alert」ボタンが表示されます。このボタンをクリックすると、「Welcome to BOM Methods Demonstration!」というメッセージが表示されるポップアップ alert ダイアログがトリガーされます。

window.alert()に関するポイント:

  • windowオブジェクトのメソッドです
  • ブロッキングダイアログを作成してスクリプトの実行を一時停止します
  • ユーザが「OK」をクリックして続行する必要があります
  • 通常、簡単な通知やデバッグに使用されます

alert ダイアログの外観例:

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

ユーザ入力インタラクションのためのプロンプトダイアログを作成する

このステップでは、window.prompt()メソッドを探索します。このメソッドを使うと、ダイアログボックスを通じてユーザに対するインタラクティブな入力を行うことができます。この BOM メソッドを使えば、ブラウザ上でユーザから簡単なテキスト入力を直接収集することができます。

プロジェクトディレクトリに移動します。

cd ~/project/bom-demo

WebIDE でbom-methods.jsファイルを開き、次の JavaScript コードを追加します。

// 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();

出力用の div を含むようにindex.htmlファイルを更新します。

<!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>

window.prompt()に関するポイント:

  • ユーザが入力したテキストを返します
  • オプションの初期値を設定できます
  • ユーザが prompt をキャンセルした場合はnullを返します
  • ユーザの応答があるまでスクリプトの実行をブロックします

prompt ダイアログのインタラクション例:

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

index.htmlファイルを Web ブラウザで開いたとき:

  1. 「Enter Name」ボタンをクリックします
  2. 名前を尋ねる prompt が表示されます
  3. 名前を入力するか、初期値のまま OK をクリックします
  4. 出力用の div に個別化された挨拶が表示されます

ユーザの意思決定のために確認ダイアログを追加する

このステップでは、window.confirm()メソッドを探索します。このメソッドは、「OK」と「キャンセル」のオプションがあるダイアログボックスを通じてユーザの確認を得るための簡単な方法を提供します。この BOM メソッドは、Web アプリケーションにおいてインタラクティブな意思決定のシナリオを作成する際に役立ちます。

プロジェクトディレクトリに移動します。

cd ~/project/bom-demo

WebIDE でbom-methods.jsファイルを開き、次の JavaScript コードを追加します。

// 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();

出力用の div があることを確認するためにindex.htmlファイルを更新します。

<!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>

window.confirm()に関するポイント:

  • ユーザが「OK」をクリックした場合はtrueを返します
  • ユーザが「キャンセル」をクリックした場合はfalseを返します
  • ユーザが選択するまでスクリプトの実行をブロックします
  • 簡単なはい/いいえの決定に役立ちます

confirm ダイアログのインタラクション例:

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

index.htmlファイルを Web ブラウザで開いたとき:

  1. 「Show Confirm Dialog」ボタンをクリックします
  2. 確認ダイアログが表示されます
  3. 「OK」または「キャンセル」を選択します
  4. 出力用の div に選択結果が表示されます

ウィンドウのオープンとクローズメソッドを試す

このステップでは、window.open()window.close()メソッドを探索します。これらのメソッドを使うと、プログラム的に新しいブラウザウィンドウまたはタブを作成して管理することができます。

プロジェクトディレクトリに移動します。

cd ~/project/bom-demo

まず、popup.htmlという新しい 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>

次に、bom-methods.jsファイルを更新してウィンドウ操作メソッドを追加します。

// 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();

互換性を確認するためにindex.htmlファイルを更新します。

<!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>

window.open()window.close()に関するポイント:

  • window.open()は新しいブラウザウィンドウまたはタブを作成します
  • URL、ウィンドウ名、機能を指定できます
  • window.close()は現在のまたは指定されたウィンドウを閉じます
  • ポップアップブロッカーがウィンドウの開きを阻止する場合があります

index.htmlファイルを Web ブラウザで開いたとき:

  1. 「Open New Window」をクリックして新しいポップアップウィンドウを作成します
  2. 「Close Last Window」をクリックして最近開いたウィンドウを閉じます
  3. 出力用の div にウィンドウ操作の状態が表示されます

まとめ

この実験では、参加者は JavaScript の実践プロジェクトを通じてブラウザオブジェクトモデル(BOM)のメソッドを探求しました。この実験は、構造化された HTML と JavaScript の環境をセットアップすることから始まり、さまざまなブラウザのインタラクション技術を示すための基盤を作りました。参加者は、プロジェクトファイルを作成する方法、基本的な HTML 構造を構成する方法、およびメソッドのデモ用の JavaScript ファイルを準備する方法を学びました。

最初のステップは、ユーザ通知のためのwindow.alert()メソッドから始まり、基本的な BOM メソッドを理解することに焦点を当てました。プロンプト、確認、ウィンドウ操作など、さまざまなブラウザのインタラクション方法を徐々に実装することで、学習者は JavaScript のブラウザレベルの API を使ってインタラクティブな Web 体験を作成し、ブラウザウィンドウの動作を管理する実践的な経験を得ました。