SyntaxPilot
Courses/Vibe Coding/Lesson 19
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Vibe Coding · Lesson 19 of 40

Project: Chrome extension

manifest.jsonpopupcontent scriptpermissions and why fewer is saferloading an unpacked extensiondebugging with DevTools

Vibe Coding: build real apps with AI · Episode 19. Every agent run below is real: Claude Code 2.1.322 (model claude-opus-5-5, from the run's init line) in print mode (claude -p), early on 12 November 2026 (India time), in /home/asha/projects/study-helper (a Git repository). The browser is Chrome for Testing 153.0.8010.12 (the Chromium build that Playwright ships), run with a real window on a virtual display: the clicks on the toolbar icon and the typing are real mouse and keyboard events, and every screenshot is of the real screen. The articles and the "Practice Bank" login page are local pages made for this video (http://localhost:8000), and the password is a made-up practice value. The JavaScript demos run in the SyntaxPilot online compiler. Facts about Chrome come from Chrome for Developers and the Chrome Web Store Help pages, read on 12 November 2026. Replies are quoted exactly, shortened where marked .... No keys or secrets are used.

The problem: thirty tabs in exam week

Asha has thirty article tabs open for her exams. Before starting one she wants to know whether it is a 5-minute or a 25-minute read, and while reading she wants every place a key word appears to be highlighted. Ctrl+F finds one match at a time and forgets it when she looks away. None of these websites are hers, so she cannot change them: the help has to live in her browser.

The obvious way: a line in the DevTools console

DevTools (developer tools) are built into every browser (Ctrl+Shift+J opens the Console in Chrome). The console is a box where you type JavaScript, and it runs inside the page you are looking at.

document.title = Math.ceil(document.body.innerText.split(/\s+/).length / 200) + " min read - " + document.title

Real result: the tab title became 4 min read - Photosynthesis: how leaves make food. Then Asha pressed F5: the title was back to normal and the console was empty.

Why it fails: each time you open or reload a page, the website sends a fresh copy and your tab runs it. Console code is added to that one copy only. A reload, a new tab or another site gives you a page without it. We need code that the browser keeps and runs for us: a browser extension.

What an extension is (an app for your browser)

Your phone Your browser
Install an app once, it stays Browser extension: a small program Chrome keeps and runs
The app's details page (name, version, access) manifest.json: the extension's ID card
Tap the icon, a small window opens Popup: the page that drops down when you click the toolbar icon
"Allow access to photos?" Permissions: which sites and features it may use

manifest.json: the ID card

Chrome's Hello World guide: the manifest is a JSON file that "describes the extension's capabilities and configuration", and it must be in the extension's root (main) folder.

JSON is a way to write data as text: "name": value pairs in double quotes, commas between items, curly brackets around a group. It is strict: no comma after the last item and no comments.

{
  "manifest_version": 3,
  "name": "Study Helper",
  "version": "1.0.0",
  "description": "Shows how long an article takes to read, ...",
  "action": {
    "default_popup": "popup.html"
  }
}
  • manifest_version: 3 is today's format (Manifest V3). Old tutorials, and AI tools trained on them, may write 2: check for 3.
  • action.default_popup is the page shown when you click the toolbar icon.

A trailing comma (run in the compiler)

const manifest = `{
  "manifest_version": 3,
  "name": "Study Helper",
  "version": "1.0.0",
}`;

try {
  JSON.parse(manifest);
  console.log("Valid JSON");
} catch (err) {
  console.log("Chrome can't read it:");
  console.log(err.message.replace(" (line", "\n(line"));   // 2 lines, to fit
}

// The fix: no comma after the last item
const fixed = manifest.replace('"1.0.0",', '"1.0.0"');
console.log(JSON.parse(fixed).name, "loads fine");

Output:

Chrome can't read it:
Expected double-quoted property name in JSON at position 75
(line 5 column 1)
Study Helper loads fine

What Chrome itself says (real dialogs)

Folder Chrome's message
Notepad saved the file as manifest.json.txt (Windows hides .txt) Failed to load extension from: /home/asha/test/study-helper. Manifest file is missing or unreadable
A trailing comma after "version": "1.0.0", Failed to load extension from: /home/asha/test/study-helper-v2. Manifest is not valid JSON. trailing comma at line 5 column 1

The AI builds it (agent run 1)

claude -p "Make a Chrome extension in this folder to help me study. On every article I open, it should show a small box with how many minutes the article takes to read. And when I click the extension's icon, a popup lets me type a word and it highlights every place that word appears on the page. Manifest V3, plain JavaScript, no frameworks." --permission-mode acceptEdits

A first run without --permission-mode acceptEdits had all six file writes refused ("Claude requested permissions to write to ... but you haven't granted it yet."). Accept edits is a permission mode (episode 6) that lets the agent write files in the folder without asking each time; running commands still needs approval.

Write  manifest.json, content.js, popup.html, popup.css, popup.js
Bash   which chromium chromium-browser google-chrome node
Bash   node --check content.js ...         → "requires approval"
Bash   google-chrome --headless=new ...    → "requires approval"
Write  README.md
Reply: "I haven't tested it yet ... manifest.json: the extension's
   settings. It asks for only two permissions (activeTab and
   scripting)."

Its manifest (real file):

{
  "manifest_version": 3,
  "name": "Study Helper",
  "version": "1.0.0",
  "permissions": ["activeTab", "scripting"],
  "action": {
    "default_title": "Study Helper",
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["content.js"],
      "run_at": "document_idle"
    }
  ]
}

