Back to Content

contentScripts.register()

files/en-us/mozilla/add-ons/webextensions/api/contentscripts/register/index.md

latest5.8 KB
Original Source

Use this function to register one or more content scripts.

It accepts one parameter, which is an object with similar properties to the objects given in the content_scripts manifest key (but note that content_scripts is an array of objects, while the argument to register() is one object).

The extension must have the appropriate host permissions for the patterns in contentScriptOptions, or the API call is rejected.

Syntax

js-nolint
let registering = browser.contentScripts.register(
  contentScriptOptions       // object
)

Parameters

  • contentScriptOptions
    • : object. A RegisteredContentScriptOptions object representing the content scripts to register. It has similar syntax to the objects in the content_scripts manifest key array. The differences are:

      • property names use {{Glossary("camel_case", "camel case")}}, rather than underscores ({{Glossary("snake_case", "snake case")}}) — for example, excludeMatches, not exclude_matches.
      • the js and css properties allow you to register strings as well as URLs, so their syntax has to distinguish these types.

      The RegisteredContentScriptOptions object has these properties:

Return value

A Promise that will be fulfilled with a {{WebExtAPIRef("contentScripts.RegisteredContentScript")}} object that you can use to unregister the content scripts.

Currently, content scripts are unregistered when the related extension page (from which the content scripts were registered) is unloaded, so you should register a content script from an extension page that persists at least as long as you want the content scripts to stay registered.

Examples

This example registers the defaultCode content script for all .org URLs:

js
const defaultHosts = "*://*.org/*";
const defaultCode =
  "document.body.innerHTML = '<h1>This page has been eaten<h1>'";

async function register(hosts, code) {
  return await browser.contentScripts.register({
    matches: [hosts],
    js: [{ code }],
    runAt: "document_idle",
  });
}

let registered = register(defaultHosts, defaultCode);

This code registers the JS file at content_scripts/example.js:

js
const scriptObj = await browser.contentScripts.register({
  js: [{ file: "/content_scripts/example.js" }],
  matches: ["<all_urls>"],
  allFrames: true,
  runAt: "document_start",
});

{{WebExtExamples}}

Browser compatibility

{{Compat}}