Keep your coding agent up to date with the latest web best practices
Release v0.0.173
github-actions[bot]18c2f84274f9
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 9bbf222..6455fbb 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -8,7 +8,7 @@"name": "modern-web-guidance","source": "./","description": "Keep your coding agent up to date with the latest web best practices",- "version": "0.0.172"+ "version": "0.0.173"}]}diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 934eb9a..f90be83 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "modern-web-guidance","description": "Keep your coding agent up to date with the latest web best practices",- "version": "0.0.172",+ "version": "0.0.173","author": {"name": "Google Chrome"}diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.jsonindex 59dcb97..f7a22f6 100644--- a/.cursor-plugin/plugin.json+++ b/.cursor-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "modern-web-guidance","description": "Modern Web Guidance is an agent skill and CLI tool designed to help AI coding agents build web applications using modern, secure, and high-performance APIs rather than outdated workarounds. Supported by the Google Chrome team, it injects expert-curated web platform best practices directly into an agent's context window to prevent the generation of bloated, legacy code.",- "version": "0.0.172",+ "version": "0.0.173","author": {"name": "Google Chrome"}diff --git a/gemini-extension.json b/gemini-extension.jsonindex 934eb9a..f90be83 100644--- a/gemini-extension.json+++ b/gemini-extension.json@@ -1,7 +1,7 @@{"name": "modern-web-guidance","description": "Keep your coding agent up to date with the latest web best practices",- "version": "0.0.172",+ "version": "0.0.173","author": {"name": "Google Chrome"}diff --git a/package.json b/package.jsonindex 066bae9..802ae3f 100644--- a/package.json+++ b/package.json@@ -3,7 +3,7 @@"displayName": "Modern Web Guidance","description": "Keep your agent up to date on the latest web best practices.","license": "Apache-2.0",- "version": "0.0.172",+ "version": "0.0.173","publisher": "GoogleChrome","repository": {"url": "https://github.com/GoogleChrome/modern-web-guidance-src"diff --git a/skills/chrome-extensions/SKILL.md b/skills/chrome-extensions/SKILL.mdindex 89046ad..a0a74a6 100644--- a/skills/chrome-extensions/SKILL.md+++ b/skills/chrome-extensions/SKILL.md@@ -6,11 +6,11 @@ description: >add-ons, or anything involving the Chrome Extensions API. Trigger on mentions of: 'Chromeextension', 'browser extension', 'manifest.json', 'content script', 'service worker' (inbrowser context), 'popup' (in browser extension context), 'side panel', 'chrome.* API',- 'declarativeNetRequest', 'omnibox', 'context menu' (in extension context), or any request- to build functionality that integrates with the Chrome browser UI. Also trigger for- publishing to the Chrome Web Store: 'publish extension', preparing an extension for- publishing, responding to a review rejection, writing permission justifications, or- drafting a privacy policy.+ 'declarativeNetRequest', 'omnibox', 'context menu' (in extension context), 'userScripts',+ 'user script', 'script manager', or any request to build functionality that integrates with+ the Chrome browser UI. Also trigger for publishing to the Chrome Web Store: 'publish+ extension', preparing an extension for publishing, responding to a review rejection, writing+ permission justifications, or drafting a privacy policy.---# Chrome Extensions@@ -350,7 +350,19 @@ chrome.desktopCapture.chooseDesktopMedia(['screen', 'window'], tab, (streamId) =**Note:** Prefer `chrome.tabCapture.getMediaStreamId()` for tab-only recording. Use `chrome.desktopCapture` only when the user should choose which screen/window to capture. See `references/extensions/media-capture.md`.-#### 18. `chrome.windows` has NO `.query()` method — use `getAll`, `getLastFocused`, or `getCurrent`+#### 18. User scripts: four non-obvious pitfalls++`chrome.userScripts` runs **user-provided code** at runtime. Use it for script managers and+user automation — not for extension-bundled scripts.++- **API throws on property access if not enabled.** Chrome 138+ requires the user to toggle "Allow User Scripts" on the extension's details page; Chrome < 138 requires Developer mode. Always call `isUserScriptsAvailable()` before any `chrome.userScripts.*` call and show an error UI when it returns false.+- **Registered scripts are cleared on extension update.** Persist configs in `chrome.storage`; re-register them in `runtime.onInstalled` for the `"update"` reason.+- **Messaging requires explicit opt-in.** Call `configureWorld({ messaging: true })` first; listen on `runtime.onUserScriptMessage`, not `runtime.onMessage`.+- **`ScriptSource` constraint:** each `js` entry must have exactly one of `code` or `file`. **`id` constraint:** cannot start with `_`.++See `references/extensions/user-scripts.md`.++#### 19. `chrome.windows` has NO `.query()` method — use `getAll`, `getLastFocused`, or `getCurrent`Unlike `chrome.tabs.query()`, the `chrome.windows` API does NOT have a `.query()` method.@@ -488,6 +500,7 @@ For detailed API patterns and publishing guidance, read the relevant file BEFORE| Storage | `references/extensions/storage.md` || Tab & window management | `references/extensions/tab-management.md` || Tab/desktop capture | `references/extensions/media-capture.md` |+| User scripts | `references/extensions/user-scripts.md` || Message passing | `references/extensions/message-passing.md` || Icons | `references/extensions/icons.md` || CHROMEWEBSTORE.md template | `references/webstore/chromewebstore-template.md` |@@ -517,6 +530,11 @@ Verify EVERY item before delivering:- [ ] Tab/desktop capture uses state locking to prevent double-start errors- [ ] `chrome.desktopCapture.chooseDesktopMedia` passes `targetTab` with `tabs` permission- [ ] `chrome.windows` calls use `getAll`/`getLastFocused`/`getCurrent` — NOT `.query()` (it doesn't exist)+- [ ] `chrome.userScripts` availability checked before use (API throws if user hasn't enabled it)+- [ ] User script configs persisted in `chrome.storage` and restored on `runtime.onInstalled` `"update"` reason+- [ ] `configureWorld({ messaging: true })` called before user scripts send messages; listening on `onUserScriptMessage` not `onMessage`+- [ ] `ScriptSource` entries each have exactly one of `code` or `file` (not both, not neither)+- [ ] User script `id` values do not start with underscore- [ ] `sidePanel.setPanelBehavior` uses `openPanelOnActionClick` — NOT `openPanelOnActionIconClick`- [ ] Error handling on all async operations- [ ] `host_permissions` scoped to specific domains (not `<all_urls>` unless needed)diff --git a/skills/chrome-extensions/references/extensions/user-scripts.md b/skills/chrome-extensions/references/extensions/user-scripts.mdnew file mode 100644index 0000000..ec9dff8--- /dev/null+++ b/skills/chrome-extensions/references/extensions/user-scripts.md@@ -0,0 +1,273 @@+# User Scripts API++The `chrome.userScripts` API lets extensions run **arbitrary code provided by the user** at+runtime — code that cannot be shipped as part of the extension package. This is fundamentally+different from content scripts (which are bundled with the extension) and `chrome.scripting`+(which executes extension-owned code programmatically).++**Use userScripts when:** you are building a script manager, custom automation tool, or any+feature where the user supplies JavaScript that should run on web pages.+**Use content scripts when:** the injected code is written by you and ships with the extension.+**Use `chrome.scripting.executeScript` when:** you need one-off execution of known, extension-owned code.++## Manifest++```json+{+ "manifest_version": 3,+ "minimum_chrome_version": "120",+ "permissions": ["userScripts"],+ "host_permissions": ["https://example.com/*"]+}+```++- `"userScripts"` permission is required — without it `chrome.userScripts` is undefined.+- `host_permissions` must cover the sites where scripts will be injected.++## User Enablement — CRITICAL++**The `chrome.userScripts` API requires explicit user opt-in. Without it, the API throws on+property access.** Behavior differs by Chrome version:++| Chrome version | Requirement |+|----------------|-------------|+| < 138 | User must enable **Developer mode** at `chrome://extensions` |+| ≥ 138 | User must toggle **"Allow User Scripts"** on the extension's details page |++```js+// ❌ BROKEN — crashes if user hasn't enabled the API+await chrome.userScripts.register([{ id: 'foo', matches: [...], js: [...] }]);+// TypeError: Cannot read properties of undefined++// ✅ CORRECT — always guard before any chrome.userScripts.* call+function isUserScriptsAvailable() {+ try {+ chrome.userScripts; // throws if not enabled+ return true;+ } catch {+ return false;+ }+}++if (!isUserScriptsAvailable()) {+ document.getElementById('warning').style.display = 'block';+ document.getElementById('main-ui').style.display = 'none';+ return;+}+```++## Execution Worlds++| World | Constant | Behavior |+|-------|----------|----------|+| **USER_SCRIPT** (default) | `ExecutionWorld.USER_SCRIPT` | Isolated from host page JS; exempt from page CSP |+| **MAIN** | `ExecutionWorld.MAIN` | Shares JS context with the host page; can access page variables |++Use `USER_SCRIPT` (the default) for safety. Use `MAIN` only when the user's script explicitly+needs to interact with the host page's JavaScript environment.++Chrome 133+ supports multiple isolated worlds via `worldId`, letting different user scripts+run in separate execution environments without interfering with each other.++## Registering Scripts (Persistent)++`register()` / `update()` / `getScripts()` / `unregister()` manage scripts that persist across+page loads and browser sessions. Registered scripts survive the service worker being terminated.++```js+// ❌ BROKEN — both code and file specified (ScriptSource must have exactly one)+await chrome.userScripts.register([{+ id: 'my-script',+ matches: ['https://example.com/*'],+ js: [{ code: 'alert(1)', file: 'user-script.js' }] // Error: specify code OR file, not both+}]);++// ❌ BROKEN — id starts with underscore (reserved prefix)+await chrome.userScripts.register([{ id: '_my-script', ... }]);+// Error: User script IDs must not start with '_'++// ✅ CORRECT — register from a file bundled with the extension+await chrome.userScripts.register([{+ id: 'my-user-script',+ matches: ['https://example.com/*'],+ js: [{ file: 'user-script.js' }],+ runAt: 'document_idle' // optional, this is the default+}]);++// ✅ CORRECT — register inline code supplied by the user+await chrome.userScripts.register([{+ id: 'my-user-script',+ matches: ['https://example.com/*'],+ js: [{ code: userProvidedCode }]+}]);+```++Always check before calling `register()` vs `update()` — registering an already-existing ID+throws an error:++```js+const existing = await chrome.userScripts.getScripts({ ids: ['my-user-script'] });+if (existing.length > 0) {+ await chrome.userScripts.update([{ id: 'my-user-script', js: [{ code: updatedCode }] }]);+} else {+ await chrome.userScripts.register([{+ id: 'my-user-script',+ matches: ['https://example.com/*'],+ js: [{ code: userProvidedCode }]+ }]);+}++// Remove a specific script+await chrome.userScripts.unregister({ ids: ['my-user-script'] });++// Remove all registered user scripts+await chrome.userScripts.unregister();+```++## Persistence: Restore on Extension Update++**Registered user scripts are cleared when the extension updates.**++```js+// ❌ BROKEN — scripts registered once at install time are lost on every update+chrome.runtime.onInstalled.addListener(({ reason }) => {+ if (reason === 'install') {+ chrome.userScripts.register([{ id: 'foo', matches: [...], js: [...] }]);+ // After the next extension update, 'foo' is gone — no re-registration+ }+});++// ✅ CORRECT — persist configs in storage, restore on both install and update+chrome.runtime.onInstalled.addListener(async ({ reason }) => {+ if (reason === chrome.runtime.OnInstalledReason.UPDATE) {+ const { scripts = {} } = await chrome.storage.local.get('scripts');+ for (const s of Object.values(scripts)) {+ await chrome.userScripts.register([s]).catch(() => {});+ }+ }+});+```++Save the full script config (id, matches, js) to `chrome.storage` whenever the user saves+a script, so it can be restored after an update.++## One-Off Injection (Chrome 135+)++`execute()` injects a script immediately into a specific tab/frame without registering it. It+does not persist across page loads.++```js+// Requires Chrome 135++const results = await chrome.userScripts.execute({+ target: { tabId: tabId },+ js: [{ code: userProvidedCode }],+ world: 'USER_SCRIPT' // optional, default+});++for (const result of results) {+ if (result.error) {+ console.error('Injection failed in frame', result.frameId, result.error);+ } else {+ console.log('Result from frame', result.frameId, result.result);+ }+}+```++Guard for Chrome 135+ availability:++```js+if (typeof chrome.userScripts.execute === 'function') {+ await chrome.userScripts.execute({ ... });+} else {+ // Fall back to register-based approach+}+```++## Messaging from User Scripts++User scripts run in the `USER_SCRIPT` world which has no access to `chrome.runtime` by+default. Messaging requires an explicit opt-in.++```js+// ❌ BROKEN — messaging not enabled; chrome.runtime is undefined in the user script+// sw.js+chrome.runtime.onMessage.addListener((msg) => { ... }); // Never fires from user scripts++// user script code (running in the page)+chrome.runtime.sendMessage({ type: 'hello' }); // TypeError: chrome is not defined++// ✅ CORRECT — opt in first, then use the dedicated listener+// sw.js (run once, e.g. on install)+await chrome.userScripts.configureWorld({ messaging: true });++// sw.js — listen on the dedicated handler, not onMessage+chrome.runtime.onUserScriptMessage.addListener((message, sender, sendResponse) => {+ sendResponse({ ok: true });+ return true; // keep channel open for async responses+});++// user script code — chrome.runtime is now available+chrome.runtime.sendMessage({ type: 'FROM_USER_SCRIPT', data: 42 });+```++For long-lived connections use `chrome.runtime.onUserScriptConnect` (analogous to+`runtime.onConnect` for content scripts).++Chrome 133+ supports per-world messaging with `worldId`:++```js+await chrome.userScripts.configureWorld({ worldId: 'my-world', messaging: true });+```++## `configureWorld()` — CSP and Messaging++```js+await chrome.userScripts.configureWorld({+ csp: "script-src 'self'", // custom CSP for the world+ messaging: true // enable chrome.runtime messaging+});++// Chrome 133+: configure a named world+await chrome.userScripts.configureWorld({+ worldId: 'my-world',+ messaging: true+});++// Chrome 133+: reset a world's configuration+await chrome.userScripts.resetWorldConfiguration('my-world');++// Chrome 133+: list all world configurations+const configs = await chrome.userScripts.getWorldConfigurations();+```++## Complete Script Manager Pattern++```js+// options.js — save user's script and (re)register it+async function saveScript(id, matches, code) {+ // Persist the config so we can restore it after extension updates+ const { scripts = {} } = await chrome.storage.local.get('scripts');+ scripts[id] = { id, matches, js: [{ code }] };+ await chrome.storage.local.set({ scripts });++ // Register or update the live script+ const existing = await chrome.userScripts.getScripts({ ids: [id] });+ if (existing.length > 0) {+ await chrome.userScripts.update([{ id, matches, js: [{ code }] }]);+ } else {+ await chrome.userScripts.register([{ id, matches, js: [{ code }] }]);+ }+}+```++## Key Differences from Content Scripts++| | Content Scripts | userScripts |+|--|-----------------|-------------|+| Code source | Bundled with extension | Provided by user at runtime |+| Persistence | Automatic (manifest) | Manual (register + restore on update) |+| Arbitrary code | No | Yes |+| User opt-in | No | Yes (Developer Mode / Allow User Scripts) |+| Messaging | `runtime.sendMessage` | `runtime.onUserScriptMessage` (after `configureWorld`) |+| CSP exemption | Yes | Yes (USER_SCRIPT world) |+| Multiple worlds | No | Yes (Chrome 133+ with `worldId`) |diff --git a/skills/modern-web-guidance/guides/user-experience/apply-webgl-shaders.md b/skills/modern-web-guidance/guides/user-experience/apply-webgl-shaders.mdindex b69fcff..ba42b5e 100644--- a/skills/modern-web-guidance/guides/user-experience/apply-webgl-shaders.md+++ b/skills/modern-web-guidance/guides/user-experience/apply-webgl-shaders.md@@ -50,14 +50,11 @@ observer.observe(canvas, options);```jscanvas.onpaint = () => {if (gl.texElementImage2D) {- gl.texElementImage2D(- gl.TEXTURE_2D,- 0,- gl.RGBA,- gl.RGBA,- gl.UNSIGNED_BYTE,- uiElement,- );+ try {+ gl.texElementImage2D(gl.TEXTURE_2D, gl.RGBA8, uiElement);+ } catch (err) {+ console.error('texElementImage2D copy failed:', err);+ }}};```@@ -161,14 +158,11 @@ targetHTMLElement.style.transform = computedTransform.toString();canvas.onpaint = () => {// 1. Update texture with HTML contentif (gl.texElementImage2D) {- gl.texElementImage2D(- gl.TEXTURE_2D,- 0,- gl.RGBA,- gl.RGBA,- gl.UNSIGNED_BYTE,- uiElement,- );+ try {+ gl.texElementImage2D(gl.TEXTURE_2D, gl.RGBA8, uiElement);+ } catch (err) {+ console.error('texElementImage2D copy failed:', err);+ }}// ... Render your 3D scene here, calculating htmlElementMVP matrix ...diff --git a/skills/modern-web-guidance/guides/user-experience/export-html-media-from-canvas.md b/skills/modern-web-guidance/guides/user-experience/export-html-media-from-canvas.mdindex 8bb1806..b985a97 100644--- a/skills/modern-web-guidance/guides/user-experience/export-html-media-from-canvas.md+++ b/skills/modern-web-guidance/guides/user-experience/export-html-media-from-canvas.md@@ -61,14 +61,11 @@ canvas.onpaint = () => {```jscanvas.onpaint = () => {if (gl.texElementImage2D) {- gl.texElementImage2D(- gl.TEXTURE_2D,- 0,- gl.RGBA,- gl.RGBA,- gl.UNSIGNED_BYTE,- uiElement,- );+ try {+ gl.texElementImage2D(gl.TEXTURE_2D, gl.RGBA8, uiElement);+ } catch (err) {+ console.error('texElementImage2D copy failed:', err);+ }}};```@@ -77,9 +74,19 @@ canvas.onpaint = () => {```jscanvas.onpaint = () => {- root.device.queue.copyElementImageToTexture(valueElement, 512, 128, {- texture: targetTexture,- });+ if (root.device.queue.copyElementImageToTexture) {+ try {+ const sourceDict = { source: valueElement };+ const destDict = {+ destination: { texture: targetTexture },+ width: 512,+ height: 128,+ };+ root.device.queue.copyElementImageToTexture(sourceDict, destDict);+ } catch (err) {+ console.error('copyElementImageToTexture copy failed:', err);+ }+ }};```diff --git a/skills/modern-web-guidance/guides/user-experience/expose-canvas-content-to-browser-features.md b/skills/modern-web-guidance/guides/user-experience/expose-canvas-content-to-browser-features.mdindex e46971a..4f1eb2c 100644--- a/skills/modern-web-guidance/guides/user-experience/expose-canvas-content-to-browser-features.md+++ b/skills/modern-web-guidance/guides/user-experience/expose-canvas-content-to-browser-features.md@@ -62,14 +62,11 @@ canvas.onpaint = () => {```jscanvas.onpaint = () => {if (gl.texElementImage2D) {- gl.texElementImage2D(- gl.TEXTURE_2D,- 0,- gl.RGBA,- gl.RGBA,- gl.UNSIGNED_BYTE,- uiElement,- );+ try {+ gl.texElementImage2D(gl.TEXTURE_2D, gl.RGBA8, uiElement);+ } catch (err) {+ console.error('texElementImage2D copy failed:', err);+ }}};```@@ -78,9 +75,19 @@ canvas.onpaint = () => {```jscanvas.onpaint = () => {- root.device.queue.copyElementImageToTexture(valueElement, 512, 128, {- texture: targetTexture,- });+ if (root.device.queue.copyElementImageToTexture) {+ try {+ const sourceDict = { source: valueElement };+ const destDict = {+ destination: { texture: targetTexture },+ width: 512,+ height: 128,+ };+ root.device.queue.copyElementImageToTexture(sourceDict, destDict);+ } catch (err) {+ console.error('copyElementImageToTexture copy failed:', err);+ }+ }};```@@ -247,14 +254,11 @@ targetHTMLElement.style.transform = computedTransform.toString();canvas.onpaint = () => {// 1. Update texture with HTML contentif (gl.texElementImage2D) {- gl.texElementImage2D(- gl.TEXTURE_2D,- 0,- gl.RGBA,- gl.RGBA,- gl.UNSIGNED_BYTE,- uiElement,- );+ try {+ gl.texElementImage2D(gl.TEXTURE_2D, gl.RGBA8, uiElement);+ } catch (err) {+ console.error('texElementImage2D copy failed:', err);+ }}// ... Render your 3D scene here, calculating htmlElementMVP matrix ...@@ -312,9 +316,17 @@ targetHTMLElement.style.transform = computedTransform.toString();canvas.onpaint = () => {// 1. Copy HTML content to textureif (device.queue.copyElementImageToTexture) {- device.queue.copyElementImageToTexture(uiElement, width, height, {- texture: targetTexture,- });+ try {+ const sourceDict = { source: uiElement };+ const destDict = {+ destination: { texture: targetTexture },+ width: width,+ height: height,+ };+ device.queue.copyElementImageToTexture(sourceDict, destDict);+ } catch (err) {+ console.error('copyElementImageToTexture copy failed:', err);+ }}// 2. Sync DOM position (same matrix math as WebGL)diff --git a/skills/modern-web-guidance/guides/user-experience/interactive-content-in-3d-scenes.md b/skills/modern-web-guidance/guides/user-experience/interactive-content-in-3d-scenes.mdindex 74b8b33..89ca5c5 100644--- a/skills/modern-web-guidance/guides/user-experience/interactive-content-in-3d-scenes.md+++ b/skills/modern-web-guidance/guides/user-experience/interactive-content-in-3d-scenes.md@@ -54,14 +54,11 @@ observer.observe(canvas, options);```jscanvas.onpaint = () => {if (gl.texElementImage2D) {- gl.texElementImage2D(- gl.TEXTURE_2D,- 0,- gl.RGBA,- gl.RGBA,- gl.UNSIGNED_BYTE,- uiElement,- );+ try {+ gl.texElementImage2D(gl.TEXTURE_2D, gl.RGBA8, uiElement);+ } catch (err) {+ console.error('texElementImage2D copy failed:', err);+ }}};```@@ -70,9 +67,19 @@ canvas.onpaint = () => {```jscanvas.onpaint = () => {- root.device.queue.copyElementImageToTexture(valueElement, 512, 128, {- texture: targetTexture,- });+ if (root.device.queue.copyElementImageToTexture) {+ try {+ const sourceDict = { source: valueElement };+ const destDict = {+ destination: { texture: targetTexture },+ width: 512,+ height: 128,+ };+ root.device.queue.copyElementImageToTexture(sourceDict, destDict);+ } catch (err) {+ console.error('copyElementImageToTexture copy failed:', err);+ }+ }};```@@ -199,14 +206,11 @@ if ('requestPaint' in HTMLCanvasElement.prototype) {canvas.onpaint = () => {// 1. Update texture with HTML contentif (gl.texElementImage2D) {- gl.texElementImage2D(- gl.TEXTURE_2D,- 0,- gl.RGBA,- gl.RGBA,- gl.UNSIGNED_BYTE,- uiElement,- );+ try {+ gl.texElementImage2D(gl.TEXTURE_2D, gl.RGBA8, uiElement);+ } catch (err) {+ console.error('texElementImage2D copy failed:', err);+ }}// ... Render your 3D scene here, calculating htmlElementMVP matrix ...@@ -264,9 +268,17 @@ if ('requestPaint' in HTMLCanvasElement.prototype) {canvas.onpaint = () => {// 1. Copy HTML content to textureif (device.queue.copyElementImageToTexture) {- device.queue.copyElementImageToTexture(uiElement, width, height, {- texture: targetTexture,- });+ try {+ const sourceDict = { source: uiElement };+ const destDict = {+ destination: { texture: targetTexture },+ width: width,+ height: height,+ };+ device.queue.copyElementImageToTexture(sourceDict, destDict);+ } catch (err) {+ console.error('copyElementImageToTexture copy failed:', err);+ }}// 2. Sync DOM position (same matrix math as WebGL)