Skip to content
AnswerWell geo Documentation

Research · 8 min read · Answerwell

Content Script Injection, Manifest Registration, and Execution Worlds

How browser extensions inject content scripts via the manifest, Scripting API, and User Scripts API—with permissions, timing, and isolated worlds.

This page summarises Chrome Extensions documentation on content scripts: JavaScript and CSS that run in the context of web pages, read and change the DOM, and talk to the parent extension. Most injection in Manifest V3 uses the browser.scripting API (or chrome.scripting); older extensions used chrome.tabs.executeScript(), which is deprecated in favour of scripting.executeScript().

Content scripts are files (or injected code) that execute while a page is loaded. They use the standard Document Object Model to read page details, modify the page, and pass information to the extension.

Content scripts are files that run in the context of web pages. Using the standard Document Object Model (DOM), they are able to read details of the web pages the browser visits, make changes to them, and pass information to their parent extension.

— Chrome, Content scripts

Extensions that change pages often pair a content script with UI such as the extension action (toolbar button). The action API documents a common pattern: on click, inject a script that proves injection worked (for example with an alert).

Isolated worlds: why page JavaScript cannot see extension variables

Section titled “Isolated worlds: why page JavaScript cannot see extension variables”

By default, content scripts run in an isolated world: a private execution environment that the host page and other extensions cannot access.

Content scripts live in an isolated world, allowing a content script to make changes to its JavaScript environment without conflicting with the page or other extensions’ content scripts.

— Chrome, Content scripts — Work in isolated worlds

The same button on a page can therefore fire two click handlers—one from the page script and one from the content script—without sharing variables like greeting. Neither the page, nor other extensions, nor other content scripts can read each other’s JavaScript contexts.

world value Where it runs Typical use
ISOLATED (default) Extension-private world Normal content scripts
MAIN Same world as the page’s scripts Only when you must share the page’s JS environment; the page can interfere
USER_SCRIPT User Scripts API world User-supplied snippets via browser.userScripts

The JavaScript world for a script to execute within. Can either be an isolated world unique to this extension, the main world of the DOM which is shared with the page’s JavaScript, or a user scripts world that is only available for scripts registered with the User Scripts API.

— Chrome, ExecutionWorld

Inject scripts lists three approaches. Pick based on whether URLs are known up front and whether injection should be automatic or event-driven.

Method When to use Mechanism
Static declaration Known match patterns; run on every matching navigation "content_scripts" in manifest.json
Dynamic declaration Patterns unknown or rules change at runtime scripting.registerContentScripts()
Programmatic injection User gesture or one-off events scripting.executeScript() / insertCSS()

Content scripts can be declared statically, declared dynamically, or programmatically injected.

— Chrome, Content scripts — Inject scripts

Within one document lifecycle stage, static manifest scripts are injected first, in manifest order, before scripts registered any other way (static declarations).

Manifest content_scripts: automatic injection on URL match

Section titled “Manifest content_scripts: automatic injection on URL match”

The "content_scripts" key loads JavaScript or CSS whenever a page matches a URL pattern. Only matches and either js or css are required.

{
"content_scripts": [
{
"matches": ["https://*.example.com/*"],
"css": ["my-styles.css"],
"js": ["content-script.js"],
"run_at": "document_idle",
"world": "ISOLATED"
}
]
}

CSS paths in the array are injected in order, before DOM construction; JavaScript files run after those CSS injections (Manifest — content scripts).

registerContentScripts: dynamic rules without editing the manifest

Section titled “registerContentScripts: dynamic rules without editing the manifest”

From Chrome 96 onward, dynamic scripts mirror static ones but are registered at runtime via the Scripting API—useful when match patterns are not known at install time or should not persist.

Dynamic content scripts are useful when the match patterns for content scripts are not well known or when content scripts shouldn’t always be injected on known hosts.

— Chrome, Inject with dynamic declarations

You can register, list, update, and remove rules with registerContentScripts(), getRegisteredContentScripts(), updateContentScripts(), and unregisterContentScripts() (browser.scripting).

executeScript and insertCSS: inject when the user acts

Section titled “executeScript and insertCSS: inject when the user acts”

Programmatic injection suits features tied to clicks, messages, or other events. The extension needs host access to the target page: declare host_permissions or use the temporary access from activeTab.

Use programmatic injection for content scripts that need to run in response to events or on specific occasions.

— Chrome, Inject programmatically

Use the chrome.scripting API to execute script in different contexts.

— Chrome, browser.scripting

Required manifest pieces for the Scripting API:

  1. Add "permissions": ["scripting", "activeTab"] (or host_permissions) and a service worker background (activeTab example).

  2. Listen for browser.action.onClicked (or another event) in the service worker.

  3. Call browser.scripting.executeScript({ target: { tabId }, files: ["content-script.js"] }) or pass func and optional args (action — inject on click).