* in a match pattern means "anything": https://*/* matches every https page. Remember the content_scripts block.

Loading it unpacked

Unpacked means loaded straight from a folder, not installed from the Chrome Web Store. Chrome's steps:

  1. Go to chrome://extensions in a new tab.
  2. Turn on Developer mode (top right).
  3. Click Load unpacked and select the extension's folder.

Real result: "Study Helper 1.0.0" appeared with Details, Remove, a reload arrow and an on/off switch. Pin it from the puzzle-piece menu so its icon sits in the toolbar.

What needs a reload (Chrome's Hello World guide): after changing the manifest, the service worker or a content script, click the reload arrow on the extension's card (and refresh the page for content scripts). The popup and other extension pages don't need it.

It works (real click on the toolbar icon)

  • The biology article (676 words) showed 📖 3 min read · 676 words in a box at the bottom right.
  • Clicking the icon, typing light and pressing Enter: 1 of 17 matches, every match yellow, the current one orange, ↑/↓ to jump.
Piece Where it runs Can it touch the article?
Popup (popup.html + popup.js) Its own small page, opened by the icon No
Content script (content.js) Inside the web page Yes: it can read and change the page

Chrome's docs: "Content scripts are files that run in the context of web pages." They run in an isolated world: "a private execution environment that isn't accessible to the page or other extensions". The popup and the content script talk with messages:

// popup.js: runs in the popup window
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const res = await chrome.tabs.sendMessage(tab.id,
                { type: "highlight", term: "light", wholeWord: false });
statusEl.textContent = `${res.index} of ${res.total} matches`;

// content.js: runs inside the article page
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
  if (msg.type === "highlight") {
    const total = highlight(msg.term, msg.wholeWord);   // wrap matches in <mark>
    sendResponse({ total, index: total ? 1 : 0 });
  }
});

<mark> is the HTML tag for highlighted text.

Reading the AI's code (never ship code you can't explain)

Why escapeRegExp?

