Content scripts

Send a message to the content script

Pass a small structured command from the popup to the page context and validate it before changing the DOM.

8 minute lesson

~~~

The popup and content script cannot call each other’s functions. Messaging crosses that context boundary.

Send a message to the active tab after ensuring the content script exists. The receiver should accept only known message types and validate every field, because messages are another input boundary.

One-time messages are JSON-serialized in Chrome. Send plain data, not functions, DOM nodes, class instances, or objects whose meaning depends on prototypes. Keep payloads small and return an explicit result so the sender can distinguish “shown” from “no listener,” “invalid note,” or “restricted page.”

await chrome.tabs.sendMessage(tab.id, {
  type: 'SHOW_PAGE_NOTE',
  note
})

tabs.sendMessage can reject when no matching content script exists—for example after the extension was reloaded but the tab was not. Page Notes can inject first and then send, or treat a missing receiver as an initialization signal, but it must not blindly inject after every error.

Handle SHOW_PAGE_NOTE with a type guard and return { ok: true }. Send an unknown type, a non-string note, and a message immediately after an extension reload. The page must remain unchanged on invalid input and the popup must show a useful recovery path.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →