Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 36 ยท Popup, Options and Content Scripts

Content Scripts Basics

Learn how content scripts work: declare them in the manifest, choose run_at, read and edit the page DOM, add CSS, watch for changes with MutationObserver and use allowed APIs.

A content script is JavaScript that Chrome injects into web pages so your extension can read and change them. It is how an extension highlights words, hides clutter, adds a "Save" button next to every product or counts links. If the popup is your extension's face, the content script is its hands inside someone else's page.

Declare a content script

The simplest way is statically, in the manifest:

JSON
"content_scripts": [
  {
    "matches": ["https://*.example.com/*"],
    "js": ["content.js"],
    "css": ["content.css"],
    "run_at": "document_idle"
  }
]

Chrome injects the listed files into every frame that matches, each time such a page loads. js files run in the order listed, so a library goes first and your code second (if you use one).

run_at

Value Injected Use for
document_start Before the page builds its DOM Setting CSS early to avoid a flash
document_end When the DOM is parsed (like DOMContentLoaded) Reading the static HTML
document_idle (default) After the DOM is ready, around load Almost everything

With document_idle you can assume document.body exists. With document_start it may not.

What a content script can touch

  • The DOM of the page: read it, change it, add nodes, listen to events.
  • The page's layout and styles (getComputedStyle).
  • A few extension APIs: chrome.runtime (messaging and getURL), chrome.storage, chrome.i18n, chrome.dom.
  • fetch, but with the page's origin rules (CORS applies as if the page made the request). To call other servers without those limits, ask the service worker to do it.

It cannot call chrome.tabs, chrome.alarms and most others; send a message to the service worker instead.

flowchart LR
    subgraph Page["Tab: example.com"]
        D["DOM"]
        PS["Page scripts"]
        CS["Content script<br/>(isolated world)"]
    end
    CS -->|read / edit| D
    PS -->|read / edit| D
    CS -->|chrome.runtime.sendMessage| SW["Service worker"]

The content script and the page share the DOM but not JavaScript variables.

A real content script

This content.js finds every link that leaves the current site and adds a small marker:

JavaScript
const here = location.hostname;
for (const link of document.querySelectorAll("a[href]")) {
  if (link.hostname && link.hostname !== here) {
    link.insertAdjacentText("beforeend", " โ†—");
    link.dataset.external = "true";
  }
}

and content.css styles them, so you can restyle without touching the DOM:

CSS
a[data-external="true"] { text-decoration: underline dotted; }

Try the logic

The page below is a stand-in. The button runs the exact content.js logic on a pretend page (location.hostname is replaced by a variable).

Mark external links

Notice !link.dataset.external: pressing the button twice does not double the arrows. Content scripts often run more than once, so make them idempotent.

Pages that change after load

Modern sites render content with JavaScript long after document_idle. A script that runs once misses everything added later. Use a MutationObserver:

JavaScript
function process(root) { /* mark links, add buttons... */ }

process(document);

new MutationObserver((mutations) => {
  for (const m of mutations) {
    for (const node of m.addedNodes) {
      if (node.nodeType === Node.ELEMENT_NODE) process(node);
    }
  }
}).observe(document.body, { childList: true, subtree: true });

Process only the new nodes, not the whole document each time, or the page slows down.

MutationObserver on a live list

Single-page apps and URL changes

Content scripts are injected on page loads. Single-page apps change the URL without a load, so matches only runs once. Observe the DOM, or have the service worker listen for chrome.webNavigation.onHistoryStateUpdated and message the content script.

Good citizenship

  • Keep it small. A content script runs on every matching page: parse cost counts.
  • Namespace what you add. Prefix classes and IDs (my-ext-badge) to avoid clashing with the page.
  • Do not trust the page. Anything you read from the DOM is untrusted text. Use textContent, not innerHTML, when you insert it back.
  • Do one thing per run. Remove listeners and observers you create if the feature is turned off.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Which run_at value is the default?

    Content scripts run at document_idle by default, after the DOM is ready.
  2. 2. Which API can a content script NOT call directly?

    Content scripts have a very limited API set. Anything involving tabs must go through the service worker.
  3. 3. Why use a MutationObserver in a content script?

    Many sites render content dynamically; an observer lets your script react to new nodes.

Summary

  • Static content scripts are declared in content_scripts with matches, js, css and run_at.
  • They share the page's DOM but have only a few chrome.* APIs.
  • Make scripts idempotent and use a MutationObserver for dynamic pages.
  • Single-page apps need extra handling because injection happens on page loads.
  • Treat page data as untrusted and namespace everything you add.

Next: The Isolated World