Logo Building Browser Extensions

Building Browser Extensions

Cộng đồng
wdm0006
building-browser-extensions

Builds and tests Manifest V3 browser extensions — service-worker message channels that survive teardown, chrome.storage read-modify-write safety, settings validation in the popup, and a Jest chrome mock that can actually fail. Use when writing or reviewing a background service worker, a popup that reads/writes chrome.storage, an extension's Jest suite, or debugging an extension whose UI silently stops responding.

Tổng quan

Nhà phát hànhwdm0006
Kho mãpython-skills
Tên kỹ năngbuilding-browser-extensions
Sao
111
Bản fork
17
Tệp đi kèm
Chỉ có hướng dẫn
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Hướng dẫn có đủ mọi thứ cần thiết

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được wdm0006 công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Building Browser Extensions trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/wdm0006/python-skills/tree/main/skills/javascript/browser-extensions
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wdm0006/python-skills.git /tmp/python-skills
mkdir -p .claude/skills
cp -r /tmp/python-skills/skills/javascript/browser-extensions .claude/skills/building-browser-extensions
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Building Browser Extensions trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Building Browser Extensions ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Building Browser Extensions với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Manifest V3 Extensions

An MV3 background script is not a long-lived page — it is a service worker the browser tears down whenever it looks idle. Almost every bug below is the same bug in different clothes: work that was started but never awaited, or state that was written from a stale snapshot. Both fail silently. There is no crash, no console error in front of the user — just a setting that reverts, a button that does nothing, or a suite that stays green over a broken handler.

Await every side effect before the handler resolves

A fire-and-forget chrome.storage.local.set can be killed with the worker. If a message handler's caller depends on that write, the write must complete before the response is sent.

MV3's onMessage closes the reply channel as soon as the listener returns unless it returns literal true:

js
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
  if (msg.action === 'triggerAction') {
    doWork()                                  // resolves only after its writes land
      .then(() => sendResponse({ success: true }))
      .catch((error) => sendResponse({ success: false, error: String(error) }));
    return true;                              // REQUIRED: keeps the channel open
  }
});

Then let the caller await the response instead of guessing at a delay:

js
// BAD — a race dressed up as a fix. Slow worker: stale read. Fast worker: wasted 500ms.
chrome.runtime.sendMessage({ action: 'triggerAction' });
setTimeout(loadFromStorage, 500);

// GOOD — the response is the signal that the write is durable.
const res = await chrome.runtime.sendMessage({ action: 'triggerAction' });
if (!res?.success) return showRetryState(res?.error);
await loadFromStorage();

Treat a missing or falsy response as failure, not success — a torn-down worker resolves sendMessage with undefined. The same rule covers any awaited teardown work behind an acknowledgement: if the handler reschedules an alarm, await the clear/create pair before responding, or the caller refreshes its UI from state that has not been rebuilt yet.

??, never ||, for numeric settings

0 is a legitimate value for an hour, a count, or an offset, and || throws it away. A user who sets a start hour of midnight gets the default instead.

js
const startHour = stored.startHour ?? DEFAULTS.startHour;   // 0 survives

chrome.storage read-modify-write is a lost update

get → mutate → set on the whole settings object races every other context (popup, worker, options page) writing the same key. Worse, if the object is absent from storage, code that spreads a local variable persists a partial settings record — and the next reader's stored || DEFAULTS keeps the truthy partial, so a missing nested key throws.

Re-read inside the write path, and rebuild over the defaults rather than over whatever snapshot you happen to be holding:

js
async function persistLastIndex(category, index) {
  const { settings } = await chrome.storage.local.get('settings');   // fresh read
  await chrome.storage.local.set({
    settings: {
      ...DEFAULTS,
      ...settings,
      enabledCategories: { ...DEFAULTS.enabledCategories, ...settings?.enabledCategories },
      lastIndices: { ...DEFAULTS.lastIndices, ...settings?.lastIndices, [category]: index },
    },
  });
}

