docs.rodeo

MDN Web Docs mirror

tabs.insertCSS()

{{AddonSidebar}} 

Injects CSS into a page.

[!NOTE] When using Manifest V3 or higher, use {{WebExtAPIRef("scripting.insertCSS()")}}  and {{WebExtAPIRef("scripting.removeCSS()")}}  to insert and remove CSS.

To use this API you must have the permission for the page’s URL, either explicitly as a host permission, or using the activeTab permission.

You can only inject CSS into pages whose URL can be expressed using a match pattern: meaning, its scheme must be one of “http”, “https”, or “file”. This means that you can’t inject CSS into any of the browser’s built-in pages, such as about:debugging, about:addons, or the page that opens when you open a new empty tab.

[!NOTE] Firefox resolves URLs in injected CSS files relative to the CSS file itself, rather than to the page it’s injected into.

The inserted CSS may be removed again by calling {{WebExtAPIRef("tabs.removeCSS()")}} .

This is an asynchronous function that returns a Promise (on Firefox only).

Syntax

let inserting = browser.tabs.insertCSS(
  tabId,           // optional integer
  details          // object
)

Parameters

Return value

A Promise that will be fulfilled with no arguments when all the CSS has been inserted. If any error occurs, the promise will be rejected with an error message.

Examples

This example inserts into the currently active tab CSS which is taken from a string.

let css = "body { border: 20px dotted pink; }";

browser.browserAction.onClicked.addListener(() => {
  function onError(error) {
    console.log(`Error: ${error}`);
  }

  let insertingCSS = browser.tabs.insertCSS({ code: css });
  insertingCSS.then(null, onError);
});

This example inserts CSS which is loaded from a file packaged with the extension. The CSS is inserted into the tab whose ID is 2:

browser.browserAction.onClicked.addListener(() => {
  function onError(error) {
    console.log(`Error: ${error}`);
  }

  let insertingCSS = browser.tabs.insertCSS(2, { file: "content-style.css" });
  insertingCSS.then(null, onError);
});

{{WebExtExamples}} 

Browser compatibility

{{Compat}} 

[!NOTE] This API is based on Chromium’s chrome.tabs API. This documentation is derived from tabs.json in the Chromium code.

In this article

View on MDN