Content scripts
Learn more about content scripts.
Content scripts run in the context of web pages in an isolated world. This allows multiple content scripts from various extensions to coexist without conflicting with each other's execution and to stay isolated from the page's JavaScript.
A script that ends with .ts
will not have front-end runtime (e.g. react) bundled with it and won't be treated as a ui script, while a script that ends in .tsx
will be.
There are many use cases for content scripts:
- Injecting a custom stylesheet into the page
- Scraping data from the current web page
- Selecting, finding, and styling elements from the current web page
- Injecting UI elements into current web page
Code for the content scripts is located in src/app/contents
directory - you need to define .ts
or .tsx
file inside to allow Plasmo to include your script in the build.
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!
Reload your extension, open a web page, then open its inspector:
To learn more about content scripts, e.g. how to configure only specific pages to load content scripts, how to inject them into window
object or how to fetch data inside, please check the official documentation.
UI scripts
Plasmo has first-class support for mounting React components into the current webpage. This feature is called content scripts UI (CSUI).
An extension can have as many CSUI as needed, with each CSUI targeting a group of webpages or a specific webpage.
To get started with CSUI, create a .tsx
file in src/app/contents
directory.
File extensions matters!
The .tsx
extension is essential to differentiate between Content Scripts UI and regular Content Scripts. Make sure to check if you're using appropriate type of content script for your use case.
To learn more about content scripts UI, e.g. how to inject custom styles, fonts or the whole lifecycle of a component, please check the official documentation.
How does it work?
Under the hood, Plasmo wraps the component you exported inside a generated content script that implements the Shadow DOM technique above, together with many helpful features. This isolation technique prevents the web page's style from affecting your component's styling and vice-versa.
Last updated on