Content Scripts in Chrome Extensions: The Practical Guide
Content scripts run in the page — but in their own world. Here's how to read the DOM, inject UI, and talk to your service worker.
Content scripts are the part of a Chrome extension that runs inside a web page. They can read and modify the DOM — but they live in an isolated JavaScript world, separate from the page's own scripts.
What content scripts can and can't do
- Can: read the DOM, modify it, inject UI elements, listen to events.
- Can't: access the page's JavaScript variables directly.
- Can't: use most `chrome.*` APIs — only `chrome.runtime` and `chrome.storage`.
- Can: send messages to the service worker for anything else.
The message-passing pattern
When a content script needs something only the service worker can do — calling an external API, opening a new tab, reading `chrome.tabs` — it uses `chrome.runtime.sendMessage`. The service worker listens via `chrome.runtime.onMessage.addListener` and responds asynchronously.
Injecting UI cleanly
Use Shadow DOM for any UI you inject. It isolates your CSS from the host page so your overlay isn't broken by site-specific styles, and your styles don't leak into the page.