You may inject a file, a function (func is serialized—closures and outer variables are not available; use args for JSON-serializable values), or CSS via insertCSS() with a css string or files (Scripting API). You cannot run arbitrary JS strings with executeScript() the way MV2 code injection often did; migration guidance steers toward func + args (Improve extension security).

Match patterns: which URLs get a content script

Section titled “Match patterns: which URLs get a content script”

Injection happens only when the URL satisfies matches (required) and optional filters.

A page is injected when:

  • Its URL matches any matches and any include_globs, and
  • It does not match exclude_matches or exclude_globs (Exclude matches and globs).

Globs use * and ? with different rules than match patterns. Narrow targets with exclude_matches rather than broad matches plus many excludes—wide patterns slow the browser and widen permission warnings (Reach peak performance).

all_frames, match_about_blank, and match_origin_as_fallback

Section titled “all_frames, match_about_blank, and match_origin_as_fallback”

By default, scripts inject only into the top frame. Set all_frames: true (manifest) or allFrames: true (Scripting API) to run in every frame whose URL still passes match rules (Specify frames).

For about:blank, data:, blob:, and similar frames, use match_about_blank and/or match_origin_as_fallback. With match_origin_as_fallback: true, Chrome uses the initiator frame’s origin instead of the frame URL; manifest patterns must include a path of * (Inject in to related frames).

Programmatic targets require tabId; use allFrames, frameIds, or documentIds, but not allFrames together with frameIds (Injection targets).

runAt and document_idle: when injection runs

Section titled “runAt and document_idle: when injection runs”

The run_at / runAt field controls the earliest injection time. Default and preferred value is document_idle.

Value Meaning
document_start After author CSS, before DOM build and before other scripts
document_end DOM complete; before images/frames finish loading
document_idle Between document_end and after load; optimised for page speed

Content scripts running at “document_idle” don’t need to listen for the window.onload event; they are guaranteed to run after the DOM completes.

— Chrome, RunAt

scripting.executeScript() runs at document_idle by default, or immediately if the page already loaded; injectImmediately tries to run as soon as possible but does not guarantee pre-load injection (executeScript()).

User Scripts API: when users supply the code

Section titled “User Scripts API: when users supply the code”

If the extension must run user-written snippets (typical of user-script managers), use the User Scripts API—not as a replacement for normal executeScript() (Deal with remote hosted code violations).

Unlike other extension features, such as Content Scripts and the browser.scripting API, the User Scripts API lets you run arbitrary code. This API is required for extensions that run scripts provided by the user that cannot be shipped as part of your extension package.

— Chrome, userScripts — Concepts and usage

Requirements include the userScripts permission, host_permissions for target sites, and a user-enabled toggle (Allow User Scripts on Chrome 138+, or Developer mode on older versions) (Enable usage). If the toggle is off, browser.userScripts may be undefined until the extension context reloads.

From Chrome 135, userScripts.execute() supports one-off injection without permanent registration (What’s new).

Manifest V2 migration: tabs.executeScript to scripting.executeScript

Section titled “Manifest V2 migration: tabs.executeScript to scripting.executeScript”

chrome.tabs.executeScript(), insertCSS(), and removeCSS() are deprecated since Chrome 91; Manifest V3 moves them to the Scripting API (tabs.executeScript(), Update your code).

Changes include:

  • Add "scripting" plus host permissions or activeTab.
  • Pass target: { tabId } inside the injection object instead of a separate tabId argument.
  • Use files: ['a.js', 'b.js'] for multiple files.

Host permissions in MV3 live under host_permissions, not inside "permissions" (Update the manifest).

For ad blocking and similar features, filter lists often describe hiding elements, not only blocking network requests. That hiding is done in the page via content scripts and the DOM; remotely fetched rule data is treated as configuration, not remote hosted executable code (Content filtering).

  • Injecting with a broad matches pattern (for example /*) at document_start instead of tight patterns and document_idle (Declare targets).
  • Using func that references service-worker variables without passing them through args (causes ReferenceError in the page) (Inject programmatically).
  • Expecting unregisterContentScripts() to undo DOM or style changes already applied (Scripting API).
  • Putting user-supplied code through generic scripting APIs instead of User Scripts—risk of Chrome Web Store rejection (Remote hosted code).
  • Using the code parameter with untrusted input in injection details (XSS risk in extensions) (InjectDetails).
  • Assuming content scripts can run on chrome:// URLs (they cannot) (FAQ).

Experimental declarativeContent RequestContentScript is not supported on stable Chrome (declarativeContent).

  1. Load your unpacked extension, open a page that matches your content_scripts matches, and confirm the script runs (for example via DevTools Console by selecting the extension’s isolated context when debugging).
  2. For programmatic flows, click the extension action without prior host permission and confirm activeTab grants injection only after user invocation (activeTab).
  3. Try a page with an iframe: verify whether all_frames / allFrames is required for child frames (Specify frames).
  4. If you use the User Scripts API, confirm the user enabled Allow User Scripts (or Developer mode) and that host_permissions cover the test URL (userScripts).
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.