# Contact Picker API

> navigator.contacts.select() 按次打开联系人选择器。本页说明语法、异常、Android 与 iOS 支持情况及表单回退。

`navigator.contacts.select()` 方法请用户选择联系人，并决定把哪些资料分享给页面。用户代理显示选择器；页面只能按次读取用户选中的记录，不能获得通讯录的持续访问权。

`api.Navigator.contacts` 与 `api.ContactsManager` 兼容数据记录了 Android M（Android 6）上的 Chrome 80 和 Android WebView 80 起的支持。桌面 Chrome、Edge、Firefox 与 macOS Safari 没有支持记录；iOS 14.5 Safari 设有 `Contact Picker API` 偏好设置；Samsung Internet 14.0 曾暴露接口但无法打开选择器，22.0 将其移除。MDN 将此 API 标为实验性功能，且未进入 Baseline。各浏览器行及核验日期见 [Contact Picker 兼容数据](/zh/compatibility/contact-picker/)。

## 语法

`Window` 中的 `[SecureContext]` 接口通过 `navigator.contacts` 提供 `select()` 和 `getProperties()`。调用 `select()` 时，页面必须处于顶层 traversable，且拥有瞬时用户激活；规范没有给 `getProperties()` 设置这两项检查。

| 操作 | 签名 | 结果 |
|---|---|---|
| 选择联系人 | `navigator.contacts.select(properties, options?)` | `Promise<sequence<ContactInfo>>` |
| 查询可用字段 | `navigator.contacts.getProperties()` | `Promise<sequence<ContactProperty>>` |

```js
navigator.contacts.select(properties)
navigator.contacts.select(properties, options)
navigator.contacts.getProperties()
```

`select()` 打开选择器前会消耗瞬时用户激活。选择器界面必须显示请求方的来源、说明所请求的属性、允许用户逐个挑选联系人，并提供取消操作。用户取消时返回空序列。`options.multiple` 为 `false` 时，界面只允许选取一个联系人。

`getProperties()` 返回用户代理所选联系人来源能提供的字段。先读取这个结果，再构造传给 `select()` 的数组。请求数组中若含有联系人来源不支持的字段，规范要求 `select()` 拒绝。

## 参数

`select()` 接受联系人字段序列和可选的选择设置。Contact Picker 规范定义了下列值。

| 参数 | 类型 | 必填 | 含义 |
|---|---|---|---|
| `properties` | `sequence<ContactProperty>` | 是 | 请求的字段。枚举包含 `"address"`、`"email"`、`"icon"`、`"name"` 和 `"tel"`。 |
| `options.multiple` | `boolean` | 否 | 默认为 `false`；设为 `true` 后可以选取多个联系人。 |

Chrome 文档记录 Android M 及以上设备上的 Chrome 80 支持 `name`、`email` 和 `tel`，`address` 与 `icon` 需要 Chrome 84 及以上版本。不要假定联系人来源会提供所有枚举值，先查询 `getProperties()`。

返回的 `ContactInfo` 字典把各字段表示为序列，因为同一联系人可以有多个同类值。字典会带回调用方请求的字段。每个地址用 `ContactAddress` 表示。

| 成员 | 类型 | 内容 |
|---|---|---|
| `name` | `sequence<DOMString>` | 所选联系人的姓名 |
| `email` | `sequence<DOMString>` | 所选联系人的电子邮箱 |
| `tel` | `sequence<DOMString>` | 所选联系人的电话号码 |
| `address` | `sequence<ContactAddress>` | 地址；接口包含 `country`、`addressLine`、`region`、`city` 和 `postalCode`。W3C 的 2021 年活动记录称，当年把 `PaymentAddress` 移植进了 `ContactInfo`。 |
| `icon` | `sequence<Blob>` | 由 `Blob` 对象表示的联系人图片 |

Chrome 文档说明：联系人没有某个请求值，或用户选择不分享该值时，相应字段都会得到空序列。页面无法从空序列判断是哪一种情况。Chrome 还说明联系人字段的标签及其他语义信息不会保留。

## 异常

`select()` 算法会先检查调用上下文、用户激活、选择器状态和请求属性，检查完成后才呈现界面。

