Google Chrome 团队发布 Modern Web Guidance,让编码智能体改用现代 Web 原生能力
Show HN: Get your coding agent off ~2019 JavaScript, onto modern web primitives
Google Chrome 联合 Microsoft Edge、Mozilla Firefox 和 MDN 团队推出 Modern Web Guidance,一套嵌入编码智能体的技能包,通过 CLI 检索约 250 项现代 Web 特性指南,引导智能体避开 2019 年前后的旧写法。
译文尚不完整,完整内容请切换到原文。
Modern Web Guidance 是一组技能,可将 Web 平台专业知识、最佳实践和浏览器兼容性数据直接嵌入你的编码代理中。它有助于引导你的编码代理远离旧有模式,转而采用能够发挥现代 Web 平台强大能力的解决方案。
由 Google Chrome、Microsoft Edge、Mozilla Firefox 和 MDN 团队以及 Web 开发社区共同维护。
快速开始
npx modern-web-guidance@latest install
此命令会运行一个交互式向导来安装 Modern Web Guidance。请参阅下方的替代安装方法。
试用(无需安装)
# Search for relevant guides npx modern-web-guidance@latest search "animate a dialog modal backdrop" # Retrieve a guide by ID npx modern-web-guidance@latest retrieve "animate-to-from-top-layer" # Scan a codebase for legacy patterns to modernize npx modern-web-guidance@latest legacy-scan .
为什么?
编码代理常常默认采用较旧的模式,因为 LLM 训练数据中包含大量遗留代码。这往往导致它们为那些如今已有原生、高性能 Web 平台解决方案的任务生成臃肿的 JavaScript。
即使模型知道某个 API 存在,它通常也缺乏生产级代码所需的丰富真实世界现代实现模式。
Modern Web Guidance 弥合了这一差距。 我们技能的 CLI 会将有针对性的、由专家精心策划的指南直接返回到你的代理上下文窗口中,重点关注:
- 现代浏览器 API:帮助模型正确构建它们经常误用的 API。
- 性能与无障碍:优先使用可由浏览器优化并内置无障碍支持的平台级 API。
- 负责任的回退方案:引导模型使用合理、轻量的回退方案,而不是沉重的 polyfill 或遗留库。
包含哪些内容?
我们涵盖了 Web 平台过去几年的新功能,直至最前沿。这些指南设计为令牌高效;我们运行评估,以便修剪模型已经知道的最低共同标准内容。
核心领域
🎨 用户体验流畅的视觉状态(View Transitions、进入/退出动画、视差滚动、CSS |
📐 CSS 布局现代布局系统(容器查询、 |
⚡ 性能速度优化(即时预加载、Interaction to Next Paint (INP) 诊断,以及通过 |
📝 表单与 UI原生组件(用于工具提示的 Anchor Positioning、Popover API、对话框、 |
♿ 无障碍重要考虑因素(屏幕阅读器和键盘可操作性、内容导航和可发现性)。 |
🤖 内置 AI本地客户端模型(原生翻译、摘要和语言检测 API)。 |
查看示例:navigation-drawer 指南。
完整列表
250 项现代 Web 功能
CSS 与布局(140 项功能)
HTML 与 DOM(36 项特性)
JavaScript 与 API(74 项特性)
203 个真实世界的开发者用例
无障碍
- accessible-error-announcement:将程序化无障碍状态(如 aria-invalid)与视觉上的 :user-invalid 状态同步,确保屏幕阅读器用户仅在交互后收到错误反馈,与视觉体验保持一致。
- accessible-generated-content:以保持无障碍的方式使用 CSS 生成内容(
::before/::after),包括为装饰性内容提供替代文本。 - respect-os-text-scale:遵循操作系统的页面文字缩放偏好,使字体大小、布局和基于 rem 的度量跟随用户的无障碍设置。
内置 AI
- language-detection:检测用户生成内容或站点已有内容的语言。
- language-model:使用 Prompt API 在浏览器中运行设备端自然语言推理,支持流式输出、结构化 JSON 响应和多轮会话管理。
- summarizer:使用设备端 Summarizer API 对文本内容进行摘要。
- translator:使用设备端 Translator API 在语言之间翻译文本。
CSS
- animate-to-intrinsic-sizes:将交互式组件(如手风琴、菜单和可展开卡片)平滑地动画过渡到其自然尺寸并从中恢复。
- atrule-support-conditionals:仅当浏览器支持某个 at-rule 时,才有条件地应用某些 CSS 规则或声明。
- calculate-with-intrinsic-sizes:基于元素的固有尺寸计算其大小,同时确保其符合给定的设计约束。
- child-state-based-styling:构建一个根据其某个子元素的状态改变样式的组件。例如,根据主题切换开关是否被选中来以浅色或深色模式渲染的组件。
- content-based-styling:构建一个根据是否包含特定子元素来改变布局的组件。例如,如果组件包含图片,则使用多列布局,否则默认使用单列布局。
- css:面向现代 CSS 架构的实践导向指南,包括层叠、选择器、作用域、嵌套和设计令牌。在编写样式或管理设计系统时使用本指南。
- css-layout:现代 CSS 布局,如 flexbox、grid、subgrid、容器查询、锚点定位和固有尺寸。在构建响应式 UI 组件或页面布局时使用此技能。
- design-token-reactivity:定义高阶设计令牌,例如密度模式(紧凑、舒适、宽松)或主题,并让后代组件以适合组件自身的方式直接响应变化。
- dynamic-sibling-styling:创建动态的视觉频谱或布局排列,使其自动适应组内元素的数量。
- fluid-scaling:根据父容器尺寸平滑缩放字号、间距和媒体尺寸等项目,而不是使用固定断点
- individual-transform-properties:在单个元素上独立于其他 transform 属性,对各个 CSS transform 属性(例如 translate、rotate、scale)进行动画或覆盖。
- overflow-clipping-control:调整元素可见的裁剪边界,使其与内容边缘、内边距边缘或边框边缘对齐——或与其中任一者保持指定偏移——从而对内容裁剪方式提供更精细的控制。
- reduce-style-repetition:通过将复杂或动态的样式逻辑封装为可复用函数(例如根据一组输入参数计算渐变的函数),减少过度的样式重复。
- responsive-design:构建可适应容器和视口尺寸的 UI,包括容器查询、动态视口单位、宽高比和响应式排版。
- selector-atrule-combinations:基于选择器与条件 @ 规则的交叉或并集来定位元素,同时尽量减少重复。
- size-aware-styling:构建一个组件,其样式可以有条件地取决于自身的宽度或高度,而不是视口的宽度或高度。例如,一个卡片组件可以根据自身大小改变布局,或者一个行动号召按钮可以根据自身宽度有条件地显示辅助文本。
- style-parent-with-has:当表单字段(例如标签或字段集)无效时,为其父元素设置样式。
- usage-aware-component-variations:使用 CSS 容器样式查询,构建基于语义上下文调整视觉逻辑的组件。
forms
- animated-select-picker:创建一个自定义 select 组件,其下拉菜单带有动画。例如,菜单淡入或滑入视图,或者选项在被选中时播放动画。
- autofill-address-form:构建一个具有正确 autocomplete 属性和自动填充支持的地址表单。
- autofill-highlight-inputs:自定义已被自动填充且用户尚未编辑的表单字段的样式
- autofill-payment-form:构建一个支付表单,使用正确的 autocomplete 值收集卡片详细信息,并支持自动填充。
- autofill-sign-in-form:构建一个具有正确 autocomplete 值和自动填充支持的登录表单。
- autofill-sign-up-form:构建一个具有正确 autocomplete 值和自动填充支持的注册表单。
- brand-consistent-forms:让复选框、单选按钮、范围滑块和进度条与站点的调色板相匹配,而无需将它们替换为自定义组件。
- branded-select-styling:创建自定义 select 元素,使其按钮、选择器、箭头图标和勾选标记都与你的品牌或设计系统的字体、颜色、间距和边框处理无缝匹配。
- custom-select-picker-layouts:创建自定义 select 选择器,让选项以独特或有趣的方式定位,而不是传统的堆叠选项列表。
- form-fields-automatically-fit-contents:允许表单字段随用户输入而增大和缩小,例如当用户输入或选择不同选项时。应用最大和最小尺寸限制,创建符合页面设计的动态响应式表单字段。
- ime-safe-enter-submit:在文本域和单行输入框(聊天、搜索、内联重命名)中实现回车提交,对 IME(输入法编辑器)用户安全,防止提交不完整的文本。
- required-field-feedback:仅在用户交互之后,为被跳过或留空的必填表单字段提供错误消息,以避免先发制人的错误,并确保反馈及时且与用户流程上下文相关。
- rich-media-picker:创建自定义 select 组件,其选项可以包含复杂的 HTML 格式(例如图片、图标和其他富格式),而不仅仅是纯文本。
- select-menu-interaction:仅在用户与控件交互之后,验证 select 菜单中已选择了非默认选项。
- slider:为原生范围滑块设置自定义轨道、滑块、填充和焦点状态的样式,同时保留原生功能和可访问性。
- sms-otp-form:通过自动提取代码和可访问的表单输入,验证用户电话号码和通过 SMS 发送的一次性密码。
- switch:使用原生 HTML switch 属性构建可访问的开关,在不支持时回退到样式化的复选框。
- validate-input-after-interaction:仅在用户完成初始交互后显示表单字段验证反馈(例如密码复杂度或电子邮件格式要求),避免在页面加载时或用户输入时过早出现错误。
html
- accessible-web-components:通过 ElementInternals ARIA mixin 设置角色和 ARIA 状态,使用 delegatesFocus 管理焦点,并将 ARIA 关系保持在单个 shadow root 内,使自定义元素默认可访问。
- custom-elements:定义、注册和管理自主自定义元素的生命周期,涵盖构造函数规则、生命周期回调、升级时机、属性/特性反射和命名约定。
- form-associated-custom-elements:通过 formAssociated 和 ElementInternals 使自定义控件原生参与表单,提交自己的值,与约束验证集成,并对重置、禁用和状态恢复做出反应。
- prerendering-custom-elements:服务器渲染自定义元素,然后就地水合,无需重新渲染或出现无样式内容闪烁。
- shadow-dom:使用 Shadow DOM 封装组件的 DOM 和样式,通过 HTML 模板高效构建树结构,并使用插槽投射使用方内容。
- styling-web-components:使用 :host 选择器、继承属性和自定义属性进行主题化、::slotted 和 ::part,以及组件内部的级联层和容器查询,实现跨影子边界的样式设置。
- web-components:编写和使用 Web Components 的入门指南与横切原则,涵盖自定义元素、Shadow DOM、模板和插槽、声明式 Shadow DOM、跨影子边界的样式设置、表单关联自定义元素以及无障碍要求。在构建可复用 UI 组件、设计系统或服务端渲染的自定义元素时,请使用本指南。
js
- calculate-event-differentials:计算日期和时间之间已流逝或剩余的时间,平衡时长单位,并使用 Temporal.Duration 和 Intl.DurationFormat 格式化人类可读的本地化时长。
- capture-location-agnostic-data:使用 Temporal Plain 类型对与位置无关的日历日期、挂钟时间、部分日期(循环生日、信用卡到期日)以及循环月度间隔进行建模,避免时区漂移。
- coordinate-global-events:通过将未来的会议或事件显式绑定到地理 IANA 时区来安排它们,使事件时间无论夏令时(DST)转换、时钟变更期间的“跳过”或“重复”小时如何都保持准确。
- sort-high-precision-timestamps:使用 Temporal.Instant 解析、排序和测量亚毫秒或纳秒级 ISO 8601 时间戳之间的间隔,避免 Date 截断冲突。
- support-global-calendar-systems:为国际用户准确显示和计算非公历日历系统(例如伊斯兰历、希伯来历或中国农历)中的日期。
performance
- batch-analytics-events:对多个分析、遥测和 Core Web Vitals 事件进行防抖和批处理,合并到单个信标中,以最大限度地减少网络争用并降低服务器负载,同时仍提供实时更新。
- break-up-long-tasks:拆分繁重的同步处理(复杂计算和/或长循环)或 DOM 更新,以改善 Interaction to Next Paint(INP)响应能力,并让浏览器处理用户输入和重绘屏幕。
- calculate-total-foreground-time:计算用户实际查看页面的总时间,排除标签页处于后台的时段。
- conditional-async-dependencies:有条件地加载或初始化异步依赖项(例如为缺失的 Web 特性导入 polyfill),而无需在页面的所有脚本依赖项之间进行复杂的编排。
- defer-rendering-heavy-content:通过推迟渲染任何用户不能立即看到的内容,减少内容密集型网页(例如具有长信息流、大量文章或复杂仪表板的页面)的渲染时间。
- defer-work-until-scroll-ends:将 DOM 更新、数据获取、分析跟踪或布局重算等开销较大的操作推迟到滚动结束后再执行,以保持流畅的滚动性能。
- deliver-optimized-decorative-images:通过同时提供下一代图片格式(如 AVIF 或 WebP)以及多种像素密度(如 1x 和 2x),让浏览器能够根据用户设备的性能动态协商文件大小与视觉质量的最佳组合,从而交付经过优化的装饰性图片(如背景、UI 图标或复杂遮罩)。
- deprioritize-background-fetches:降低使用 Fetch API 发起的后台数据获取的优先级,以避免与用户发起的请求产生网络争用。
- detect-initial-visibility-state:可靠地判断页面最初是否在后台加载,即使在脚本于用户将页面切换到前台之后才异步加载的情况下也能判断。
- efficient-background-processing:当组件不在屏幕上时暂停后台 JavaScript 执行(如
<canvas>动画、WebGL 渲染或高频 WebSocket 数据轮询),并在其滚动回视野时及时恢复,从而节省系统资源和电池续航。 - faster-spa-view-transitions:通过保留单页应用(SPA)中先前访问过的视图的结构化 DOM 状态,而不是在每次导航时销毁并重建它们,实现更快速地切换回这些视图。
- flicker-free-client-side-ab-testing:使用客户端 JavaScript 修改或注入 HTML、CSS 和 JavaScript 来交付并渲染 A/B 测试、多变量测试或其他实验,且不会先显示原始内容再闪烁或闪动切换为实验内容。
- full-session-analytics:可靠地跟踪用户整个页面访问期间的分析数据、Core Web Vitals、错误和遥测数据,并将数据发送推迟到用户离开页面时。
- identify-heavy-scripts:识别导致长动画帧的最主要脚本
- identify-inp-causes:识别运行缓慢的 JavaScript 以及其他导致 Interaction to Next Paint(INP)响应性不佳的原因。
- improve-next-page-load-performance:通过预取或预渲染用户接下来可能访问的页面来改善页面加载性能。
- interaction-paint-timing:测量用户交互和客户端导航在屏幕上渲染出新的内容更新所需的时间。
- interactions-in-complex-layouts:通过避免在复杂布局(如数据密集型仪表板或电子表格式网格)中重新计算布局,使交互更迅捷、更灵敏(降低 Interaction to Next Paint(INP)分数)。
- lazy-load-video-and-audio:推迟下载屏幕外的视频和音频资源(包括视频海报图片和预加载的媒体数据),直到媒体播放器接近视口,以节省带宽并减少初始页面加载期间的网络争用。
- optimize-image-priority:优化 Largest Contentful Paint (LCP) 候选图片的加载优先级,并降低非关键图片的优先级,以减少关键资源的加载延迟。
- optimize-preload-priority:优化预加载内容的相对优先级,以减少关键资源的加载延迟。
- optimize-script-priority:优化脚本的加载优先级,提升关键异步脚本的优先级,并降低非必要脚本或位于 body 末尾脚本的优先级,以改善加载顺序并减少延迟。
- out-of-order-html-streaming:以声明式方式更新页面,内容可稍后流式传输到同一 HTML 文档中,或通过命令式 JavaScript API 更新。
- resolution-optimized-pseudo-elements: Use resolution-optimized images in CSS pseudo-elements (such as
::beforeand::after) to reduce the number of DOM nodes. - schedule-tasks-by-priority: Schedule tasks with different priorities to ensure critical work runs first while background work is deferred.
privacy
- privacy: Action-oriented guidelines for web developers to implement privacy by design, data minimization, third-party audits, and secure data handling. Use this skill when designing applications, integrating third-party services, handling user data, or configuring security headers.
pwa
- install-web-app: Install web applications from a page using browser-controlled consent UI.
- migrate-web-app-origin: Transfer an installed web app to a new origin while preserving user configuration and OS-level shortcuts.
security
- client-side-encryption: Establish shared secrets using public-key encapsulation or key agreement—including hybrid and post-quantum protection—and encrypt sensitive data in the browser with authenticated encryption.
- digital-signatures: Sign and verify messages, tokens, or artifacts in the browser using classical or quantum-resistant (post-quantum) asymmetric keys to ensure data integrity and authenticity.
- local-network-access: Access resources on a user's local network or loopback interface from a public web application.
- passkey-authentication: Authenticate a returning user with a passkey for primary sign-in.
- passkey-conditional-create: Silently register a passkey for an existing user after a successful password login.
- passkey-management: Let users view and manage the passkeys registered to their account.
- passkey-reauthentication: Verify a signed-in user's identity using their existing passkeys before a sensitive action.
- passkey-registration: Register a passkey for an existing user account.
- passkeys: Comprehensive orientation and cross-cutting principles for implementing WebAuthn and Passkeys in web applications. Use this guide when handling passkey registration, authentication, management, or reauthentication.
- quick-sign-ins: Authenticate returning users in place with their saved passkeys or passwords before navigating to a sign-in page or interrupting their workflow.
- restrict-outbound-connections: Restrict a page or worker to communicating only with an explicit allowlist of network endpoints to prevent unauthorized third-party requests and client-side data exfiltration.
- sanitize-untrusted-html: Safely parse and display untrusted HTML content from user input by removing unsafe elements and attributes.
- secure-external-subresources: Verify the cryptographic integrity of external scripts, stylesheets, fonts, and images loaded from third-party origins, and control whether those requests send credentials or referrer URLs.
- trusted-types: Prevent DOM-based XSS attacks by defining a Trusted Types policy to sanitize untrusted HTML, using the policy when writing to DOM sinks like innerHTML, and enforcing Trusted Types via Content Security Policy.
- validate-origins: Compare and validate web origins and sites safely across cross-document messages and URLs without error-prone string parsing.
- verify-email-ownership: Verify that a user owns an email address during account creation, sign-in, or recovery without sending a one-time passcode or magic link email.
ui-atoms
- carousel-slide-effects: Create a carousel of slides with images or other visual elements, where each slide animates as they enter/center/exit their scroller. For example, the slides may fade-in/fade-out, rotate, get bigger or smaller, etc.
- component-specific-light-dark-theme: Force certain elements to be in light mode or dark mode (e.g. code blocks, media players, etc) independently of the page's color-scheme.
- icons: Display and manage icons that can be set and parameterized from CSS, are fast to load, crisp at any resolution and are properly exposed to (or hidden from) assistive technologies.
- position-aware-tooltips: Build tooltips and popovers with directional arrows (or other visual styling) that automatically point the correct way when the element flips to a fallback position.
- pull-to-reveal: Build a pull-to-reveal feature that would enable the user to pull down on the screen to reveal more content, like a search bar.
- responsive-table: Build a data table that presents tabular data with proper header semantics, and remains readable and navigable on small screens and with assistive technologies.
- scroll-position-aware-elements: Build floating buttons or widgets (back-to-top, scroll-to-bottom, chat launchers, etc.) that appear and disappear based on whether the user has scrolled at all.
- scroll-progress-indicator: Create a scroll progress bar, stepped progress tracker, or any visual affordance that communicates how far through a page or section the user has scrolled.
- scrollability-affordance-hints: Build scroll shadows or fading edges that appear only when there's actually more content to scroll to in that direction.
- shrinking-header-on-scroll: Smoothly animate a fixed header or full-page cover on scroll to dynamically shrink, gain shadows, and transform its layout over a predefined scroll distance.
- single-line-overflow: Show text that must stay on one line, such as a tab label, table cell, navigation item, or file name, in a space it may not fit, without breaking the layout or losing the text.
- state-aware-sticky-headers: Build sticky section headers or navbars that visually transform when they're actually "stuck" at the top, changing their color scheme or gaining a shadow.
- viewport-aware-dropdowns: Position dropdowns, flyouts, or contextual action panels tethered to a trigger button so they automatically flip axes at viewport edges instead of getting clipped.
ui-behaviors
- 2d-panning: Allow users to freely pan or scroll two-dimensional surfaces—such as maps, zoomed images, infinite canvases, or large data grids—across both directions (whether diagonally or changing direction mid-gesture) without the gesture locking to a single horizontal or vertical axis.
- anchor-positioning-tab-underline: Transition an element seamlessly between two target element positions. For example, moving a selected tab underline between the previously selected tab and the currently selected tab.
- animate-element-entry-exit: Smoothly hide/show elements as they are added/removed from the DOM or as their display values are toggled.
- animate-to-from-top-layer: Animate elements such as dialogs, popovers, and tooltips as they're entering/exiting the top layer.
- carousel-snap-highlights: Visually highlight the currently snapped non-interactive item in scroll-snapping carousels, galleries, or full-page swipe experiences. For example, expanding a card when snapped, or revealing hidden content.
- consistent-cross-document-transitions: Ensure critical page state is loaded and stable before initiating a cross-document view transition. This means critical CSS styles are loaded and applied, critical JavaScript is loaded and run, and the HTML visible for the user's initial view of the page has been parsed before the transition runs.
- cross-document-transitions: Create smooth, seamless transitions between full page navigations, such as cross-fades, custom reveal effects, or morphing of content from one page to the next.
- custom-button-actions: Declaratively connect a button to any element to trigger custom, application-specific actions using declarative button commands, invoker commands, button commands, custom commands, or declarative toggle actions.
- declarative-dialog-popover-control: Toggle the visibility of a dialog or popover from a button without writing JavaScript.
- directional-navigation-transitions: Animate visual state changes to reflect the direction of a user's navigational flow, such as sliding new content in from the right when advancing forward or from the left when returning to a previous screen.
- drag: Support dragging to move a floating element around the page.
- drag-and-drop: Support dragging to rearrange the children of a container along one axis (horizontal or vertical) while preserving their state and accessible order.
- dynamic-sibling-animations: Stagger animation or transition timing across sibling elements so each one starts after a computed delay based on its position in the sibling list.
- dynamic-sort: Best practices for handling dynamic user-triggered reordering of a container's children (e.g. list items, table rows, or a card grid), with optional animated reordering that respects user preferences, good screen reader UX, and optimal performance for large lists.
- group-element-transitions: Smoothly rearrange and animate list items, cards, or grid elements into their new positions simultaneously when adding, removing, shuffling, or reordering—such as removing a product from a shopping cart.
- highlight-text-ranges: Highlight arbitrary text ranges on a page such as search results, spelling errors, or collaborative editing cursors.
- interactive-content-reveal: Create interactive reveal effects, such as a spotlight that follows the user's pointer to uncover details within an image or UI section.
- interest-triggered-action-previews: Show a live preview of a button's effect when a user signals interest (e.g. hovering, focusing, or long-pressing) but before they commit to clicking.
- interest-triggered-tooltips: Show a tooltip or supplemental information when a user hovers over, focuses on, or long-presses an interactive element, without requiring a click.
- light-dismiss-a-dialog: Create a modal dialog that can be closed via light dismiss (i.e. clicking or tapping outside of the dialog)
- motion: Animate UI with CSS transitions, animations, scroll-driven animations, and view transitions while keeping motion on the compositor and respecting reduced-motion preferences.
- move-dom-element-without-losing-state: Move or reparent a DOM element without losing important element state, such as interactivity states (:focus/:active),
<iframe>loading state, animation/transition state, etc - parallax-scroll-effects: Create scroll-based effects (such as parallax) where foreground and background layers move at different rates, creating a sense of depth as the user scrolls.
- persistent-top-layer-ui: Keep a modal dialog, fullscreen element, or native popover visibly open and functionally active when its underlying DOM node is moved or reparented in the DOM.
- physics-based-easing: Create custom, physics-based animation and transition effects, like bounce and spring, that feel more natural and engaging than traditional easing curves.
- platform-controls-dismiss-dialog: Create a modal dialog that can be closed via standard platform-specific user actions, such as pressing the
Esckey on desktop platforms, or a "back" or "dismiss" gesture on mobile platforms - prevent-page-scroll-under-modal-dialog: Prevent the underlying page from scrolling while a modal dialog is open.
- same-document-transitions: Visually connect persisting elements across different page states or navigations in a Single Page Application (SPA) (e.g. expanding a product thumbnail into a full-bleed hero image) by smoothly morphing their size, position, or other styling properties.
- scoped-component-transitions: Animate state changes inside a single component (a card, list, panel, or other subtree) while the rest of the page remains interactive, and other transitions run concurrently.
- scroll-completion-effects: Trigger visual effects, animations, or focus changes on a target element only after a smooth programmatic scroll to that element has finished.
- scroll-entry-exit-effects: Create fade-in, scale-up, or other complex reveal-type effects on elements as they enter and exit the scrollport (or viewport) while the user is scrolling.
- scroll-snap-realtime-feedback: Provide real-time visual feedback in linked UI elements while a user scrolls through snap-aligned content, before the scroll gesture completes.
- scroll-snap-state-sync: Synchronize navigation indicators, linked content panels, and analytics tracking with the actively snapped item in a scrollable container.
- scroll-target-on-load: Build a scrollable list of elements (e.g. a carousel of images or a chat conversation thread) that can be displayed with a particular element scrolled into view on the initial render.
- scrollytelling: Animate visual properties on a target element — such as fading a backdrop, shifting a background color, or to create scrollytelling experiences — driven entirely by the scrollport position of a completely different element.
- search-hidden-content: Hide content from view using patterns such as accordions, tabs, and "Read more" sections, while ensuring the hidden text reveals itself during native "Find in page" searches, allows search engine indexing, supports URL fragment deep links, and maintains ARIA accessibility.
- sortable-table: Progressively enhance a data table with behaviors that allow users to sort rows by clicking on column headers.
- spatial-navigation: Implement accessible spatial navigation using arrow keys that works correctly in different layout modes (grid etc)
- swipe-to-remove: Let users act on items in a list (remove, archive, mark as read, etc.) with a horizontal swipe gesture, so they can process entries quickly without tapping a separate control.
- swipe-to-reveal: Let users swipe horizontally on a list item or content pane to reveal contextual action buttons or a side menu without automatically triggering an action.
ui-components
- accordion: Build an accordion component with animation, optional exclusive (one-open-at-a-time) behavior, and brand-consistent styling.
- app-menus: Build an application menu bar where several top-level menus (such as File, Edit, and View) act as a single keyboard stop and switch between each other on hover or arrow keys.
- breadcrumbs: Build a breadcrumb trail that shows the user's location within a site hierarchy and lets them navigate to ancestor pages.
- card: Build a card component that adapts its presentation to its own available space and contents.
- carousel: Build a carousel component that displays a set of items in a horizontal or vertical layout.
- checkbox: Style checkboxes, including custom icons, layout, colors, check/uncheck animations, while preserving native functionality and accessibility.
- copy-button: Build a copy button that copies text from arbitrary elements to the clipboard.
- dark-mode-toggle: Build a dark mode toggle component that allows users to override their system color scheme preference for the current site.
- dialog: Build a modal or non-modal dialog component that is accessible, manages focus appropriately, and can be dismissed the way users expect on each platform.
- hovercard: Build a hovercard component that displays an interactive structured preview of the page a certain type of link (e.g. a user profile) will navigate to when hovered over.
- menu: Build a menu component that displays a list of options or actions, with support for nested submenus.
- navbar: Build a site navigation bar that adapts across screen sizes and indicates the current page.
- navigation-drawer: Create a navigation drawer component that, when triggered from a menu button, slides in from the side overlaid on top of existing page content, and slides out when dismissed (by swiping away, tapping outside, or pressing escape).
- persistent-app-tours: Create persistent onboarding walkthroughs using tethered native overlays that stay open during user interaction.
- persistent-toast-notifications: Create non-intrusive toast and overlay notifications for persistent, stackable messaging and state communication.
- progress: Build a styled progress bar that communicates completion of a task or process, in both determinate and indeterminate states.
- progress-ring: Build a progress ring component that visually represents the completion status of a task or process, with support for content in the center and brand-consistent styling.
- scrollspy: Highlight the currently visible section of a page in a navigation menu
- spinner: Build a loading spinner that communicates busy state to all users, respects reduced-motion preferences, and animates efficiently.
- stack-drill-down: Build full-screen hierarchical navigation that lets users drill down into nested views and swipe or navigate back to return, with browser history kept in sync.
- tabs: Build a responsive tabbed interface with good UX when not all tabs fit on screen.
- toolbar: Build a toolbar component that displays a set of controls for performing actions.
user-experience
- content-first-noise-reduction: Maximize content and reduce noise by removing blocking popups, keeping persistent navigation compact, and moving secondary content behind on-demand disclosure.
- form-factor-adaptation: Adapt layouts, controls, and text to any device or container so touch targets stay usable, content fits its space, and nothing collides with system UI.
- natural-interactions: Implement natural interactions with clear hover, focus, and press feedback, motion that opens from its trigger, swipeable content, and keyboard-reachable actions.
visual-design
- adapt-scrollbar-to-contrast-preferences: Enhance scrollbar visibility for users who prefer high-contrast interfaces
- apply-webgl-shaders: Apply custom visual effects with WebGL shaders to HTML content.
- browser-ui-theming: Theme browser-generated UI such as text selection, scrollbars, form controls, and pickers with CSS instead of re-creating it with custom elements.
- color: Color guidance for the web, including contrast requirements, light and dark color schemes, Forced Colors Mode, and generating tints and shades from a base color.
- complex-shapes: Clip elements and their content to any free-form shape, like a symbol, brush stroke, or organic texture for more expressive designs.
- contrast-color: Select a readable text color with sufficient contrast on a dynamic background color.
- custom-text-decorations: Add text decorations such as underlines, overlines, strikethroughs, or entirely custom shapes, with reveal animations, custom offsets and end insets, and flexible ink skipping.
- customize-scrollbar-color-and-thickness: Customize the color or thickness of a scrollbar
- dark-mode: Implement dark mode support in a way that respects the user's light/dark theme preference and adapts browser UI (e.g. scrollbars, form controls, etc)
- equal-width-text-lines: Make every line of a multi-line heading or lockup span the same width, as in poster-style or stacked-headline typography. Unlike justified text, the text itself is sized to the width rather than the spacing stretched
- export-html-media-from-canvas: Capture and export dynamic HTML content as images or video frames from within canvas.
- expose-canvas-content-to-browser-features: Expose content rendered in a canvas to browser features like assistive technologies, translation, or reading mode.
- improve-text-layout-and-legibility: Improve the layout and legibility of short standalone text content, such as headings no longer than a few lines, by enabling the browser to apply evenly balanced line breaks when wrapping text.
- interactive-content-in-3d-scenes: Integrate interactive HTML elements into a 3D scene.
- precise-text-alignment: Achieve precise vertical alignment with text of any font. For example, exactly equal visual padding above and below text, or aligning text perfectly flush with adjacent icons or images.
- shaped-cutouts: Combine multiple shapes to create complex cutouts or 'knockout' effects in elements, such as adding a notch to an element.
- soft-edge-content-fade: Apply a transparency gradient to content edges to indicate further scrollable areas or to obscure payment-walled text.
- typography: Typography best practices for the web, including font sizing units, line height, text wrapping and balancing, and fluid type that scales with the viewport.
- visual-effects: Visual effects with CSS such as layered shadows, blend modes, gradients with predictable color interpolation, and patterns like stripes, checkerboards, dots, and pie charts built from gradients alone.
- visually-stable-font-fallbacks: Define font styles such that text remains readable and visually consistent in the event that there's a swap between the preferred font and one of the fallbacks (or vice versa).
- visually-stable-mixed-fonts: Define font styles such that text remains readable and visually consistent in situations where multiple fonts are used to render a single block of text.
- visually-texture-content: Apply realistic weathering and texture patterns to elements to give them an organic, aged, or physical material appearance.
wasm
- cpp-on-the-web: Compile C/C++ to WebAssembly using Emscripten
webmcp
- agentic-forms: Expose client-side functionality as tools to AI agents by annotating standard HTML forms with WebMCP attributes.
- agentic-javascript-tools: Programmatically register client-side JavaScript functions as tools for AI agents using the WebMCP Imperative API.
- webmcp: Use this guide to implement WebMCP in browser applications, exposing client-side functionality as tools to AI agents via declarative or imperative APIs.
Safe Adoption of Modern Features
- Progressive Enhancement & Nuanced Fallbacks: We distinguish between purely additive enhancements (like speculative preloading) which are safe to let older browsers silently ignore, and critical behaviors (like dialog controls or network beacons) where we write highly considered, low-overhead fallbacks.
- Responsible Fallbacks: We prioritize lightweight, case-specific custom fallbacks (<50 LOC) or conditionally-loaded polyfills instead of heavy third-party bundles.
- Gotchas & Quirks: We document hidden platform limitations, such as the 64KB payload quota for
fetchLater()or macOS-specific scrollbar behaviors. - Baseline-Aware Integration: We leverage real-time compatibility data from the Baseline project so agents dynamically adapt to current browser support.
- Origin Trial & Volatile Feature Gates: Guides covering experimental Origin Trial APIs or volatile features (single-engine features shipped within the last 3 months or still stabilizing) remain discoverable via
search, but are gated onretrieveso agents do not adopt unstable APIs without explicit developer consent.
Project Configuration (.mwgrc)
Configure Origin Trial and volatile feature opt-ins for a repository with an optional .mwgrc JSON file in your project root (or ~/.mwgrc as a user-level fallback), which you can commit to share across your team:
| CLI Command | .mwgrc Key |
Effect |
|---|---|---|
npx modern-web-guidance@latest set-allow-origin-trials |
"allowOriginTrials": true |
Unlocks guides for experimental Origin Trial APIs. |
npx modern-web-guidance@latest set-allow-volatile-features |
"allowVolatileFeatures": true |
Unlocks guides for volatile single-engine features. |
How It Works
- Activation: The coding agent activates the
modern-web-guidanceskill because of a relevant task. The agent is instructed to use themodern-web-guidanceCLI for web platform queries. - Local Semantic Search: The agent runs
modern-web-guidance search "<query>". The tool matches the query to the best guide using an offline, zero-dependency embedding model and BM25 search engine (no network calls, no API keys). - Guide Fetch: The agent retrieves the guide via
modern-web-guidance retrieve <guide-id>, inserting targeted code patterns, gotchas, and fallbacks directly into its context window.
Tip
Note: We use npx to ensure the content doesn't go stale, but the CLI works offline, completely private and local.
The npm package is self-contained, with no extra dependencies to ensure both low-latency and supply-chain security.
Alternative Installation Methods
Vercel Skills CLI (aka npx skills)
npx skills add GoogleChrome/modern-web-guidance
GitHub CLI
gh skill install GoogleChrome/modern-web-guidance
Google Antigravity
agy plugin install https://github.com/GoogleChrome/modern-web-guidance
GitHub Copilot CLI
/plugin marketplace add GoogleChrome/modern-web-guidance /plugin install modern-web-guidance@googlechrome
Claude Code Plugin
/plugin marketplace add GoogleChrome/modern-web-guidance
/plugin install modern-web-guidance@googlechrome
/plugin # Select GoogleChrome marketplace, press enter, enable AutoUpdate
/reload-pluginsGrok Build CLI
grok plugin install https://github.com/GoogleChrome/modern-web-guidance --trust
Kimi Code
/plugins install https://github.com/GoogleChrome/modern-web-guidance
OpenAI Codex
codex plugin marketplace add GoogleChrome/modern-web-guidance codex plugin add modern-web-guidance@googlechrome
Updating
If you installed the skill using npx modern-web-guidance@latest install, you can update with: npx modern-web-guidance@latest update.
Otherwise, consult your agent's documentation for updating plugins and skills.
Evals to prove this works well
We developed a robust eval harness to ensure that the content is empirically proven and continuously calibrated so AI agents write better code. We run automated evaluations using a closed-loop validation pipeline:
[ Expert-authored guidance and demo ]
│
▼
[ Target generation ] ──> Tasks on real webapps, Golden solutions, Playwright graders
│
▼
[ Calibration loop ] ───> Runs Grader on Golden Solutions (Must Pass 100%)
│ Runs Grader on Unmodified Base App (Must Fail 100%)
▼
[ E2E agent evals ] ────> Runs coding agents in guided vs. unguided modes
Compares pass rates and accessibility w/ and w/o the skill
- Simulated Developer Tasks: We define realistic developer prompts against full base applications (
daily-grind,devtools-times) that mimic real-world requests (e.g., "make my images load faster"). Prompts avoid naming APIs or features, testing whether the agent can naturally discover and apply the right guides. - Static & Browser-Based Assertions: Playwright graders verify that each implementation requirement was followed—checking source patterns, computed styles, runtime DOM behaviors, and accessibility states.
- Self-Healing Calibration: Graders are calibrated against multi-agent (Claude/Codex/AGY) golden solutions (100% pass target) and an unmodified baseline application (0% pass target).
- E2E Testing: We measure coding agent performance on real tasks with and without guidance. The opportunity (100% - unguided pass rate) and uplift (guided - unguided pass rate) are key: if models already succeed without guidance, we prune redundant advice; where agents struggle, we refine guides to maximize uplift.
Recent eval results snapshot
Explore full per-agent and per-guide breakdowns on the Eval Dashboard.
| Date | Agent + Model | Tasks / Assertions | Unguided → Guided (Uplift) |
|---|---|---|---|
| Nov 8 | antigravity_cli (gemini-4-argon) | 214 / 1673 | 58% → 94% (+36pp) |
| Nov 8 | codex_cli (gpt-6.1-sol) | 215 / 1795 | 54% → 82% (+28pp) |
| Nov 8 | claude_code (opus-5-5) | 215 / 1801 | 57% → 88% (+31pp) |
| Nov 6 | codex_cli (gpt-6.1-sol) | 212 / 1773 | 53% → 86% (+33pp) |
| Nov 6 | claude_code (opus-5-5) | 212 / 1773 | 56% → 90% (+34pp) |
| Nov 6 | antigravity_cli (gemini-4-argon) | 212 / 1722 | 60% → 96% (+36pp) |
| Nov 4 | codex_cli (gpt-6.1-sol) | 209 / 1743 | 52% → 85% (+33pp) |
| Nov 4 | claude_code (opus-5-5) | 209 / 1743 | 57% → 90% (+33pp) |
| Nov 4 | antigravity_cli (gemini-4-argon) | 207 / 1722 | 60% → 96% (+36pp) |
| Nov 2 | codex_cli (gpt-6.1-sol) | 205 / 1729 | 55% → 82% (+27pp) |
Available Skill Packs
You can customize which skill packs are installed using the --choose flag:
npx modern-web-guidance@latest install --choose
modern-web-guidance(~205 tokens): Comprehensive guidance on modern browser APIs, layouts, and performance.chrome-extensions(~175 tokens): Guidance on Manifest V3, background workers, extension APIs, and Chrome Web Store publishing.
Telemetry & Privacy
Google collects anonymous usage information to improve the tool's reliability, relevance, and performance. Collected information includes installation counts, the calling agent name, guide retrieval IDs, and CLI tool search queries generated by the agent (e.g. "dark mode scrollbar color-scheme"). Raw user prompts are not collected. You can inspect what is collected in modern-web.ts.
Tip
To Opt-Out: set the DISABLE_TELEMETRY=1 env variable in your shell profile (e.g., .bashrc or .zshrc):
export DISABLE_TELEMETRY=1Google handles this data in accordance with the Google Privacy Policy.
Contributors
Found a bug, outdated pattern, or missing web platform feature? Open an issue or see CONTRIBUTING.md in the source repository (GoogleChrome/modern-web-guidance-src).
Huge thanks to everyone who has contributed!
License
Unless otherwise noted:
- Software code in this project is licensed under the Apache License 2.0.
- Documentation and guide content under
guides/are licensed under Creative Commons Attribution 4.0 International (CC-BY 4.0).
Portions of the documentation in this project are derived from MDN Web Docs by Mozilla Contributors and W3C, WHATWG, and IETF specifications.
来源:Hacker News · github.com