Two things that snippet is doing deliberately:

  • Defaults-based, never partial. Every key a consumer indexes into exists, even on a first write after storage was cleared.
  • Nested objects merged explicitly. A shallow {...DEFAULTS} aliases DEFAULTS.enabledCategories — it is the same object, typically a module global shared by worker and popup. Mutating the stored copy later reaches back and rewrites your defaults for the rest of the process.

The cleanest version of this rule: make selection pure and persistence explicit. A function that picks a random item should return { item, category, index } and write nothing; the caller awaits the persist. Pure selection is trivially testable, and the write can no longer be silently skipped.

Share reminder delivery only when the side effects match

A "show something now" routine usually serves both a scheduled alarm (which must respect quiet hours / weekends) and a manual button (which must not). Do not fork into a second near-copy; take an explicit opt-out and default it to the safe value:

js
async function showReminder(skipTimeCheck = false) {
  if (!skipTimeCheck && !isWithinActiveHours(settings)) return;
  // ...
}

// alarm handler: showReminder();        → gated
// manual reminder: showReminder(true);  → schedule bypassed

Use the bypass only for a manual action that explicitly requests the same reminder delivery. It bypasses the schedule, not every policy: pause and active session checks need their own deliberate handling.

A catalog's "select this item" action has different side effects. Reusing showReminder(true) would send an unwanted notification and update random repeat-avoidance history. Give selection its own handler: validate integer category/item indices and bounds before reading session state, reject a valid future session deadline, then await only the selected-item write. Exact session expiry permits selection; use the deadline validation below.

Test the distinction at the handler boundary: a manual reminder works off-hours; a catalog selection writes the chosen item without notifying or changing repeat-avoidance history; invalid indices and an active session leave storage untouched. Sharing a pure lookup helper is useful; sharing an effectful pipeline is correct only when the requested effects match.

HTML input constraints are inert; validate in JS

min="0" max="23" on a number input is enforced only by form submission or an explicit checkValidity(). A popup that reads .value on a click handler gets none of it, and parseInt('') is NaN:

js
// BAD — NaN >= NaN is false, so this "range check" passes for a blank field.
const start = parseInt(startInput.value);
if (start >= end) return showError();

NaN then serializes through chrome.storage to null, gets replaced by the default on read (so the app looks fine), and renders as an empty field next time the popup opens — sticky corruption behind a "Settings saved ✓" toast. Out-of-range values are stored verbatim and can make an active-hours predicate true for every hour of the day.

js
function readHour(input, name) {
  const raw = input.value.trim();
  if (!/^\d+$/.test(raw)) throw new ValidationError(name);
  const n = Number(raw);
  if (!Number.isInteger(n) || n < 0 || n > 23) throw new ValidationError(name);
  return n;
}

Validate the whole string before conversion: parseInt('9.5', 10) and parseInt('9hours', 10) both return 9, which passes integer and range checks. Number('') returns 0, so conversion alone also accepts a blank as midnight. The digit check rejects those inputs while preserving a legitimate 0.

Validate in the shared save path, not per-field in the markup — and report the failure instead of showing success. Test valid boundaries 0 and 23, and reject blank, fractional, trailing-text, negative, and 24 inputs; every rejected save must leave storage untouched and show an error.

A stored deadline must be a usable Date, not just a number

Snooze/pause features persist an epoch-millisecond deadline and compare it to Date.now(). Storage hands back whatever was written, so validate on read:

js
const MAX_DATE_MS = 8.64e15;           // largest time a JS Date can represent
function readDeadline(raw) {
  return Number.isSafeInteger(raw) && Math.abs(raw) <= MAX_DATE_MS ? raw : null;
}
const paused = (d) => d !== null && d > Date.now();   // strict: expiry instant is "not paused"

A finite but oversized value (1e20) passes Number.isFinite, then new Date(raw) is Invalid Date and the popup renders "Paused until Invalid Date" forever. null/NaN/strings must read as "not paused", never as a deadline. Test the exact-expiry boundary (deadline === now is expired) and an over-range value.

A throw during DOMContentLoaded kills the whole popup

Popup init typically loads state and binds listeners in one handler. If the state load throws — say a partial settings object missing a nested key — the handler unwinds before addEventListener runs, and every button in the popup is dead with no visible error. Bind listeners first, then load state inside try/catch and degrade to defaults.

