首頁  >  文章  >  web前端  >  使用 JavaScript 讀取電話聯絡人

使用 JavaScript 讀取電話聯絡人

WBOY
WBOY原創
2024-08-19 18:33:25873瀏覽

作者註:本文所述的技術和流程處於實驗階段,僅適用於少數瀏覽器。在撰寫本文時,聯絡人選取器 API 僅受 Android Chrome(從版本 80 開始)和 iOS Safari(從版本 14.5 開始,但僅在標誌後面)支援。如果您想查看功能,可以在我的網站上查看正在運行的演示。


從手機或平板電腦上的聯絡人清單中讀取條目傳統上僅限於本機應用程式。但透過聯絡人選擇器 API,我們可以使用 JavaScript 來做到這一點。

對於需要電話號碼或VoIP 等聯絡資訊的應用程式、我們想要發現認識的人的社交網絡,或者需要填寫表單資訊而不交換應用程式來查看數據的應用程序,此功能可能會很有趣。

API 和裝置將限制哪些屬性可用。有五種標準可供開發者選擇:

  • 名字
  • 電話
  • 電子郵件
  • 地址
  • 圖示

這裡的複數很重要,因為聯絡人可以有多個電話、電子郵件或多個地址。為了保持一致性,傳回的資料將始終位於數組內,即使它是單一值。稍後會詳細介紹。


隱私與安全

手機上儲存的聯絡資訊可能包含我們必須謹慎對待的敏感資訊。因此,我們必須考慮隱私和安全因素:

  • 聯絡人選取器 API 程式碼必須在頂層瀏覽上下文中執行。它可以防止外部代碼(例如廣告或第三方插件)讀取您手機上的聯絡人清單。
  • 聯絡人選擇器 API 程式碼只能在使用者手勢後執行。因此,開發人員無法完全自動化該流程。使用者必須採取行動才能觸發接觸讀取。
  • 此人必須允許存取聯絡人清單。這個限制是手機強加的,不是JS強加的。使用者必須授予瀏覽器存取聯絡人的權限(如果還沒有)。

他們第一次使用使用聯絡人選擇器 API 的網站時,可能會收到以下訊息:

Read Phone Contacts with JavaScript

有些人可能會覺得這個彈出視窗「可怕」。
 

手機每次都會顯示此彈出窗口,直到使用者點擊「允許」。在此之前,聯絡人選取器 API 將不會運作。哪個好;我們希望確保用戶授予適當的權限。一次性的事情也很好。每次頁面執行聯絡人選擇器 API 程式碼時授予授權將是一件令人頭痛的事情。


API 與程式碼

聯絡人選取器 API 僅定義了兩個方法:

  • getProperties():傳回可在裝置上讀取的屬性清單。定義中只有五個:「地址」、「電子郵件」、「圖示」(這可能不是聯絡人圖片)、「姓名」、「電話」(電話),但設備可能不允許訪問所有其中。
  • select():開啟聯絡人彈出視窗並在使用者完成操作後返回選擇。它需要兩個參數:要讀取的屬性清單和帶有選項的可選物件。

這兩種方法都會傳回 Promise,但考慮到它們觸發的操作會阻塞應用程式的常規流程,因此我們在處理它們時應該使用 async/await。

忽略 getProperties() 並直接請求所有屬性可能很誘人。但如果你這樣做的話要小心:它可能會起作用,但如果任何指定的屬性不可用, select() 方法將拋出異常。

範例

聯絡人選擇器 API 的演示正在運行(在此處在線運行或觀看此視頻)。如果支援 API,它會顯示一個按鈕,讀取聯絡人的電話號碼、姓名和電子郵件以進行顯示。

首先,我們需要按鈕。正如隱私和安全部分前面詳細介紹的,在調用 API 之前需要用戶執行操作,因此如果沒有用戶交互,我們無法觸發任何內容:

<button onclick="getContactData()">Show contact data</button>

主要程式碼位於 getContactData() 函數中。但在此之前,如果聯絡人選擇器 API 不可用,那麼顯示該按鈕有何意義呢?如果按鈕不可用,我們將其隱藏。或者更好的是,讓我們預設隱藏按鈕(新增隱藏屬性),並且僅在 API 可用時才顯示它。

