📣 背景

我们在登录,输入账号密码后,通常会收到 要保存密码吗? 的提示,保存后我们可以在 chrome://password-manager/passwords Google 密码管理工具中查看

图 0


Chrome 提供默认的密码管理工具


图 1

如何保存?

如果我们想在自己的网站登录时,保存信息到 Google 密码管理工具,该如何实现呢?

图 2

1
2
3
4
5
<form method="get" action="#">
<input type="text" name="username" />
<input type="password" name="password" />
<button id="submit">提交</button>
</form>

Credential Management API

保存密码

Chorme 提供 [Credential Management API](https://developer.mozilla.org/en-US/docs/Web/API/Credential_Management_API#credential_management_concepts_and_usage), 我们可以使用 PasswordCredential 对账号密码进行管理

1
2
3
4
5
6
7
8
9
10
const cred = new PasswordCredential({
id,
password,
name,
iconURL,
});

navigator.credentials.store(cred).then(() => {
// Do something else.
});

如上面的例子,我们点击 提交 按钮时,可以通过 navigator.credentials.store 保存起来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
submit.addEventListener('click', (e) => {
e.preventDefault();

const fm = new FormData(document.querySelector('form'));

const cred = new PasswordCredential({
id: fm.get('username'),
name: fm.get('username'),
password: fm.get('password'),
});

navigator.credentials
.store(cred)
.then((data) => {
console.log('data: ', data);
})
.catch((error) => {
console.error('error: ', error);
});
});

接下来可以看到出现了保存密码的提示弹窗

图 3

获取密码

保存完密码后,我们可以通过 navigator.credentials.get 获取到密码,这是一个异步接口 (为什么是异步下文会提到)

1
2
3
4
5
6
7
navigator.credentials
.get({
password: true,
})
.then((profile) => {
console.log('profile: ', profile);
});

需要注意的是,密码是明文

图 4

多组密码

如果保存了多组密码,那么在获取密码的时候会弹窗 登录身份选择框,需要手动选择

图 5


选择后,如果绑定了指纹之类的,还会进一步进行安全验证

图 6


验证通过后,返回选择的密码,这也是为什么该接口是异步的原因

图 7

自动填充

在选择完密码后,我们还可以再进一步,将获取到的密码直接填充到表单上

一种是直接使用 <input/> 组件默认的浏览器行为进行填充

图 8

第二种就是在获取到密码后,直接设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
navigator.credentials
.get({
password: true,
})
.then((profile) => {
console.log('profile: ', profile);

if (!profile) {
return;
}

document.querySelector('[name="username"]').value = profile.name;
document.querySelector('[name="password"]').value = profile.password;
});