Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 36 ยท Projects and Practice

Project: Price Highlighter with a Content Script

Build an extension whose content script finds prices in page text and wraps them in a highlight, with an on/off switch in the popup, settings in storage and safe DOM changes.

This project puts a content script to work. Price Highlighter scans a page for amounts like $19.99 and highlights them so you can skim a long shopping page quickly. A toggle in the popup turns it on or off, and the choice is remembered. You will practise safe DOM text processing, messaging and storage together.

The real extension needs Chrome. The text-processing core runs here against a sample page, and the extension files are shown for copying into a folder.

Design

flowchart LR
    P["Popup toggle"] -- "storage.local: enabled" --> S["chrome.storage"]
    S -- "onChanged" --> C["content.js<br/>(in each page)"]
    C --> D["Wrap prices in mark.pm-price"]

The popup writes a setting; every page's content script reacts to it.

Design rules for a polite content script:

  • Touch text nodes only: never rebuild the page with innerHTML, which would destroy event listeners and could execute injected markup.
  • Skip script, style, textarea, input and already-marked nodes.
  • Run after the page is ready (document_idle) and cope with content added later with a MutationObserver.
  • Keep the page's own structure: wrap matches in a <mark> element and nothing more.

The matching logic

JavaScript
const PRICE = /(?:\$|โ‚ฌ|ยฃ)\s?\d{1,3}(?:[,.]\d{3})*(?:[.,]\d{2})?/g;

It matches a currency symbol followed by an amount such as $5, $1,299.00, โ‚ฌ 12,50. Real shopping pages vary a lot, so this is intentionally simple; improving it is part of the exercises.

Highlight prices in a sample page

Look at what is not highlighted: the phone number, "$50" in plain prose is (it is a price), and the text inside the <textarea> stays untouched. Turning the switch off restores the original text exactly, because the code only replaces text nodes and removes its own marks.

The extension files

JSON
{
  "manifest_version": 3,
  "name": "Price Highlighter",
  "version": "1.0.0",
  "description": "Highlights prices on web pages so you can scan them quickly.",
  "permissions": ["storage"],
  "action": { "default_popup": "popup.html" },
  "content_scripts": [{
    "matches": ["https://*/*"],
    "js": ["content.js"],
    "css": ["content.css"],
    "run_at": "document_idle"
  }]
}

content.css:

CSS
mark.pm-price { background: #ffe066; color: inherit; padding: 0 2px; border-radius: 3px; }

content.js (reuses the highlight and clear functions from above):

JavaScript
let observer;

async function start() {
  const { enabled = true } = await chrome.storage.local.get("enabled");
  if (enabled) turnOn(); else turnOff();
}

function turnOn() {
  highlight(document.body);
  observer = new MutationObserver((records) => {
    observer.disconnect();                    // ignore our own changes
    for (const r of records) r.addedNodes.forEach((n) => {
      if (n.nodeType === Node.ELEMENT_NODE) highlight(n);
    });
    observer.observe(document.body, { childList: true, subtree: true });
  });
  observer.observe(document.body, { childList: true, subtree: true });
}

function turnOff() {
  observer?.disconnect();
  clear(document.body);
}

chrome.storage.onChanged.addListener((changes, area) => {
  if (area === "local" && changes.enabled) {
    changes.enabled.newValue ? turnOn() : turnOff();
  }
});

start();

The popup is only a checkbox that writes enabled:

JavaScript
// popup.js
const box = document.getElementById("enabled");
const { enabled = true } = await chrome.storage.local.get("enabled");
box.checked = enabled;
box.addEventListener("change", () => chrome.storage.local.set({ enabled: box.checked }));

Because every page listens to storage.onChanged, flipping the box updates all open tabs at once, with no messaging code. For one-tab-only commands you would use messages instead.

Why these choices

  • matches is https://*/*, not <all_urls>: a trade-off. The extension needs to run on any shop, but it stays off http, file and browser pages. A stricter version would let the user add sites with optional host permissions (Permissions model).
  • No innerHTML anywhere; the extension never injects markup built from page text.
  • The observer disconnects while it edits, otherwise its own changes would trigger it forever.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the highlighter edit text nodes instead of setting innerHTML?

    Replacing only text nodes keeps the page's structure and listeners and avoids parsing page text as HTML.
  2. 2. What is the MutationObserver for?

    Many pages add content dynamically, so the script processes newly added nodes.
  3. 3. Why does the observer disconnect while highlighting?

    The highlight adds nodes, which would fire the observer repeatedly.
  4. 4. How do all open tabs learn that the toggle changed?

    onChanged fires in every context that listens, including content scripts.

Summary

  • A content script should modify text nodes, skip form fields and its own marks, and clean up after itself.
  • Use document_idle, a MutationObserver for dynamic pages, and narrow matches.
  • Storage plus onChanged is a simple way to control every tab.
  • No innerHTML with page data; leave the page's structure intact.

Next: Project: Tab Snoozer with Alarms