我正在尝试在提交之前将密码转换为 sha1 和。我使用 crypto.subtle.digest
进行转换。因为它返回了一个 promise ,所以我等待它。问题是,密码未转换就提交了。
function buf2hex(buffer) { // buffer is an ArrayBuffer
return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}
async function onPwSubmit(event) {
/* Handle password-form-submit-events
*
* Replace the entered password with the SHA1-hash of it.
* Return 'false' to abort form-submission if anything goes wrong.
* Return 'true' otherwise.
*/
event.preventDefault();
let input_password = document.getElementById('{{ form.password.auto_id }}');
if (!input_password) { // Just in case something goes wrong, add a message.
alert("Could not hash entered password with SHA1. Please call help.");
console.log("Is there a form-field with id 'id_password'?");
// Abort the form-submit by returning false.
// Must not submit with password not hashed.
return false;
}
let digest = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(input_password.value));
input_password.value = buf2hex(digest).toUpperCase();
event.submit()
return true; // allow form-submit to continue with return true
}
document.querySelector("#passwordform").addEventListener("onsubmit", onPwSubmit)
我希望在提交之前转换密码,但事实并非如此。
最佳答案
您的处理程序根本没有运行,因为监听器未正确附加:
document.querySelector("#passwordform").addEventListener("onsubmit", onPwSubmit)
这会监听名为 onsubmit
的事件,并在该事件发生时调用回调。但没有这样的事件。您想要监听 submit
事件,句号:
document.querySelector("#passwordform").addEventListener("submit", onPwSubmit)
在使用 =
分配处理程序时,仅使用 on
前缀,例如:
document.querySelector("#passwordform").onsubmit = onPwSubmit
同样的模式(何时使用 on
以及何时不使用)也适用于所有其他事件。
您也无法从事件提交
:
event.submit()
相反,选择表单,然后对其调用submit
:
document.querySelector("#passwordform").submit();
(这不会递归调用您附加的submit
处理程序,不用担心)
关于javascript - 异步 onsubmit 处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55470523/