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

瀏覽器相容性