Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท Popup, Options and Content Scripts

Injecting Scripts Programmatically

Inject scripts and CSS on demand with chrome.scripting.executeScript and insertCSS, pass arguments, read results, use activeTab, and register dynamic content scripts.

Static content_scripts run on every page that matches, whether the user wants them or not. Often you want the opposite: run code only when the user clicks, on the tab they are looking at, with arguments you choose. That is what the chrome.scripting API is for.

Permissions

JSON
{
  "permissions": ["scripting", "activeTab"]
}
  • scripting allows the API.
  • activeTab gives temporary access to the current tab after a user gesture (clicking the toolbar icon, a context-menu item or a keyboard shortcut) with no host permission and no install warning. It ends when the tab navigates or closes.

Without activeTab you would need host_permissions for the sites you touch. That is the main reason to prefer it.

executeScript

Run a function in a tab:

JavaScript
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

const results = await chrome.scripting.executeScript({
  target: { tabId: tab.id },
  func: () => document.title,
});

console.log(results[0].result); // the page's title

Key points:

  • target selects the tab (and optionally frameIds or allFrames: true).
  • func is serialized and sent to the page, so it cannot use variables from the surrounding scope. It is a stand-alone function.
  • The return value must be JSON-serializable. You get one result per frame, each as { frameId, result }. A returned promise is awaited.
  • Add args to pass data in:
JavaScript
await chrome.scripting.executeScript({
  target: { tabId: tab.id },
  func: (word, color) => {
    for (const el of document.querySelectorAll("p")) {
      if (el.textContent.includes(word)) el.style.background = color;
    }
  },
  args: ["Chrome", "gold"],
});

To run a file instead of a function, use files:

JavaScript
await chrome.scripting.executeScript({
  target: { tabId: tab.id },
  files: ["content/highlight.js"],
});

By default the code runs in the isolated world. Add world: "MAIN" to run beside the page's own scripts (see the previous lesson).

insertCSS and removeCSS

JavaScript
await chrome.scripting.insertCSS({
  target: { tabId: tab.id },
  css: "body { filter: grayscale(1); }",
});

await chrome.scripting.removeCSS({
  target: { tabId: tab.id },
  css: "body { filter: grayscale(1); }",
});

removeCSS needs the same text (or file) you inserted. That makes it ideal for toggles.

sequenceDiagram
    participant U as User
    participant SW as Popup / worker
    participant T as Tab
    U->>SW: Click icon (activeTab granted)
    SW->>T: scripting.executeScript(func, args)
    T-->>SW: [{ frameId: 0, result }]
    SW->>U: Show the result

Code goes out as a function; a result comes back.

A stand-in for executeScript

func is serialized. That detail causes the most confusion, so let us model it. The stand-in converts the function to a string and rebuilds it in a different scope, which is how Chrome transports it. The outer variable is not visible after the move.

JS Why func cannot use outer variables

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A highlighter, end to end

This stand-in has a popup with a word field and a "Highlight" button, and a fake page. The function passed to fakeExecute is exactly the kind of func you would give to executeScript: self-contained, with its inputs passed as args.

Highlight a word on the page

(In a real extension this would use textContent on text nodes rather than innerHTML for safety, a point the security chapter takes up.)

Dynamic content script registration

Sometimes you want a script to run on every future page load for sites the user chooses later. Register content scripts at runtime:

JavaScript
await chrome.scripting.registerContentScripts([
  {
    id: "dark-mode",
    matches: ["https://*.example.com/*"],
    js: ["dark.js"],
    runAt: "document_start",
    persistAcrossSessions: true,
  },
]);

await chrome.scripting.unregisterContentScripts({ ids: ["dark-mode"] });

Note runAt here is camelCase, while in the manifest it is run_at. You need host_permissions for the match patterns (activeTab does not apply).

Where you cannot inject

Chrome blocks injection into chrome:// pages, the Chrome Web Store, other extensions' pages and (without the right permission) file:// URLs. Calling executeScript there throws an error such as Cannot access a chrome:// URL. Catch it and tell the user instead of failing silently:

JavaScript
try {
  await chrome.scripting.executeScript({ target: { tabId }, func });
} catch (error) {
  statusEl.textContent = "This page cannot be changed by extensions.";
}

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Why can the func passed to executeScript not use variables from the popup?

    Only the function's source travels to the page. Pass values through args instead.
  2. 2. What does the activeTab permission give you?

    activeTab grants access to the tab the user just interacted with, until it navigates or closes, without a host permission.
  3. 3. Which call removes CSS you added earlier?

    scripting.removeCSS removes CSS previously added by scripting.insertCSS (use the same css or files).

Summary

  • Use chrome.scripting to inject on demand; activeTab avoids broad host permissions.
  • executeScript takes a self-contained func and args, or files, and returns one result per frame.
  • insertCSS and removeCSS toggle styles.
  • registerContentScripts creates dynamic static-style scripts at runtime.
  • Some pages cannot be scripted; handle the error.

Next: Service Worker Basics