首页  >  文章  >  web前端  >  使用 JavaScript 读取电话联系人

使用 JavaScript 读取电话联系人

WBOY
WBOY原创
2024-08-19 18:33:25872浏览

作者注:本文中描述的技术和流程处于实验阶段,仅适用于少数浏览器。在撰写本文时,联系人选取器 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