Skip to content

content_scripts in Chrome Extensions

Content Scripts are JavaScript files that run in the context of web pages, allowing a Chrome Extension to read and modify the DOM of the pages the user visits^[600-developer__frontend__google__chrome-plugin-develop.md].

Unlike the extension's background scripts or popup scripts, which run in the extension's own isolated process, content scripts are injected into the specific web pages matching defined patterns^[600-developer__frontend__google__chrome-plugin-develop.md].

Configuration

Content scripts are declared in the manifest.json file under the content_scripts key^[600-developer__frontend__google__chrome-plugin-develop.md].

Matching Patterns

The matches property specifies which URLs the script should be injected into^[600-developer__frontend__google__chrome-plugin-develop.md]. This property accepts an array of patterns. For example: * "http://*/*": Matches all HTTP pages. * "https://*/*": Matches all HTTPS pages^[600-developer__frontend__google__chrome-plugin-develop.md].

Script Injection

The js property lists the JavaScript files to be loaded^[600-developer__frontend__google__chrome-plugin-develop.md]. These files are loaded in the order specified. It is common to import libraries (such as jQuery) to facilitate DOM manipulation within the target page^[600-developer__frontend__google__chrome-plugin-develop.md].

Example Configuration

"content_scripts": [{
  "matches": [
    "http://*/*", 
    "https://*/*"
  ],
  "js": [
    "jquery.1.8.3.min.js"
  ]
}]
^[600-developer__frontend__google__chrome-plugin-develop.md]

Functionality

  • DOM Access: Content scripts can see and modify the DOM of the web page, as well as detect changes via event listeners^[600-developer__frontend__google__chrome-plugin-develop.md].
  • Library Usage: The scope of the content script is the current web page, not the extension's popup. Therefore, any libraries (like jQuery) included in the js array will be available for use on the current page^[600-developer__frontend__google__chrome-plugin-develop.md].
  • [[Chrome Extension]]
  • [[manifest.json]]
  • [[DOM Manipulation]]

Sources

  • 600-developer__frontend__google__chrome-plugin-develop.md