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

瀏覽器相容性

另見