Skip to content

content_scripts Chrome Extension Scripts

Content Scripts are JavaScript files that run in the context of web pages, allowing a Chrome Extension to manipulate the Document Object Model (DOM) and content of specific sites the user visits^[600-developer__frontend__google__chrome-plugin-develop.md].

Configuration

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

To specify where the scripts should run, use the matches property to list URL patterns (e.g., http://*/*, https://*/*)^[600-developer__frontend__google__chrome-plugin-develop.md]. The actual JavaScript files to be injected are listed in the js array^[600-developer__frontend__google__chrome-plugin-develop.md]. This configuration allows developers to import external libraries, such as jQuery, to be utilized within the target page's context^[600-developer__frontend__google__chrome-plugin-develop.md].

"content_scripts": [{
  "matches": [ "http://*/*", "https://*/*" ],
  "js": [ "jquery.1.8.3.min.js" ]
}]

Execution Context

Unlike scripts loaded in the extension's [[popup-pages|popup.html]], content scripts execute within the "current page" the user is viewing^[600-developer__frontend__google__chrome-plugin-develop.md]. This allows them to read and modify page elements directly.

Interaction

Extensions can interact with content scripts programmatically using the chrome.tabs.executeScript method^[600-developer__frontend__google__chrome-plugin-develop.md]. This function, typically called from the popup or background scripts, accepts a tabId and a code object containing a code string to be executed in the context of the specified tab^[600-developer__frontend__google__chrome-plugin-develop.md]. This is commonly used to autofill forms or trigger actions on web pages.

Sources