Notifications: stable ids replace, and openPopup can reject

Reusing one notification id means a new notification replaces the pending one — usually what you want, so state it deliberately rather than discovering it. In a click handler, clear the clicked id before awaiting chrome.action.openPopup(), and catch that call: it rejects when there is no active window to attach to.

Action buttons (buttons on a basic notification) are not rendered on every OS/Chrome combination. Treat them as a shortcut, never the only route: the body click must still reach every action, and a button handler such as snooze must re-check pause/session state itself when it reuses a code path that skips it.

Your chrome mock is part of the system under test

A hand-rolled chrome mock decides which bugs are reachable. Four failure modes, all of which produce a green suite over broken code:

Stubs leak across tests. jest.clearAllMocks() clears recorded calls but keeps implementations, so one test's sendMessage.mockResolvedValue(...) answers for every later test in the file — silently unhooking the real listener. Have the reset helper reinstall default implementations:

js
function resetAll() {
  jest.clearAllMocks();
  installDefaultImplementations(chrome);   // not just clearAllMocks()
}

A mock that drops async responses. If the fake sendMessage invokes listeners in a forEach and resolves responses[0], then any listener that returns true and responds later resolves to undefined — so every handler using the async pattern above appears to fail. Honor return true by resolving the promise the listener eventually fulfills. Until it does, a test needing a real round trip must invoke the listener directly (chrome.runtime.onMessage.addListener.mock.calls[0][0]).

Synchronous mock storage cannot detect a missing await. If the fake set mutates its backing object and returns an already-resolved promise, the write wins the microtask race whether or not the handler awaited it. To test ordering you must gate the write, then prove the handler is still pending:

js
let release;
const gate = new Promise((r) => { release = r; });
const realSet = chrome.storage.local.set.getMockImplementation();
chrome.storage.local.set.mockImplementation((items) =>
  items.settings ? gate.then(() => realSet(items)) : realSet(items));

const pending = handler({ action: 'save' }, {}, sendResponse);
for (let i = 0; i < 50; i++) await Promise.resolve();   // drain microtasks
expect(sendResponse).not.toHaveBeenCalled();            // fails if the await is missing
release();
await pending;
expect(sendResponse).toHaveBeenCalledWith({ success: true });

getMockImplementation() returns the default the reset helper installed, so this composes with the mock instead of replacing storage behavior.

For a multi-step side effect, gate the last promise the acknowledgement claims is complete, not merely an earlier step. Gating alarms.clear does not prove that alarms.create is awaited: this broken implementation still passes a clear-gated test while replying before the new alarm exists.

js
async function setupAlarm() {
  await chrome.alarms.clear('reminder');
  chrome.alarms.create('reminder', schedule); // BUG — floating promise
}

Gate create itself and assert both the response and the externally visible effect remain pending until release:

js
let releaseCreate;
const createGate = new Promise((r) => { releaseCreate = r; });
chrome.alarms.create.mockImplementation(() => createGate);

listener({ action: 'updateSettings' }, {}, sendResponse);
for (let i = 0; i < 50; i++) await Promise.resolve();
expect(sendResponse).not.toHaveBeenCalled();

releaseCreate();
for (let i = 0; i < 50; i++) await Promise.resolve();
expect(sendResponse).toHaveBeenCalledWith({ success: true });

Apply the same rule to notification creation, storage writes, and any helper whose name implies that a sequence has finished: the helper must await every nested promise before its caller can truthfully acknowledge success.

Fake timers are dropped the moment you go real. jest.useRealTimers() mid-test discards setSystemTime, so any new Date() afterward sees wall-clock time and a time-of-day branch follows whatever hour CI runs at — green by day, red at night. Stay on fake timers and drain microtasks in a loop instead of awaiting a real setTimeout.

Two smaller traps: throwing from chrome.notifications.create is the cheapest way to drive a handler's rejection path, but if the handler ever stops awaiting or catching it, Jest dies with an unhandled rejection and worker crashes rather than a named assertion failure — still red, just unreadable. And a tests/setup.js that replaces global.console swallows probe output even under --verbose; write to a temp file when you need to see inside a run.

