Back to Content

scripting.registerContentScripts()

files/en-us/mozilla/add-ons/webextensions/api/scripting/registercontentscripts/index.md

latest1.7 KB
Original Source

Registers one or more content scripts.

[!NOTE] This method is available in Manifest V3 or higher in Chrome and Firefox 101. In Firefox 102+, this method is also available in Manifest V2.

To call this API, you must have the "scripting" permission. To run the injected script, the extension must have permission for the page's URL, either explicitly as a host permission or using the activeTab permission.

Syntax

js-nolint
await browser.scripting.registerContentScripts(
  scripts         // array
)

Parameters

  • scripts
    • : array of {{WebExtAPIRef("scripting.RegisteredContentScript")}}. A list of scripts to register.

Return value

A Promise fulfilled with no arguments or rejected when there are errors. Errors can occur during script parsing and file validation or if the IDs specified exist. When an error occurs, no scripts are registered.

Examples

This example registers a content script that injects the file "script.js":

js
const script = {
  id: "a-script",
  js: ["script.js"],
  matches: ["https://example.com/*"],
};

try {
  await browser.scripting.registerContentScripts([script]);
} catch (err) {
  console.error(`failed to register content scripts: ${err}`);
}

{{WebExtExamples}}

Browser compatibility

{{Compat}}

[!NOTE] This API is based on Chromium's chrome.scripting API.