PasswordCredentialInit
PasswordCredentialInit 字典代表傳遞給 CredentialsContainer.create() 中 password 選項的值,用於建立密碼憑證。
從表單初始化
網站可以直接傳遞一個 HTMLFormElement,而不是直接傳遞此字典。create() 的實現會根據元素 autocomplete 屬性的值,從表單的可提交元素中提取資料來填充憑證。
autocomplete 值 |
目標憑證屬性 |
|---|---|
"username" |
id |
"name" 或 "nickname" |
name |
"new-password" 或 "current-password" |
密碼 |
"photo" |
iconURL |
如果表單同時包含 "new-password" 和 "current-password" 元素,將使用 "new-password" 的值。
origin 屬性被設定為 HTMLFormElement 所包含的文件的源。
例項屬性
iconURL可選-
一個字串,表示與憑據關聯的圖示或頭像的 URL。
id-
一個字串,表示憑據的唯一 ID。
name可選-
一個字串,表示憑據使用者名稱。
origin-
一個表示憑證源的字串。
PasswordCredential物件是源繫結的,這意味著它們只能在指定的用於它們的源上使用。 密碼-
一個表示憑證密碼的字串。
示例
從物件字面量建立密碼憑證
此示例構造一個物件字面量來初始化密碼憑證。
js
const credInit = {
id: "1234",
name: "Serpentina",
origin: "https://example.org",
password: "the last visible dog",
};
const makeCredential = document.querySelector("#make-credential");
makeCredential.addEventListener("click", async () => {
const cred = await navigator.credentials.create({
password: credInit,
});
console.log(cred.name);
// Serpentina
console.log(cred.password);
// the last visible dog
});
從表單建立密碼憑證
此示例使用表單來初始化密碼憑證。
HTML
HTML 聲明瞭一個 <form>,其中包含三個可提交的元素,分別代表使用者 ID、使用者顯示名稱和密碼。
html
<form>
<div>
<label for="userid">Enter your user ID: </label>
<input type="text" name="userid" id="userid" autocomplete="username" />
</div>
<div>
<label for="username">Enter your username: </label>
<input type="text" name="username" id="username" autocomplete="name" />
</div>
<div>
<label for="password">Enter your password: </label>
<input
type="password"
name="password"
id="password"
autocomplete="new-password" />
</div>
</form>
<button id="make-credential">Make credential</button>
<pre id="log"></pre>
JavaScript
JavaScript 將表單傳遞給 create(),並記錄結果憑證的一些值。
如果表單不包含必需憑證屬性的值,create() 返回的 Promise 將會拒絕。
js
const makeCredential = document.querySelector("#make-credential");
const formCreds = document.querySelector("form");
makeCredential.addEventListener("click", async () => {
try {
const credential = await navigator.credentials.create({
password: formCreds,
});
log(
`New credential:\nname: ${credential.name}, password: ${credential.password}`,
);
} catch (e) {
if (e.name === "TypeError") {
log("Error creating credential\nMake sure you filled in all the fields");
}
}
});
const logElement = document.querySelector("#log");
function log(text) {
logElement.innerText = text;
}
結果
規範
| 規範 |
|---|
| Credential Management Level 1 # typedefdef-passwordcredentialinit |