Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 36 ยท Messaging and Storage

Long-Lived Connections with Ports

Open long-lived channels between extension parts with runtime.connect and onConnect, stream many messages over one port, handle disconnects, and know when ports are better than one-time messages.

A one-time message is like sending a letter: one question, one answer. When two parts of your extension need to chat for a while (a live log, a progress bar, a stream of updates), opening a new letter each time is wasteful. A port is a phone call: you connect once, both sides can talk whenever they like, and either side finds out when the other hangs up.

Opening and accepting a port

One side calls connect, the other listens with onConnect. Both ends get a Port object with postMessage, onMessage and onDisconnect.

JavaScript
// content script or popup (real extension code)
const port = chrome.runtime.connect({ name: "progress" });
port.postMessage({ type: "start", total: 5 });
port.onMessage.addListener((msg) => console.log("update:", msg));
port.onDisconnect.addListener(() => console.log("worker went away"));
JavaScript
// service-worker.js (real extension code)
chrome.runtime.onConnect.addListener((port) => {
  if (port.name !== "progress") return;
  port.onMessage.addListener((msg) => {
    if (msg.type === "start") {
      for (let i = 1; i <= msg.total; i++) port.postMessage({ done: i });
    }
  });
});

The name lets one extension keep several kinds of port apart: the listener checks it and ignores ports it does not own. To reach a tab's content script, the worker or popup uses chrome.tabs.connect(tabId, { name }), and the content script listens with the same runtime.onConnect.

A port stand-in: two ends of one connection

Handling disconnects

A port closes when:

  • either side calls port.disconnect();
  • the page that owns one end is closed or navigated away (a popup closing disconnects its ports);
  • the service worker stops after a few seconds of being idle (but an open port that is receiving messages counts as activity in recent Chrome versions).

Always register onDisconnect. It is where you release resources, update the UI or reconnect. A very common pattern is a content script that reconnects when the worker restarts:

JavaScript
function connect() {
  const port = chrome.runtime.connect({ name: "live" });
  port.onDisconnect.addListener(() => {
    // chrome.runtime.lastError tells you why, if it was an error
    setTimeout(connect, 1000);
  });
  return port;
}

If the extension is updated or reloaded while a tab is open, the old content script becomes an orphan: chrome.runtime calls then throw "Extension context invalidated". Wrap long-lived content scripts in try/catch and stop their work when that error appears.

Ports versus one-time messages

One-time message

One question Ask once, get one answer
Simple No state to manage
Best for Commands and lookups
1 / 2

Prefer one-time messages for most things; they are easier to reason about and to test. Reach for a port when you have a stream, or when you need to know that the other side is still alive.

Broadcasting to several listeners

Each connect creates a separate port, so the worker can hold several at once (one per tab). Keep them in a Set and remove each one in onDisconnect:

JavaScript
const ports = new Set();
chrome.runtime.onConnect.addListener((port) => {
  ports.add(port);
  port.onDisconnect.addListener(() => ports.delete(port));
});
function broadcast(message) {
  for (const p of ports) p.postMessage(message);
}

Remember that the worker can be stopped and restarted: a Set in memory is lost. Content scripts that reconnect (as above) rebuild it. Do not keep anything important only in worker memory; see Storage patterns.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which method accepts an incoming port in the service worker?

    runtime.onConnect fires when another part calls runtime.connect or tabs.connect.
  2. 2. What is the main reason for the name option of runtime.connect?

    An extension may open several ports for different purposes. The listener checks port.name and ignores the ones it does not own.
  3. 3. A popup is closed while it has an open port to the worker. What does the worker see?

    Closing the page closes its ports, and the other end receives onDisconnect so it can clean up.
  4. 4. When are ports a better choice than sendMessage?

    Ports keep one channel open for many messages and report disconnects. One-off requests are simpler with sendMessage.

Summary

  • A port is a long-lived two-way channel created by runtime.connect or tabs.connect and accepted by runtime.onConnect.
  • Name ports so listeners can ignore ones they do not own.
  • Always handle onDisconnect; reconnect or clean up there.
  • Keep a Set of ports to broadcast, but do not rely on worker memory surviving.
  • Prefer one-time messages unless you really have a stream.

Next: The Storage API