0Pricing
Browser Extensions Development (Chrome & Edge) · レッスン

一方向メッセージングパターン

コンテンツスクリプトとバックグラウンドサービスワーカー間で、またはその逆方向に、シンプルな一方向通信を実装します。

「一方向メッセージングパターン」はCoddyKit上の無料Browser Extensions Development (Chrome & Edge)レッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはBrowser Extensions Development (Chrome & Edge)学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Browser Extensions Development (Chrome & Edge)コースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

One-Way Messaging Intro

Welcome! In this lesson, we'll explore one-way communication in browser extensions. This is how different parts of your extension can talk to each other, like a content script sending data to your background service worker, or vice versa.

Think of it like sending a message without expecting an immediate reply.

Isolated Extension Worlds

Browser extensions are designed with security in mind. This means different components of your extension (like content scripts and background service workers) live in their own isolated JavaScript environments.

  • Content Scripts: Run directly on web pages.
  • Background Service Worker: Runs in the background, handling events and persistent logic.

They can't directly access each other's variables or functions. Messaging is the bridge!

CS to BG: Sending Messages

To send a one-way message from a content script to your background service worker, you use the chrome.runtime.sendMessage() method.

You pass an object (your message) as the first argument. This object can contain any data you want to send.

Content Script Sender Example

Here's a simple content script that sends a message to the background service worker when the page is clicked. Imagine tracking user interactions!

/* content.js */

document.addEventListener('click', () => {
  chrome.runtime.sendMessage({
    action: "userClicked",
    data: "The document was clicked!"
  });
  console.log("Message sent from content script.");
});

BG to CS: Receiving Messages

In your background service worker, you need to set up a listener to receive messages from content scripts (or other parts of your extension). You use chrome.runtime.onMessage.addListener() for this.

The listener function receives the message itself, sender info, and a sendResponse function (which we won't use for one-way).

Background Listener Example

This background script listens for messages. When it receives a message with action: "userClicked", it logs the data.

/* background.js */

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "userClicked") {
    console.log("Received from content script:", message.data);
    // No sendResponse() for one-way communication
  }
});

BG to CS: Sending Messages

Now, let's look at sending a message from your background service worker to a content script. This is slightly different because you need to specify *which* tab's content script should receive the message.

You use chrome.tabs.sendMessage(tabId, message), where tabId identifies the target tab.

Background Sender Example

This example shows a background script sending a message to the active tab's content script when the extension's icon is clicked. The message tells the content script to change the page's background.

/* background.js (continued) */

chrome.action.onClicked.addListener((tab) => {
  // Send a message to the content script in the clicked tab
  chrome.tabs.sendMessage(tab.id, {
    action: "changeBackground",
    color: "#E0FFFF" // Light Cyan
  });
  console.log("Message sent to content script in tab:", tab.id);
});

CS to BG: Receiving Messages

Just like background scripts, content scripts also use chrome.runtime.onMessage.addListener() to listen for incoming messages.

When a background script sends a message using chrome.tabs.sendMessage() to a specific tab, only the content scripts injected into that tab will receive it.

Content Script Receiver Example

This content script snippet listens for the "changeBackground" action and updates the body's background color. This allows your background script to control aspects of the webpage.

/* content.js (continued) */

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "changeBackground") {
    document.body.style.backgroundColor = message.color;
    console.log("Page background changed to:", message.color);
  }
});

Check Your Understanding

Which of the following are key components or methods used for one-way message passing between a content script and a background service worker?

Recap: One-Way Messaging

Great job! You've learned the fundamentals of one-way messaging in browser extensions.

  • Isolated Environments: Extension components operate independently.
  • chrome.runtime.sendMessage(): Used to send messages from content scripts to background or other parts.
  • chrome.tabs.sendMessage(): Used by background scripts to send messages to specific content scripts.
  • chrome.runtime.onMessage.addListener(): Used by both content scripts and background scripts to listen for incoming messages.

This is a crucial skill for building interactive and robust extensions!

よくある質問

「一方向メッセージングパターン」レッスンは無料ですか?

はい。「一方向メッセージングパターン」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Browser Extensions Development (Chrome & Edge)コースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Browser Extensions Development (Chrome & Edge)コースには全4レッスンが含まれています。

「一方向メッセージングパターン」で何を学びますか?

コンテンツスクリプトとバックグラウンドサービスワーカー間で、またはその逆方向に、シンプルな一方向通信を実装します。 ブラウザで直接実行するハンズオンコードでBrowser Extensions Development (Chrome & Edge)を演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Browser Extensions Development (Chrome & Edge)を始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのBrowser Extensions Development (Chrome & Edge)は初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「一方向メッセージングパターン」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このBrowser Extensions Development (Chrome & Edge)レッスンでコードを書いて実行できますか?

はい。すべてのBrowser Extensions Development (Chrome & Edge)レッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. 一方向メッセージングパターン
  2. コンポーネント間の双方向メッセージング
  3. Chrome Storage APIの利用
  4. SyncとLocalストレージ、クォータ
← Browser Extensions Development (Chrome & Edge)に戻る