Mastering Content Scripts: Giving Your Extension “Eyes” and “Hands”

Mastering Content Scripts: Giving Your Extension “Eyes” and “Hands”

If the manifest is the blueprint, Content Scripts are the actual workers on the ground. They are the only part of your extension that runs in the context of the web page you are visiting, allowing you to read its content (eyes) and modify it (hands).

How Content Scripts Work

Content scripts run in what Chrome calls an Isolated World.

  • The Shared DOM: Your script and the original website both see the same HTML elements. You can use standard document.getElementById() or fetch() just like on a normal website.
  • The Isolated Logic: Your JavaScript variables and the website’s JavaScript variables are invisible to each other. This prevents your extension from accidentally breaking the website’s own code.

Two Ways to Inject Scripts

As a developer, you have two primary methods for getting your code onto a page:

1. Static Injection (Via Manifest)

Use this if you want your script to run automatically every time a specific website loads (e.g., an ad blocker).

In your manifest.json:

"content_scripts": [
  {
    "matches": ["https://*.google.com/*"],
    "js": ["content.js"],
    "css": ["styles.css"]
  }
]

2. Programmatic Injection (Via Scripting API)

Use this if you want the script to run only when triggered by an event, such as a user clicking your extension’s icon.

In your background.js (Service Worker):

chrome.action.onClicked.addListener((tab) => {
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    files: ['content.js']
  });
});

Building a “Page Styler” Extension

Let’s build a practical tool that changes the background color of any page you visit.

  1. The Content Script (content.js):
    // This script runs directly on the web page
    document.body.style.backgroundColor = "#ADD8E6"; // Changes to light blue
    console.log("TCMHACK: Page color has been successfully swapped!");
  2. Match Patterns: To ensure your script runs on the right sites, use Match Patterns.
    • https://*.google.com/* — Runs only on Google.
    • — Runs on every single website.

Key Execution States

You can control when your script fires using the run_at key:

  • document_start: Before the DOM is even created. Great for CSS resets.
  • document_end: Immediately after the DOM is ready.
  • document_idle (Default): When the page is finished loading and is idle.

Conclusion

Content scripts are what make extensions truly powerful. By mastering how to inject and run these scripts, you can build tools that improve productivity, change UI, or scrape data. In our next tutorial, we will look at Message Passing—how these content scripts “talk” to your background service worker and popup.


Discover more from TCMHACK

Subscribe to get the latest posts sent to your email.

Tags:

Leave a Reply

Discover more from TCMHACK

Subscribe now to keep reading and get access to the full archive.

Continue reading