CredentialsContainer: store() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流浏览器均已支持。

安全上下文: 此功能仅在安全上下文(HTTPS)中可用,且支持此功能的浏览器数量有限。

store() 方法是 CredentialsContainer 接口的一部分,它将一组用户凭证存储在一个 Credential 实例中,并返回一个包含此实例的 Promise

注意: 此方法仅限于顶级上下文中使用。在 <iframe> 元素内调用此方法将解析但不会产生任何效果。

语法

js
store(credentials)

参数

credentials

一个有效的 Credential 实例。

返回值

一个 Promise,解析为 undefined

异常

NotAllowedError DOMException

如果当前操作中存在与正在操作的凭证类型相同的凭证,则抛出此异常。

示例

在成功认证后存储密码凭证

此代码将在用户注册或登录后,并且服务器确认凭证正确时执行。

js
// Check if the browser supports password credentials (and the Credential Management API)
if ("PasswordCredential" in window) {
  let credential = new PasswordCredential({
    id: "example-username",
    name: "Carina Anand", // In case of a login, the name comes from the server.
    password: "correct horse battery staple",
  });

  navigator.credentials.store(credential).then(
    () => {
      console.info("Credential stored in the user agent's credential manager.");
    },
    (err) => {
      console.error("Error while storing the credential: ", err);
    },
  );
}

规范

规范
Credential Management Level 1
# dom-credentialscontainer-store

浏览器兼容性