自动填充事件处于源试用阶段

发布时间:2026 年 6 月 10 日

表单是网络上常见的互动点,但它们会给用户带来相当大的摩擦。浏览器长期以来一直提供自动填充功能来减少这种摩擦,让用户无需重复执行输入信用卡号、地址和登录凭据等任务。

对于开发者来说,处理表单自动填充是一项挑战。虽然开发者可以 监听 inputchange 事件在 <form> 元素上,但这些事件不会 告诉您数据是如何到达字段的。这种不明确性使得在表单自动填充的确切时刻触发特定逻辑(例如布局调整)变得困难。新的 autofill 事件(现在作为 Chrome 源试用 提供)

(从 Chrome 147 开始)在浏览器协助用户自动填充时,为开发者提供有用的信号。

autofill:解决 inputchange 未解决的问题

inputchange 事件是通用信号,不会区分用户手动填写表单字段和使用自动填充的情况。由于没有专门用于自动填充表单的事件,开发者很难可靠地执行在填写表单时有用的界面更新。例如,用户指定居住国家/地区,附近会显示一个字段,用于指定他们居住的州或区,这因国家/地区而异。对于开发者来说,响应自动填充请求触发此更新更可预测,对用户来说也更有用。autofill 事件解决了这个问题。

autofill 事件在浏览器自动填充表单之前执行。该事件的监听器会收到要填充的 autofillValues 数组和 refill 函数。例如,如果监听器更改了内容,监听器可以调用 refill 函数来请求浏览器重新填充表单。请看以下示例表单标记:

<form>
  <div>
    <label for="country">Country</label>
    <select id="country" name="country" autocomplete="country">
      <!-- ... -->
    </select>
  </div>
  <div>
    <label for="address-line-1">Address Line 1</label>
    <input type="text" name="address-line-1" id="address-line-1" autocomplete="address-line1">
  </div>
  <div>
    <label for="city">City</label>
    <input type="text" name="city" id="city" autocomplete="address-level2">
  </div>
  <div>
    <div class="state">
      <!-- This section gets populated based on the
           value provided in the country field -->
    </div>
  </div>
  <div>
    <input type="submit" value="Calculate">
  </div>
</form>

此 JavaScript 会绑定 document 上的 autofill 事件:

document.addEventListener('autofill', async event => {
  // A null check here is a good idea, as
  // refills are not available in a WebView.
  if (event.refill == null) {
    /* Apply legacy logic */
    return;
  }

  // Walk the fields
  for (const {field, value} of event.autofillValues) {
    if (field.name === 'country') {
      if (value === 'Germany') {
        document.querySelector('.state').innerHTML = `
        <label for="state">State:</label>
        <select name="state" id="state" autocomplete="address-level1">
          <option selected="selected"></option>
          <option value="BW">Baden-Württemberg</option>
          <option value="BY">Bavaria</option>
          <!-- Other states omitted -->
        </select>
      `;
      } else {
        /* Logic for other countries */
      }
    }
  }

  await event.refill();
});

此示例是一个典型的地址表单。用户可以点击或点按表单字段来触发自动填充工具提示。选择自动填充地址后,会发生以下情况:

  1. autofill 事件处理程序在表单字段自动填充之前执行。
  2. event.autofillValues 在具有两个属性的对象中提供建议的自动填充数据:
    • field:对要自动填充的 DOM 元素的引用。
    • value:该字段的建议自动填充值。
  3. 检测到国家/地区字段名称后,逻辑会检测国家/地区(在此示例中为德国),并使用该国家/地区的正确选项填充州下拉列表。
  4. 调用 event.refill() 以指示浏览器重新填充表单,这会在更改后的表单上重复自动填充操作。

如果您对更复杂的 autofill 用例感兴趣,Yoav Weiss 的 Shopify 创建了两个演示:

  1. 一个 个人信息表单 与本文中的示例类似,但不仅仅是 autofill 事件的基本 演示。
  2. 一个信用卡自动填充演示 使用 autofill 事件检测发卡机构,并使用丰富的视觉效果大幅更新 DOM 。

信用卡自动填充演示说明了 autofill 事件的功能。虽然在 autofill 事件之前也可以实现这些类型的体验,但拥有专门用于表单自动填充的事件可以带来更好的开发者体验。

autofill 事件和 :autofill CSS 伪类

:autofill CSS 伪类 与自动填充的表单元素匹配,autofill 事件可以作为其补充 。