| 异常 | 条件 |
|---|---|
| `InvalidStateError` | 调用方不是顶层 traversable；当前 navigable 已显示联系人选择器；或者选择器启动、联系人来源读取失败。 |
| `SecurityError` | 相关全局对象没有瞬时用户激活。 |
| `TypeError` | `properties` 为空，或含有联系人来源不支持的属性。 |

Android 联系人选择器无法打开时，Chromium 的实现与规范所列异常不同，会以 `TypeError: Unable to open a contact selector` 拒绝。恢复逻辑应处理被拒绝的 promise，不要只按规范中的异常名称分支。延迟回调可能在瞬时用户激活过期后才运行，届时无法通过实现中的激活检查；请在激活处理函数中尽快调用 `select()`。

:::caution
Chromium 的 [`contacts_manager.cc`](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/modules/contacts_picker/contacts_manager.cc) 写明了三条错误消息。调用方不在最外层主框架时抛出 `InvalidStateError: The contacts API can only be used in the top frame`；缺少瞬时用户激活时抛出 `SecurityError: A user gesture is required to call this method`；选择器尚未关闭又发起调用时抛出 `InvalidStateError: Contacts Picker is already in use.`。把 `select()` 放在按钮处理函数内，并在 promise 待定期间禁用按钮。
:::

## 示例

下面的代码始终保留表单路径。功能检测可以决定显示哪个控件，但接口存在时，调用仍可能被拒绝，也可能返回不含请求值的联系人。

### 选取邮箱，失败后允许手动输入

在文档中放置一个按钮和一个 `<input type="email">`。先检测 `'contacts' in navigator && 'ContactsManager' in window`，再从 `click` 处理函数直接调用 `select()`。空结果按取消处理；缺少邮箱或 promise 被拒绝后，显示输入框。

```js
const pickButton = document.querySelector('#pick-recipient');
const manualField = document.querySelector('#recipient-email');

const supported = 'contacts' in navigator && 'ContactsManager' in window;
pickButton.hidden = !supported;
manualField.hidden = supported;

pickButton.addEventListener('click', async () => {
  try {
    const [contact] = await navigator.contacts.select(['name', 'email']);
    if (!contact) return; // 用户取消
    const email = contact.email[0];
    if (!email) {
      manualField.hidden = false; // 该联系人没有邮箱
      return;
    }
    manualField.value = email;
  } catch (err) {
    console.error(`${err.name}: ${err.message}`);
    manualField.hidden = false;
  }
});
```

浏览器不支持接口或调用失败时，输入框就是恢复路径。检查 `contact.email[0]` 也能处理联系人没有邮箱、或用户不分享邮箱的情况，随后转到同一个输入框。

### 请求字段不可用时回退到参会人表单

打开选择器前，先查询联系人来源支持的值。这个函数过滤期望字段并传入 `multiple: true`；接口不存在或没有可用字段时返回 `null`，调用方据此显示参会人表单。直接读取缺失的首项会得到 `undefined`。

```js
async function pickAttendees(wanted = ['name', 'tel', 'icon']) {
  if (!('contacts' in navigator && 'ContactsManager' in window)) {
    return null; // 调用方显示自己的参会人表单
  }
  const available = await navigator.contacts.getProperties();
  const props = wanted.filter((p) => available.includes(p));
  if (props.length === 0) return null;

  const contacts = await navigator.contacts.select(props, { multiple: true });
  return contacts.map((c) => ({
    name: c.name?.[0] ?? '',
    tel: c.tel?.[0] ?? '',
    avatar: c.icon?.[0] ? URL.createObjectURL(c.icon[0]) : null,
  }));
}
```

从用户激活处理函数调用此函数，因为其中的 `select()` 会消耗瞬时用户激活。返回 `null` 表示调用方应显示表单；空数组表示选择器没有返回已选联系人。调用处还应捕获拒绝，并像第一个示例一样显示表单。

## 另请参阅

- [Contact Picker API 浏览器支持](/zh/compatibility/contact-picker/)
- [Web Share API](/zh/reference/capabilities/web-share/)
- [Payment Request API](/zh/reference/capabilities/payment-request/)
- [Contact Picker API](https://w3c.github.io/contact-picker/)（w3.org）
- [A contact picker for the web](https://developer.chrome.com/docs/capabilities/web-apis/contact-picker)（developer.chrome.com）
- [Chrome Platform Status: Contacts API](https://chromestatus.com/feature/6511327140904960)（chromestatus.com）