Workflows
/
Content Scripts

Content Scripts

Content scripts run in the context of web pages.

NOTE: Since Plasmo's default Typescript configuration treats all source files as modules, if you don't have any imports or exports in your code, you'll have to add an export {} line at the start of your file. (You will see this warning when creating your first content script!)

Use cases:

Adding a single content script

Create a content.ts file that exports an empty object and hack away! See with-content-script for an example.

Adding multiple content scripts

Create a contents directory for multiple content scripts, and add your content scripts there. See with-many-content-scripts for an example.

Customizing content script config

To provide a custom content script configuration, such as matching a custom domain per script, setting the all_frames key, etc., export a config object from your content script:

import type { PlasmoContentScript } from "plasmo"

export const config: PlasmoContentScript = {
  matches: ["<all_urls>"],
  all_frames: true
}

Working with this configuration object is a breeze thanks to the exported PlasmoContentScript type 🥳.

Injecting into the main world

You must inject into the main world if you'd like to access the window object from your content script.

It's not currently possible to declaratively inject content scripts into the main world via the content_scripts manifest field.

Instead, Chrome offers a chrome.scripting.executeScript API that lets you inject content scripts into the main world.

 chrome.scripting.executeScript(
    {
      target: {
        tabId // the tab you want to inject into
      },
      world: "MAIN", // MAIN to access the window object
      func: windowChanger // function to inject
    },
    () => {
      console.log("Background script got callback after injection")
    }
  )
}

For the func key, you can pass in a Typescript function from your project, which will automatically convert to a JavaScript function when your extension bundles.

See with-main-world-content-script-injection for an example.

Importing Web Accessible Resources

Use the url: scheme to load assets to be used from web-accessible resources.

Web-accessible resources are helpful if you'd like to reference static content from your content script, and the data-base64 or data-text schemes aren't a good solution to your problem.

Usage

In your content script,

import myJavascriptFile from "url:./path/to/my/file/something.js"

something.js will be bundled and added to the web_accessible_resources manifest.json key automatically — no need to do it manually.

What is myJavascriptFile?

> console.log(myJavascriptFile)

chrome-extension://<your chrome ext id>/something.eb20bc99.js?1656000646313

The imported variable is a string that points to the path of the resource.

So access that JavaScript file however you'd like!

NOTE: Please see this note about ~ import resolution

Last updated on July 24, 2022