例如,您可能希望使用 :autofill 来区分刚刚自动填充的字段与在 autofill 事件期间修改的字段。这对于用户来说可能是一个有用的信号,表明该字段已预先填充,但可修改的表单控件中的数据存在,这告诉用户他们仍然可以根据需要更改该字段。

document.addEventListener('autofill', async event => {
  if (event.refill !== null) {
    // Walk the fields to be autofilled:
    for (const {field, value} of event.autofillValues) {
      let cardIssuer;

      // If this field is the credit card number,
      // use its value to get the card issuer.
      if (field.name === 'card-number') {
        cardIssuer = getCardIssuerFromNumber(value);
      }

      // Populate the card issuer field with
      // the data we got from the card number
      if (field.name === 'card-issuer') {
        field.value = cardIssuer;
        field.classList.add('modified-by-event');
      }
    }
  }
});

在前面的代码块中,系统会遍历自动填充的字段,直到找到信用卡号字段。该字段中的数据用于获取发卡机构,该机构会填充到该字段中,并获得 .modified-by-event 类。然后,可以调整此字段的自动填充样式,使其与其他未被 autofill 事件修改的自动填充字段区分开来:

/* Standard autofill style: */
input:autofill {
  border: 0.25rem solid #cc0;
}

/* Autofill style for `autofill` event-modified data: */
input.modified-by-event-autofill:autofill {
  border-color: #0cc;
}

这样,您就可以保留自动填充表单字段的样式语义,继承 :autofill 样式,并仍以独特的方式向用户提供有意义的呈现,表明表单字段已自动填充。

autofill 事件和 field-sizing CSS 属性

如果 field-sizing CSS 属性 的值为 content,则 <textarea> 元素等字段会自动 调整大小以适应其内容。这样就不需要在小字段中使用笨拙的滚动条:

textarea {
  /* The field grows to fit the content automatically: */
  field-sizing: content;
  min-height: 3lh;
  transition: min-height 0.2s ease-out;
}

这是一个不错的用户体验考虑因素,但可能会导致布局偏移。当用户输入内容时,输入字段的扩展是渐进式的。但是,当浏览器 将多行地址自动填充到 <textarea> 元素中时,该字段可能会 立即大幅扩展。借助 autofill 事件,您可以更有效地管理这些过渡,例如,通过为容器添加动画效果或调整其滚动位置,以避免用户丢失上下文。

document.addEventListener('autofill', event => {
  // Assumes a single field for the purpose of a quick
  // demonstration, such as a multiline address field:
  const [addressDetails] = event.autofillValues;

  // Since field-sizing: content causes an immediate jump,
  // we can use the event to ensure the UI remains stable:
  requestAnimationFrame(() => {
    addressDetails.scrollIntoView({behavior: 'smooth', block: 'nearest'});
  });

  if (event.refill !== null) {
    await event.refill();
  }
});

每个应用的要求都不同,因此您需要确定这是否是一种值得使用的模式,但它说明了如何使用 CSS 和 autofill 事件的组合来实现目标。

检测和衡量表单自动填充

表单自动填充的分析数据对企业很有价值,但衡量 表单上的 自动填充使用现有的 Web 功能 很难。例如,通常的做法是依赖于 CSS :autofill 伪类,该伪类不是基准。

autofill 事件是一种检测表单自动填充的工具。由于该事件仅在实际自动填充尝试时触发,而不会在任何输入时触发,并且 event.autofillValues 属性仅包含自动填充的字段,因此您可以跟踪自动填充的数据:

document.addEventListener('autofill', event => {
  // Get autofilled data
  const autofillData = {
    // Assumes the form has an ID for simplicity:
    form: event.target.id,
    autofilled: true
  };

  // Send to analytics endpoint
  const body = JSON.stringify(autofillData);
  navigator.sendBeacon('/analytics', body);
});

此示例经过简化,但它说明了捕获此信息有多么简单。您可以按照适合您的方式构建和收集自动填充分析数据,而无需使用难以实现且不可靠的变通方法。

注册源试用

autofill 事件处于 Chrome 源试用阶段,您的参与可以帮助 Chrome 改进该事件。原始试用版 可让您与真实用户一起测试实验性功能,并在 Chrome 团队之前向 Chrome 团队提供反馈,然后 API 成为 Web 平台的一部分。

如需开始在您的网站上使用 autofill 事件,请在此处注册原始试用版。Chrome 期待看到您如何使用它,以及它如何帮助我们发现改进机会。