Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 36 ยท Messaging and Storage

One-Time Messages with runtime.sendMessage

Send one-time messages between the popup, content scripts and the service worker with chrome.runtime.sendMessage and tabs.sendMessage, reply asynchronously, and avoid the classic port-closed error.

An extension is not one program. It is several isolated pieces: the service worker, the popup, the options page and a content script in every tab. None of them share variables. The only way they talk to each other is by passing messages, and the simplest kind is the one-time message: one piece asks, another answers once.

In this lesson you learn the two send functions, the receiving listener, how to reply (including asynchronously), and the bug that bites almost every beginner: a reply that never arrives. The Chrome APIs only exist inside a real extension, so the live examples use a small hand-written stand-in for chrome.runtime. It follows the same rules as the real one, and the real code is shown beside it.

Who sends to whom

There are two directions:

  • chrome.runtime.sendMessage(message) sends to the extension's own pages and its service worker. Use it from a content script, popup or options page.
  • chrome.tabs.sendMessage(tabId, message) sends to the content scripts in one tab. Use it from the service worker or popup. A content script cannot send to another tab directly.
flowchart LR
    CS["Content script<br/>(in a web page)"] -- "runtime.sendMessage" --> SW["Service worker"]
    P["Popup"] -- "runtime.sendMessage" --> SW
    SW -- "tabs.sendMessage(tabId)" --> CS
    P -- "tabs.sendMessage(tabId)" --> CS

Messages flow through the runtime. A tab is addressed by its id.

Receiving and replying

The receiver registers a listener. It gets the message, a sender object describing who sent it, and a sendResponse function.

JavaScript
// service-worker.js (real extension code)
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === "greet") {
    sendResponse({ reply: `Hello, ${message.name}!` });
  }
});
JavaScript
// popup.js (real extension code)
const response = await chrome.runtime.sendMessage({ type: "greet", name: "Ada" });
console.log(response.reply);

In Manifest V3 the promise form (await chrome.runtime.sendMessage(...)) works, so you do not need callbacks. The message can be any value that survives JSON-style cloning: objects, arrays, strings, numbers. Functions, DOM nodes and class instances do not survive.

A runtime.sendMessage stand-in

A message nobody answers resolves with undefined. That is why every message should carry a type field: a listener checks the type, ignores messages it does not know and lets another listener respond.

Replying asynchronously

The most common bug: the listener must answer synchronously, unless it returns true. Real Chrome closes the reply channel as soon as the listener function returns. If you call sendResponse later (after a fetch or a storage read), the sender sees "The message port closed before a response was received."

The fix is to return true. That tells Chrome the reply will come later.

JavaScript
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === "load-count") {
    chrome.storage.local.get("count").then(({ count = 0 }) => {
      sendResponse({ count });
    });
    return true; // keep the channel open
  }
});

An async listener function is a trap: it returns a Promise, not true, so the channel closes. Either return true and call sendResponse inside, or wrap the work in a normal function.

Why return true matters

Reading the sender

The sender argument tells you where a message came from: sender.tab is set when it came from a content script (with tab.id and tab.url), and sender.id is the extension id. Use it to answer the right tab, and use it to check trust (see Secure messaging).

JavaScript
chrome.runtime.onMessage.addListener((message, sender) => {
  if (message.type === "page-title" && sender.tab) {
    console.log(`Tab ${sender.tab.id} says: ${message.title}`);
  }
});

Common mistakes

  • Sending to a tab that has no content script. tabs.sendMessage then fails with "Receiving end does not exist". Inject the script first or catch the error.
  • Sending a message from the service worker before it has a listener on the other side.
  • Registering the listener inside an async function or an event handler. In a service worker, register listeners at the top level so they exist when the worker wakes.
  • Forgetting that every listener in the same context receives every message. Filter by type.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call sends a message from the service worker to the content script in one tab?

    chrome.tabs.sendMessage addresses the content scripts of one tab by its id. runtime.sendMessage goes to the extension's own pages and worker.
  2. 2. A listener calls sendResponse after an awaited fetch, but the sender gets a port-closed error. What is missing?

    Returning true keeps the reply channel open. An async function returns a Promise instead, which does not keep it open.
  3. 3. What does the sender object tell the receiver?

    sender.tab is set for content scripts and sender.id is the extension id. Use both to reply and to validate.
  4. 4. What happens to a message that no listener answers?

    Unanswered messages resolve with undefined, which is why a type field and explicit replies are good practice.

Summary

  • Extension parts are isolated; they cooperate by passing messages.
  • runtime.sendMessage reaches the worker and extension pages; tabs.sendMessage(tabId, ...) reaches a tab's content scripts.
  • A listener receives (message, sender, sendResponse); reply synchronously or return true and reply later.
  • Give every message a type and ignore types you do not handle.
  • Register listeners at the top level of the service worker.

Next: Long-Lived Connections with Ports