What Is a Content Script in Chrome Extensions and How It Works
Patrick Bushe
January 8, 2025 · 5 min read
A content script is JavaScript (and optionally CSS) that a Chrome extension runs inside the web pages you visit. It's how extensions change what you see on a site: darkening pages, hiding elements, adding buttons or reading text.
What a content script can do
- Read and change the page's content, layout and styles.
- Listen for clicks, scrolling and key presses on the page.
- Use a few extension features directly, such as storage and messaging.
- Send messages to the extension's background service worker, which can use the rest of Chrome's extension features.
Declaring one in the manifest
"content_scripts": [{
"matches": ["https://*.example.com/*"],
"js": ["content.js"],
"css": ["content.css"],
"run_at": "document_idle"
}]
- matches sets which sites it runs on.
<all_urls>means every site. - run_at sets when:
document_start(before the page builds),document_endordocument_idle(the default, after the page loads). - all_frames runs it inside frames as well.
Extensions can also inject scripts only when needed with chrome.scripting.executeScript, for example when you click the toolbar button.
The isolated world
Content scripts share the page's content but not its JavaScript. The page can't see the script's variables, and the script can't directly call the page's functions. This protects both sides. In Manifest V3, a script can opt into the page's own environment with "world": "MAIN" when it truly needs to.
Talking to the rest of the extension
Content scripts use chrome.runtime.sendMessage to ask the service worker to do things they can't, such as opening tabs, and the service worker replies. Extensions should treat messages from content scripts carefully, because a malicious page can tamper with what the script sees.
Real examples
- Modern Dark Mode uses a content script to apply a dark filter to each page and flip images back.
- Cookie Auto-Reject runs from the start of page load in every frame, so it can click "Reject all" as soon as a banner appears.
- Color Palette Extractor reads the colors used by elements on the page.
Permissions and trust
A content script that runs on all sites is why Chrome warns that an extension can "read and change all your data on all websites". It's normal for tools that work everywhere, but only install such extensions from developers you trust. See extension permissions explained.
Build your own
See building a Manifest V3 extension and what Manifest V3 changed.