ContactsManager

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

安全上下文: 此功能仅在安全上下文(HTTPS)中可用,且支持此功能的浏览器数量有限。

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

ContactsManager 接口是 Contact Picker API 的一部分,它允许用户从其联系人列表中选择条目,并将所选条目的有限详细信息共享给网站或应用程序。

ContactsManager 可通过全局 navigator.contacts 属性访问。

实例方法

select() 实验性

返回一个 Promise,当该 Promise 解析时,将向用户显示一个联系人选择器,允许他们选择希望共享的联系人。

getProperties() 实验性

返回一个 Promise,该 Promise 将解析为一个 Array,其中包含指示可用联系人属性的 strings

示例

特性检测

以下代码检查 Contact Picker API 是否受支持。

js
const supported = "contacts" in navigator && "ContactsManager" in window;

检查支持的属性

以下异步函数使用 getProperties 方法检查支持的属性。

js
async function checkProperties() {
  const supportedProperties = await navigator.contacts.getProperties();
  if (supportedProperties.includes("name")) {
    // run code for name support
  }
  if (supportedProperties.includes("email")) {
    // run code for email support
  }
  if (supportedProperties.includes("tel")) {
    // run code for telephone number support
  }
  if (supportedProperties.includes("address")) {
    // run code for address support
  }
  if (supportedProperties.includes("icon")) {
    // run code for avatar support
  }
}

选择联系人

以下示例设置了要为每个联系人检索的属性数组,并设置了一个选项对象以允许选择多个联系人。

然后定义一个异步函数,该函数使用 select() 方法向用户显示联系人选择器界面并处理所选结果。

js
const props = ["name", "email", "tel", "address", "icon"];
const opts = { multiple: true };

async function getContacts() {
  try {
    const contacts = await navigator.contacts.select(props, opts);
    handleResults(contacts);
  } catch (ex) {
    // Handle any errors here.
  }
}

handleResults() 是一个由开发者定义的函数。

规范

规范
联系人选择器 API
# contacts-manager

浏览器兼容性

另见