// only show the button if browser supports Contact Picker API
if ("contacts" in navigator) {
  document.querySelector("button").removeAttribute("hidden");
}

現在按鈕邏輯已經就位,讓我們專注在 getContactData()。這是函數的註解版本:

// it is asynchronous because we'll wait for the modal selection
async function getContactData() {
  // indicate what contact values will be read
  const props = ["tel", "name", "email"];

  // wrap everything in a try...catch, just in case
  try {
    // open the native contact selector (after permission is granted)
    const contacts = await navigator.contacts.select(props);

    // this will execute after the native contact selector is closed
    if (contacts.length) {
      // if there's data, show it
      alert("Selected data: " + JSON.stringify(contacts));
    } else {
      // ...if not, indicate nothing was selected
      alert("No selection done");
    }
  } catch (ex) {
    // if something fails, show the error message
    alert(ex.message)
  }
}

Once the button triggers this function, and if the browser has permissions (see screenshot in the previous section), the contact modal will show up, indicating essential information: the URL reading the data, what data it will return, and the list of contacts to pick from.

Read Phone Contacts with JavaScript

The Contact Picker shows what information will be shared
 

After closing the modal, the contacts variable will store the data in JSON as an array with an object containing the information requested (it may be empty if it is not available in the contact card).

For example, this is the result after selecting myself as a contact (fake data):

[
  {
    "address": [],
    "email": [ "alvarosemail@gmail.com" ],
    "icon": [],
    "name": [ "Alvaro Montoro" ],
    "tel": [ "555-555-5555", "555-123-4567" ]
  }
]

If the data includes an icon, it will be a blob with the image. If the data includes an address, it will be a more complex object with street, city, country, ZIP code, etc. You can check the returned values in the specification.

But why an array if we only selected one contact? Because there's an option to choose more than one contact!

Selecting Multiple Contacts

It is possible to select more than one contact. If we want to do that, we need to pass a second parameter to the navigator.contacts.select() method indicating this option.

const props = ["tel", "address", "icon", "name", "email"];
// only one option available: read multiple or only one (default)
const options = { multiple: true };

try {
  const contacts = await navigator.contacts.select(props, options);
  // ...

The result is an array of contacts, so the rest of the code could remain the same for this example.


The code above can be intimidating, mainly because of all the comments I added. Here's a lightly commented version of the code above. As you may notice, it is pretty simple:

async function getContactData() {
  if ("contacts" in navigator) {
    const props = await navigator.contacts.getProperties();
    const options = { multiple: true };

    try {
      const contacts = await navigator.contacts.select(props, options);

      if (contacts.length) {
        // code managing the selected data
      } else {
        // code when nothing was selected
      }
    } catch (ex) {
      // code if there was an error
    }
  }
}

You can check out a running demo on my website. Don't worry, I don't do any with the contact information beyond writing it on the screen. But review the code before if you don't trust me.


Conclusion: Privacy Over Piracy

Contact information is PII (Personally Identifiable Information), and we must treat it with all the care and security that sensitive data requires.

Apart from possible legal requirements that I am not going to go through (because I don't know them, and they change from country to country), here are some basic guidelines when dealing with sensitive data:

  • Respect people's privacy. Don't force them to share information they don't want to share.
  • Treat the data with care and in a safe way. Would you be comfortable if the data you are processing were yours?
  • Don't store data if you don't need to. Read it, use it, forget it. Don't store data that you are not using.
  • Only get the data that you need. Don't be sneaky or shady. Get just what's required to build credibility and trust.

Suppose a web app tries to read addresses, names, or emails while selecting a phone number. If that happened to me, I would automatically reject the permission and leave the website.

So, explore JavaScript and the Contact Picker API, but always remember that there's a person behind the screen and that the data they share could be risky if it falls into the wrong hands. Don't be reckless.



If you enjoyed this article about JavaScript and like to test Web APIs and different things with JS, check out this other article:


Develop a Rock Band game with HTML and JavaScript
Read Phone Contacts with JavaScript

以上是使用 JavaScript 讀取電話聯絡人的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn