Icon not found

Content Scripts

Content scripts are JavaScript files that run in the context of web pages. In Extension.js, these scripts are essential for interacting with web pages, modifying their content, and accessing page elements. Content scripts allow your extension to add custom functionality to specific pages or web applications.

How It Works?

Extension.js manages content scripts by performing the following actions:

  1. Process Script Files: All JavaScript and CSS files declared in the content_scripts field of the manifest.json are compiled, bundled, and emitted.
  2. Inject CSS for Hot-Module Replacement (HMR): During development, Extension.js injects CSS files dynamically to support HMR, ensuring seamless updates without a full page reload.
  3. Maintain Isolation: Content scripts operate in an isolated environment, ensuring no direct access to the page’s JavaScript context.

Content Scripts Support

The following fields in the manifest.json are used for declaring content scripts and related resources:

Manifest Field File Type Expected HMR Support
content_scripts.js .js, .ts, .mjs, .tsx Yes
content_scripts.css .css, .scss, .less, .sass Yes

Sample Content Script Declaration

Below is an example of how to declare content scripts within the manifest.json file:

{
  "manifest_version": 3,
  "name": "My Extension",
  "version": "1.0",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["./scripts/content-script.js"],
      "css": ["./styles/content-style.css"]
    }
  ]
}

This configuration specifies that the content-script.js JavaScript file and content-style.css CSS file should run on all web pages.

Handling Additional Content Scripts

To include additional content scripts outside the manifest.json, place them in the /scripts folder. This approach allows you to modularize your scripts for better code organization.

Example Usage:

scripts/
└── extra-content-script.js

Output Path

Content scripts are output to the following directory:

dist/
  [browser]/
  ├── content_scripts/
  │   └── content-script.js
  │   └── extra-content-script.js
  └── other-extension-files

Best Practices

  • Minimize Content Scripts: Limit the size and complexity of content scripts to improve performance.
  • Modularize Code: Use the /scripts folder to keep content scripts organized and modular.
  • Leverage HMR During Development: Take advantage of HMR to test CSS changes dynamically without reloading the page.

Next Steps