A regex (regular expression) is a search pattern. Some characters are commands, not letters: + means "repeat the thing before", and *, ., ?, (, [ are special too. Escaping puts a backslash before them so they mean themselves.

const term = "C++";                       // Asha searches for C++
const text = "Pointers in C++ made simple. C++ kept pointers from C.";

try {
  const naive = new RegExp(term, "gi");   // the obvious way
  console.log(text.match(naive));
} catch (err) {
  console.log("Crash:", err.message);
}

// The AI's escapeRegExp: put a backslash before every special character
function escapeRegExp(s) {
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
console.log("Escaped:", escapeRegExp(term));
const safe = new RegExp(escapeRegExp(term), "gi");
console.log("Matches:", text.match(safe).length);

Output:

Crash: Invalid regular expression: /C++/gi: Nothing to repeat
Escaped: C\+\+
Matches: 2

The reading-time maths

const WORDS_PER_MINUTE = 220;          // the AI's choice (an average adult reader)

function readingTime(words) {
  return Math.max(1, Math.round(words / WORDS_PER_MINUTE));
}

const articles = [["Photosynthesis", 676], ["C++ pointers", 305],
                  ["Short notice", 90], ["Long chapter", 4500]];

for (const [name, words] of articles) {
  const exact = (words / WORDS_PER_MINUTE).toFixed(2);
  console.log(name.padEnd(15), String(words).padStart(5), "words =",
              exact.padStart(5), "min ->", readingTime(words), "min read");
}

// Without Math.max(1, ...), a 90-word notice would say:
console.log("Without the minimum:", Math.round(90 / WORDS_PER_MINUTE), "min read");

Output:

Photosynthesis    676 words =  3.07 min -> 3 min read
C++ pointers      305 words =  1.39 min -> 1 min read
Short notice       90 words =  0.41 min -> 1 min read
Long chapter     4500 words = 20.45 min -> 20 min read
Without the minimum: 0 min read

The console line said 4 minutes: it divided the whole page's words by 200 and rounded up. The extension said 3: 220 words a minute, rounded to the nearest minute, at least 1. Same article, different assumptions.

AI mistake 1: code boxes were never searched

Real result on the C++ article: searching cout said No matches, although std::cout << *p; was on screen; and light in the photosynthesis equation box was not highlighted. The reason, in the AI's content.js:

const SKIP_TAGS = new Set([
  "SCRIPT", "STYLE", "NOSCRIPT", "TEXTAREA", "INPUT", "SELECT",
  "OPTION", "IFRAME", "SVG", "CANVAS", "CODE", "PRE", "TEMPLATE"
]);

// while walking the page's text:
if (SKIP_TAGS.has(el.tagName.toUpperCase())) {
  return NodeFilter.FILTER_REJECT;     // never look inside these
}

CODE and PRE are the tags for code boxes. The AI guessed code wasn't worth searching; for a programming student it is the most important text. Test with the pages you really use.

AI mistake 2: "only two permissions"

The AI's reply: "It asks for only two permissions (activeTab and scripting)." Chrome's Details page for version 1.0.0 said:

Site access · Allow this extension to read and change all your data on websites you visit: On all sites

The content_scripts block did that. Chrome's "Declare permissions" page: adding or changing match patterns in host_permissions and content_scripts.matches also triggers a warning. Host permissions are the list of websites an extension may access.

Proof on a login page (real)

On the practice login page, with a made-up password typed in, the DevTools console's context dropdown (next to "top") listed Study Helper: its code was running in the login page. Selecting it and running

document.querySelector("#password").value

returned 'MangoTree42'. The extension never did anything bad with it, but it ran on every page with the power to read everything.

Permissions: why fewer is safer

Real life Extension
A spare house key for the newspaper boy: any room, any day content_scripts on http://*/* and https://*/*: On all sites
Opening the door when he rings: one visit activeTab: one tab, after your click
Fewer keys, fewer surprises Least privilege: ask only for what the main job needs
  • activeTab (Chrome's docs): "gives an extension temporary access to the currently active tab when the user invokes the extension" (clicks its icon, a context-menu item, a keyboard shortcut, or an omnibox suggestion). Access ends when the user navigates to a different site or closes the tab. It "displays no warning message during installation."
  • Chrome's permission warning guidelines: "Ensure you only request permissions that support the extension's main functionality." Optional permissions can be requested at runtime instead.
  • Chrome Web Store Help lists the warning "Your data on all the websites you visit": it "gives access to read, request or modify data from every page you visit (bank account, Facebook)."
  • Another example from Chrome's permissions list: "tabs" shows the warning "Read your browsing history."

Why it matters even when today's code is honest: extensions update themselves, so a future version or a stolen developer account can add bad code with all the access you already gave; a bug runs on every page; and people see the warning and trust the extension less.

Asha's day (run in the compiler)

// Asha's browsing day. Which pages does each version run on?
const day = ["https://studynotes.example/photosynthesis", "https://mail.example.com/inbox",
  "https://bank.example.in/login", "https://school.example.edu/marks",
  "https://codecorner.example/cpp-pointers", "https://video.example.com/watch",
  "https://shop.example.in/cart", "https://chat.example.com/family"];
const clicked = ["https://studynotes.example/photosynthesis",
                 "https://codecorner.example/cpp-pointers"];

// Version 1: "content_scripts": matches ["http://*/*", "https://*/*"]
const v1 = day.filter((url) => /^https?:\/\/[^/]+\//.test(url));
// Version 2: "activeTab": only the tabs where Asha clicked the icon
const v2 = day.filter((url) => clicked.includes(url));

console.log("Version 1 ran on", v1.length, "of", day.length, "pages:");
v1.forEach((u) => console.log("   ", u));
console.log("Version 2 ran on", v2.length, "of", day.length, "pages:");
v2.forEach((u) => console.log("   ", u));

Output:

Version 1 ran on 8 of 8 pages:
    https://studynotes.example/photosynthesis
    https://mail.example.com/inbox
    https://bank.example.in/login
    https://school.example.edu/marks
    https://codecorner.example/cpp-pointers
    https://video.example.com/watch
    https://shop.example.in/cart
    https://chat.example.com/family
Version 2 ran on 2 of 8 pages:
    https://studynotes.example/photosynthesis
    https://codecorner.example/cpp-pointers

The fix (agent run 2)

claude -p "Two problems. 1) You said it only asks for two permissions, but chrome://extensions says "Allow this extension to read and change all your data on websites you visit: On all sites". Because content.js runs on every page, it can read the password I type on my bank's login page (I checked in DevTools). I only need it when I click the icon. Make it run only on click: no content_scripts in the manifest, just activeTab and scripting, and show the reading time inside the popup instead of a box on every page. 2) Searching "cout" says No matches, but std::cout is right there in a code box on the page. Highlight inside code blocks too. Keep everything else the same." --permission-mode acceptEdits
Write  manifest.json        no "content_scripts", version 1.1.0
Edit   content.js           no box on the page; CODE and PRE not skipped
Edit   popup.js, popup.html, popup.css, README.md
Bash   node --check content.js ...   → "requires approval"
Reply: "You were right, and what I told you before was misleading.
   The manifest only listed two permissions, but the content_scripts
   entry quietly gave the extension access to every site, so it ran
   on every page, bank logins included. ... I couldn't test it ...
   The card's site access should now say "On click"."
{
  "manifest_version": 3,
  "name": "Study Helper",
  "version": "1.1.0",
  "permissions": ["activeTab", "scripting"],
  "action": {
    "default_title": "Study Helper",
    "default_popup": "popup.html"
  }
}

How content.js reaches the page now: the click opens the popup and gives activeTab access to that tab, and the scripting permission lets the popup inject the file on demand (Chrome calls this programmatic injection, versus static declarations in the manifest):

// popup.js, version 1.1.0: runs when Asha clicks the icon
const ready = (async () => {
  const tab = await getTab();               // the tab she is looking at
  await chrome.scripting.executeScript({    // load content.js into it NOW
    target: { tabId: tab.id },
    files: ["content.js"],
  });
  return tab;
})();

async function send(message) {
  const tab = await ready;
  return chrome.tabs.sendMessage(tab.id, message);
}

The retest (real)

Test Version 1.0.0 Version 1.1.0
Reading time Box on every article page Top of the popup: 📖 1 min read · 305 words
Search cout (C++ article) No matches 1 of 1 match, inside the code box
Search light (biology) 17 matches (equation skipped) 18 matches
light, Whole word only 16 matches (sunlight not highlighted)
Practice login page, DevTools context list Study Helper listed; password readable Study Helper not listed
Details → Site access "read and change all your data on websites you visit: On all sites" The "On all sites" line is gone; the list of sites it may access automatically is empty

The AI predicted "The card's site access should now say "On click"". Chrome's page did not use those words: the AI was guessing a screen it had never seen. Always look yourself.

Debugging with DevTools (agent run 3)

On chrome://extensions the popup said "Can't run on this page". Right-click the icon → Inspect popup (shown with Developer mode on) opens DevTools for the popup page. Its console was empty, because the AI's code swallowed the error (caught it and threw away the message):

  } catch {
    readingEl.textContent = "Can't run on this page";
    readingEl.classList.add("error");
  }
claude -p "On chrome://extensions the popup just says "Can't run on this page", and when I inspect the popup the console is empty, so I can't see why. Don't hide errors: log the real error with console.error in every catch, and keep the friendly message. Change nothing else." --permission-mode acceptEdits
Bash   grep -rn "catch" --include=*.js .   → popup.js:35, popup.js:61
Edit   popup.js   } catch (err) {
                    console.error("Reading time failed:", err);
Edit   popup.js   console.error(`"${message.type}" message failed:`, err);
Reply: "It's probably the executeScript call failing, since Chrome
   doesn't let extensions inject scripts into chrome:// pages."

After reloading and clicking again, the popup's console showed:

Reading time failed: Error: Cannot access a chrome:// URL

Chrome does not let extensions run scripts on its own chrome:// pages.

Where to look when it breaks

Problem Where to look
Won't load The error dialog, or the card's Errors button ("turns red when there's an error")
Popup Right-click the icon → Inspect popup → Console
Content script The web page's own DevTools console; pick the extension in the dropdown next to "top" (content script errors are not on the Extensions page)
Service worker (background script) The link next to "Inspect views" on the card
"My change does nothing" You changed the manifest or a content script: click reload on the card, then refresh the tab

Git history of the project (real):

e97a618 Log real errors in popup catch blocks (Claude Code, prompt 3)
3bf5197 Run only on click (activeTab), reading time in popup, search code blocks (Claude Code, prompt 2)
bc98b8f Study Helper: reading time box and word highlighter (Claude Code, prompt 1)

The finished extension (version 1.1.0, all files)

manifest.json

{
  "manifest_version": 3,
  "name": "Study Helper",
  "version": "1.1.0",
  "description": "Shows how long an article takes to read, and highlights any word you search for on the page.",
  "permissions": ["activeTab", "scripting"],
  "action": {
    "default_title": "Study Helper",
    "default_popup": "popup.html"
  }
}

popup.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Study Helper</title>
  <link rel="stylesheet" href="popup.css">
</head>
<body>
  <p id="reading" class="reading" aria-live="polite">Measuring…</p>
  <h1>Find &amp; highlight</h1>
  <form id="search-form">
    <input id="term" type="text" placeholder="Type a word…" autocomplete="off" autofocus>
    <button type="submit">Highlight</button>
  </form>
  <label class="option">
    <input id="whole-word" type="checkbox"> Whole word only
  </label>
  <div class="row">
    <span id="status" aria-live="polite"></span>
    <span class="nav">
      <button id="prev" type="button" title="Previous match" disabled>↑</button>
      <button id="next" type="button" title="Next match" disabled>↓</button>
      <button id="clear" type="button">Clear</button>
    </span>
  </div>
  <script src="popup.js"></script>
</body>
</html>

popup.css

body {
  width: 280px;
  margin: 0;
  padding: 12px;
  font: 13px/1.4 system-ui, -apple-system, "Segoe UI", sans-serif;
  color: #111827;
  background: #fff;
}
.reading {
  margin: 0 0 12px; padding: 8px 10px; border-radius: 8px;
  background: #1f2937; color: #f9fafb;
}
.reading .muted { opacity: .7; font-size: 11px; }
.reading.error { background: #fef2f2; color: #b91c1c; }
h1 { font-size: 14px; margin: 0 0 8px; }
form { display: flex; gap: 6px; }
input[type="text"] {
  flex: 1; min-width: 0; padding: 6px 8px;
  border: 1px solid #d1d5db; border-radius: 6px; font: inherit;
}
input[type="text"]:focus { outline: 2px solid #facc15; border-color: #eab308; }
button {
  padding: 6px 10px; border: 1px solid #d1d5db; border-radius: 6px;
  background: #f9fafb; font: inherit; cursor: pointer;
}
button[type="submit"] { background: #facc15; border-color: #eab308; font-weight: 600; }
button:disabled { opacity: .4; cursor: default; }
.option { display: flex; align-items: center; gap: 6px; margin: 8px 0; color: #4b5563; }
.row { display: flex; align-items: center; justify-content: space-between; gap: 6px; }
.nav { display: flex; gap: 4px; }
.nav button { padding: 4px 8px; }
#status { color: #4b5563; }
#status.error { color: #b91c1c; }

popup.js

const form = document.getElementById("search-form");
const termInput = document.getElementById("term");
const wholeWord = document.getElementById("whole-word");
const statusEl = document.getElementById("status");
const prevBtn = document.getElementById("prev");
const nextBtn = document.getElementById("next");
const clearBtn = document.getElementById("clear");
const readingEl = document.getElementById("reading");

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

// Nothing runs on pages by default. Clicking the icon grants activeTab access to this one tab,
// and we inject content.js into it now. (It guards against double-loading if the popup is reopened.)
const ready = (async () => {
  const tab = await getTab();
  await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ["content.js"] });
  return tab;
})();

async function send(message) {
  const tab = await ready;
  return chrome.tabs.sendMessage(tab.id, message);
}

async function showReadingTime() {
  try {
    const s = await send({ type: "stats" });
    readingEl.classList.remove("error");
    readingEl.innerHTML = s.isArticle
      ? `📖 <strong>${s.minutes} min read</strong> <span class="muted">· ${s.words.toLocaleString()} words</span>`
      : `<span class="muted">Not enough article text for a reading time</span>`;
  } catch (err) {
    console.error("Reading time failed:", err);
    readingEl.textContent = "Can't run on this page";
    readingEl.classList.add("error");
  }
}
showReadingTime();

function showResult(res) {
  statusEl.classList.remove("error");
  if (!res || !res.total) {
    statusEl.textContent = termInput.value.trim() ? "No matches" : "";
  } else {
    statusEl.textContent = `${res.index} of ${res.total} match${res.total === 1 ? "" : "es"}`;
  }
  prevBtn.disabled = nextBtn.disabled = !(res && res.total);
}

function showError() {
  statusEl.textContent = "Can't run on this page";
  statusEl.classList.add("error");
  prevBtn.disabled = nextBtn.disabled = true;
}

async function run(message) {
  try {
    showResult(await send(message));
  } catch (err) {
    console.error(`"${message.type}" message failed:`, err);
    showError(); // chrome:// pages, the Web Store, PDFs, etc.
  }
}

form.addEventListener("submit", (e) => {
  e.preventDefault();
  run({ type: "highlight", term: termInput.value, wholeWord: wholeWord.checked });
});
wholeWord.addEventListener("change", () => {
  if (termInput.value.trim()) form.requestSubmit();
});
prevBtn.addEventListener("click", () => run({ type: "step", step: -1 }));
nextBtn.addEventListener("click", () => run({ type: "step", step: 1 }));
clearBtn.addEventListener("click", () => {
  termInput.value = "";
  run({ type: "clear" });
  termInput.focus();
});

content.js

// Study Helper page script: reading-time stats + word highlighting.
// Not a content script: the popup injects it into the current tab only when you click the icon
// (activeTab + scripting). The guard makes repeated injections (popup reopened) harmless.
if (!window.__studyHelperLoaded) {
  window.__studyHelperLoaded = true;

  const WORDS_PER_MINUTE = 220;
  const MIN_WORDS_FOR_ARTICLE = 150; // skip search pages, menus, near-empty pages
  const MARK_CLASS = "study-helper-mark";
  // Text inside these is never visible page text (or is a form field), so don't touch it.
  // <code>/<pre> are NOT skipped: code samples are real page text worth searching.
  const SKIP_TAGS = new Set([
    "SCRIPT", "STYLE", "NOSCRIPT", "TEXTAREA", "INPUT", "SELECT",
    "OPTION", "IFRAME", "SVG", "CANVAS", "TEMPLATE"
  ]);

  // ---------- Reading time ----------

  function findArticleRoot() {
    // Prefer the most specific "article-like" container; fall back to the body.
    const articles = Array.from(document.querySelectorAll("article"));
    if (articles.length) {
      // Pick the article with the most text (pages sometimes have small teaser <article>s).
      return articles.reduce((best, el) =>
        el.innerText.length > best.innerText.length ? el : best
      );
    }
    return document.querySelector("main, [role='main']") || document.body;
  }

  function countWords(text) {
    const matches = text.match(/[\p{L}\p{N}]+(?:['’-][\p{L}\p{N}]+)*/gu);
    return matches ? matches.length : 0;
  }

  // Returned to the popup, which displays it. Nothing is added to the page.
  function getReadingStats() {
    if (!document.body) return { words: 0, minutes: 0, isArticle: false };
    const words = countWords(findArticleRoot().innerText || "");
    return {
      words,
      minutes: Math.max(1, Math.round(words / WORDS_PER_MINUTE)),
      isArticle: words >= MIN_WORDS_FOR_ARTICLE
    };
  }

  // ---------- Highlighting ----------

  function ensureHighlightStyle() {
    if (document.getElementById("study-helper-style")) return;
    const style = document.createElement("style");
    style.id = "study-helper-style";
    style.textContent = `
      mark.${MARK_CLASS} {
        background: #fde047 !important; color: #111 !important;
        border-radius: 2px; padding: 0 1px;
      }
      mark.${MARK_CLASS}.study-helper-current {
        background: #fb923c !important; outline: 2px solid #ea580c;
      }`;
    (document.head || document.documentElement).appendChild(style);
  }

  function clearHighlights() {
    const marks = document.querySelectorAll(`mark.${MARK_CLASS}`);
    const parents = new Set();
    marks.forEach((mark) => {
      const parent = mark.parentNode;
      parent.replaceChild(document.createTextNode(mark.textContent), mark);
      parents.add(parent);
    });
    parents.forEach((p) => p.normalize()); // merge split text nodes back together
  }

  function escapeRegExp(s) {
    return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  }

  function highlight(term, wholeWord) {
    clearHighlights();
    term = term.trim();
    if (!term) return 0;
    ensureHighlightStyle();

    const pattern = wholeWord
      ? `(?<![\\p{L}\\p{N}_])${escapeRegExp(term)}(?![\\p{L}\\p{N}_])`
      : escapeRegExp(term);
    const regex = new RegExp(pattern, "giu");

    // Collect text nodes first; modifying the DOM while walking would confuse the walker.
    const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
      acceptNode(node) {
        if (!node.nodeValue.trim()) return NodeFilter.FILTER_REJECT;
        for (let el = node.parentElement; el && el !== document.body; el = el.parentElement) {
          if (SKIP_TAGS.has(el.tagName.toUpperCase()) || el.isContentEditable) {
            return NodeFilter.FILTER_REJECT;
          }
        }
        return NodeFilter.FILTER_ACCEPT;
      }
    });
    const nodes = [];
    while (walker.nextNode()) nodes.push(walker.currentNode);

    let count = 0;
    for (const node of nodes) {
      const text = node.nodeValue;
      regex.lastIndex = 0;
      let match;
      let last = 0;
      const frag = document.createDocumentFragment();
      while ((match = regex.exec(text)) !== null) {
        if (match[0].length === 0) { regex.lastIndex++; continue; }
        frag.appendChild(document.createTextNode(text.slice(last, match.index)));
        const mark = document.createElement("mark");
        mark.className = MARK_CLASS;
        mark.textContent = match[0];
        frag.appendChild(mark);
        last = match.index + match[0].length;
        count++;
      }
      if (last > 0) {
        frag.appendChild(document.createTextNode(text.slice(last)));
        node.parentNode.replaceChild(frag, node);
      }
    }
    currentIndex = -1;
    if (count) goTo(1);
    return count;
  }

  let currentIndex = -1;

  function goTo(step) {
    const marks = document.querySelectorAll(`mark.${MARK_CLASS}`);
    if (!marks.length) return { index: 0, total: 0 };
    marks[currentIndex]?.classList.remove("study-helper-current");
    currentIndex = (currentIndex + step + marks.length) % marks.length;
    const mark = marks[currentIndex];
    mark.classList.add("study-helper-current");
    mark.scrollIntoView({ behavior: "smooth", block: "center" });
    return { index: currentIndex + 1, total: marks.length };
  }

  chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
    if (msg.type === "stats") {
      sendResponse(getReadingStats());
    } else if (msg.type === "highlight") {
      const total = highlight(msg.term, msg.wholeWord);
      sendResponse({ total, index: total ? 1 : 0 });
    } else if (msg.type === "clear") {
      clearHighlights();
      currentIndex = -1;
      sendResponse({ total: 0, index: 0 });
    } else if (msg.type === "step") {
      sendResponse(goTo(msg.step));
    }
  });
}

To try it: save the five files in one folder, open chrome://extensions, turn on Developer mode, click Load unpacked, pick the folder, and pin Study Helper.

Common mistakes (real)

Mistake What you see Why Fix
"version": "1.0.0", before } Manifest is not valid JSON. trailing comma at line 5 column 1 JSON is strict No trailing commas, no comments
File saved as manifest.json.txt Manifest file is missing or unreadable Windows hides .txt Show file extensions; rename
content_scripts on http://*/*, https://*/* Site access On all sites; runs on the login page Match patterns count as site access activeTab + scripting, inject on click
"CODE", "PRE" in the skip list cout: No matches The AI guessed what matters Test with your real pages
new RegExp("C++") Invalid regular expression: /C++/gi: Nothing to repeat + is a command in a regex Escape the search term
catch { show a message } Popup console empty The error was swallowed console.error(err) in every catch
Edited content.js, nothing changed Old behaviour Chrome still runs the old file Reload the card, refresh the tab
Trusting the AI's summary "only two permissions" It didn't count match patterns Read Chrome's Details page

Mini project

Build a "Focus timer" extension with an AI: click the icon, start a 25-minute timer in the popup, and show how many minutes are left. Rules: Manifest V3, plain JavaScript, no access to any website (it doesn't need any). Then:

  1. Load it unpacked and open its Details page: what does Site access say?
  2. Ask the AI to "also block YouTube while the timer runs". What permission does it add, and what does the Details page say now?
  3. Close the popup: does the timer stop? Ask the AI why, and read about service workers and chrome.alarms in Chrome's docs.
  4. Put a console.error in every catch, and find the messages with Inspect popup.

Practice questions

  1. Why does a line typed into the DevTools console disappear after a reload?
Answer

The tab runs a fresh copy of the page sent by the website. Console code was added only to the old copy.

  1. Which file must every extension have, and where?
Answer

manifest.json, in the extension's main (root) folder.

  1. Why does {"name": "Study Helper",} fail to load?
Answer

JSON does not allow a comma after the last item (a trailing comma). Chrome says "Manifest is not valid JSON".

  1. The popup has the word Asha typed; the article has the text. How does the highlight happen?
Answer

The popup sends a message to the content script in the article's tab (chrome.tabs.sendMessage). The content script, which runs inside the page, wraps the matches in mark tags and sends back the count.

  1. What does escapeRegExp("C++") return, and why is it needed?
Answer

C++ . In a regex + means "repeat", so "C++" as a pattern is invalid (Nothing to repeat). Escaping makes each + a plain plus sign.

  1. An article has 1,000 words. What does the AI's formula show? And the console line's?
Answer

Math.max(1, Math.round(1000 / 220)) = Math.round(4.55) = 5 min. The console line: Math.ceil(1000 / 200) = 5 min (it counted the whole page, so in practice a little more).

  1. The manifest lists only "activeTab" and "scripting". Can the extension still have access to every site?
Answer

Yes, if it has a content_scripts entry with broad match patterns such as https:///. Those count as site access; Chrome's Details page shows "On all sites".

  1. With activeTab, when does access end?
Answer

When the user navigates to a different site or closes the tab.

  1. The popup says "Can't run on this page" and the console is empty. What's wrong with the code, and what's the fix?
Answer

The catch block shows a message but never logs the error (it swallows it). Add console.error(err) in the catch, then look in Inspect popup.

  1. You edited content.js but the page behaves the same. Why?
Answer

Content scripts need the extension to be reloaded (reload arrow on its card) and the page refreshed. Chrome is still running the old file.

Quiz

Which manifest can read every page Asha visits?

A) "permissions": ["activeTab"]
B) "permissions": ["storage"]
C) "content_scripts": [{ "matches": ["https://*/*"], "js": ["content.js"] }]
D) "action": { "default_popup": "popup.html" }
Answer

C. A content script matched to https:/// runs in every https page, so Chrome shows site access On all sites. activeTab gives one tab, only after a click; storage and a popup give no page access.

Interview questions

  1. What is the difference between a popup, a content script and a service worker in a Chrome extension?
  2. What is an isolated world, and what can a content script not do directly? (Chrome's docs: it can't use most extension APIs directly; it reaches them through messages.)
  3. activeTab vs host permissions: when would you need each?
  4. Static content scripts vs programmatic injection with chrome.scripting.executeScript: trade-offs?
  5. How do you find the cause of an error in an extension's popup? In a content script?
  6. What does "least privilege" mean, and how would you review an AI-generated manifest for it?
  7. Why can't an extension run on chrome:// pages?

Glossary

Term Meaning (plain words) Example
Browser extension A small program you install into the browser; the browser keeps it and runs it Study Helper
DevTools The developer tools built into the browser Ctrl+Shift+J opens the Console
Console The DevTools box where you type JavaScript that runs in the page; also where errors appear document.title = ...
manifest.json The extension's ID card: name, version, popup, permissions "manifest_version": 3
JSON A strict text format for data: "key": value, commas between items, no trailing comma, no comments {"name": "Study Helper"}
Trailing comma A comma after the last item; JSON rejects it "1.0.0",}
Manifest V3 Today's manifest format, manifest_version: 3 Version 2 is the old format
Load unpacked Install an extension straight from a folder (Developer mode) chrome://extensions → Load unpacked
Developer mode A switch on chrome://extensions that shows Load unpacked and debugging links Top right of the page
Toolbar icon (action) The extension's button next to the address bar The grey S
Popup The small page that drops down when you click the icon popup.html
Content script A file that runs inside web pages and can read and change them content.js
Isolated world The content script's private space: it sees the page, the page can't see its variables Study Helper in the DevTools context list
Message passing Sending data between the popup and the content script chrome.tabs.sendMessage(tab.id, {type: "highlight"})
Permission What an extension declares it may use "permissions": ["activeTab", "scripting"]
Host permissions / site access Which websites an extension may read and change "On all sites"
Match pattern A pattern of web addresses; * means anything https://*/* = every https page
activeTab Temporary access to the current tab, only after the user invokes the extension Clicking the icon
scripting Permission to use chrome.scripting, e.g. to inject a file chrome.scripting.executeScript
Programmatic injection Loading a content script on demand from code, instead of declaring it for every page After the click
Least privilege Ask only for the access the main job needs activeTab instead of all sites
Regex (regular expression) A search pattern where some characters are commands + = repeat
Escaping Putting \ before a special character so it means itself C\+\+
<mark> The HTML tag for highlighted text Yellow matches
Catch block The code that runs when something fails catch (err) { ... }
Swallowing an error Catching an error and throwing away its message An empty console
console.error Prints an error message to the console console.error("Reading time failed:", err)
Inspect popup Right-click the icon → DevTools for the popup page Developer mode on
Service worker An extension's background script, running without a page "Inspect views" link
Accept edits An agent permission mode: it may write files without asking each time --permission-mode acceptEdits

Summary

  • Code typed into the console disappears on reload; an extension is code the browser keeps and runs.
  • manifest.json is its ID card, in strict JSON: no trailing commas, no comments; manifest_version: 3.
  • Load unpacked: chrome://extensions → Developer mode → Load unpacked. Reload the card after changing the manifest or a content script.
  • The popup is its own page; the content script runs inside the web page; they talk with messages.
  • Read the AI's code: escapeRegExp stops C++ from crashing a regex; Math.max(1, ...) stops "0 min read".
  • The AI's real mistakes: it skipped code boxes, and it said "only two permissions" while Chrome said On all sites; its code could read a login page's password.
  • Fewer is safer: activeTab + scripting, injected on click. Check Chrome's Details page yourself.
  • Never swallow errors: console.error in every catch, then Inspect popup or the page's console.

Next episode: an AI-powered app that calls a real LLM API, and keeps its key on the server.