Smoke-testing the unpacked popup in a real browser

Jest proves logic; a browser pass proves the popup renders and binds. Load the unpacked extension in a persistent-context browser driver and open chrome-extension://<id>/popup.html. Three traps:

  • Do not use string predicates such as page.wait_for_function("..."): they are evaluated with eval and violate the extension's CSP. Use locator assertions, or poll locator.inner_text() from the host script. Never relax the extension CSP to make verification pass.
  • Entrance animations wash out screenshots. A tab switch re-triggers a fade-in; wait for it to finish (or disable animations) before a full-page capture, and never pixel-diff regions that show a live clock or countdown.
  • Wait on the observable, not on a storage value that may not change. With one eligible item, a "pick another" action writes the same value back, so wait for the button label to return to idle instead.
  • A step that only records is not a guard. A smoke step that logs "what happened" (a reminder replaced the running exercise, the open popup still shows the old count) and then prints PASS keeps passing after the bug is fixed and after it regresses. Every PASS label must come from an assertion on the fixed behavior; keep genuinely exploratory observations under a different label that cannot turn the run green. Also keep asserted message text in one place shared with the UI: when validation copy changes (e.g. "hour" becomes "time"), a harness holding a literal copy fails with the old string and gets dismissed as noise. Never read a harness exit status as release sign-off until each step's assertion is known to fail when its fix is reverted.

PR-comment CI steps need two permissions

A workflow step that comments on a pull request via the issues API needs both issues: write and pull-requests: write, and such a step is usually gated if: github.event.action == 'opened' — so pushing another commit re-runs the workflow as synchronize, skips the step, and turns the job green without fixing anything. See permissioning-ci-workflows for the scope rules and how to re-verify an event-conditioned step.

Checklist

MV3 extension health:
- [ ] every onMessage handler that responds asynchronously returns true and replies on both paths
- [ ] callers await the response; no setTimeout used to "wait for" a write
- [ ] a missing/falsy sendMessage response is treated as failure
- [ ] numeric settings read with ?? (0 is valid), never ||
- [ ] storage writes re-read first and rebuild over DEFAULTS; nested objects merged explicitly
- [ ] selection/computation is pure; persistence is a separate awaited call
- [ ] manual reminder delivery bypasses only the intended schedule gate; alarms keep the default
- [ ] catalog selection validates indices and session state, without notification or repeat-history effects
- [ ] settings validated in JS (Number.isInteger + range), not by inert HTML min/max
- [ ] stored deadlines validated as safe integers within Date range; expiry uses strict `>`
- [ ] popup binds listeners before loading state; state load degrades to defaults
- [ ] chrome mock: reset reinstalls default implementations; async responses honored
- [ ] at least one test gates a write to prove the handler awaits it
- [ ] multi-step effects are tested by gating the terminal promise, not only an earlier step
- [ ] fake timers never swapped for real timers mid-test
- [ ] notification buttons are optional shortcuts; the body click reaches every action
- [ ] popup smoke test uses locator waits (no string predicates) and settled animations
- [ ] PR-comment workflow step has issues: write AND pull-requests: write

Câu hỏi thường gặp

Kỹ năng AI Building Browser Extensions làm được gì?

Builds and tests Manifest V3 browser extensions — service-worker message channels that survive teardown, chrome.storage read-modify-write safety, settings validation in the popup, and a Jest chrome mock that can actually fail. Use when writing or reviewing a background service worker, a popup that reads/writes chrome.storage, an extension's Jest suite, or debugging an extension whose UI silently stops responding.

Vì sao nên dùng Building Browser Extensions trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Building Browser Extensions là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Building Browser Extensions trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/wdm0006/python-skills/tree/main/skills/javascript/browser-extensions. TypingMind đọc tệp SKILL.md rồi cài đặt kỹ năng để bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Building Browser Extensions?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Building Browser Extensions với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Building Browser Extensions với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Building Browser Extensions có miễn phí không?

Có. Kỹ năng này được wdm0006 phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