HTML5实现调用手机通讯录,获取手机通讯录信息。
HTML5实现调用手机通讯录,获取手机通讯录信息。
HTML5实现调用手机通讯录,获取手机通讯录信息。
直接无法读,和file控件一样需要用户自己选择,用select方法
网址需要使用https协议,要不无法使用contacts对象。
用最新版的移动端chrome测试,内置的浏览器虽然内核是webkit,但是很多没实现通讯录选择器,会报错【unable to open a contact selector】
<button onclick="choose()">读取通讯录</button>
<script>
async function choose() {
if (!navigator?.contacts?.select) { alert('浏览器不支持!'); return; }
const props = await navigator.contacts.getProperties();
alert(JSON.stringify(props))
const opts = { multiple: true };
try {
var rs = await navigator.contacts.select(props, opts);
alert(JSON.stringify(rs))
}
catch (e) { alert('获取失败\n' + e) }
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>获取通讯录</title>
</head>
<body>
<button onclick="getContacts()">获取通讯录</button>
<ul id="contacts"></ul>
<script>
function getContacts() {
if (typeof navigator.contacts === 'undefined') {
alert('无法获取通讯录信息');
return;
}
navigator.contacts.pickContact(function(contact){
var name = contact.displayName;
var phoneNumbers = contact.phoneNumbers;
var phones = [];
for (var i = 0; i < phoneNumbers.length; i++) {
phones.push(phoneNumbers[i].value);
}
var list = document.getElementById('contacts');
var item = document.createElement('li');
item.innerHTML = name + ': ' + phones.join(', ');
list.appendChild(item);
}, function(error){
alert('获取通讯录信息失败');
});
}
</script>
</body>
</html>
本题无标准答案,同学们可以自己研究考虑一下,