javascript - Asyncronos onsubmit 处理程序
问题描述
我正在尝试在提交之前将密码转换为 sha1 总和。我crypto.subtle.digest
用来做转换。由于它返回一个承诺,我等待它。问题是,提交的密码未转换。
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
和何时不使用)也适用于所有其他事件。
你也不submit
能从一个事件中:
event.submit()
而是选择表单,然后调用submit
它:
document.querySelector("#passwordform").submit();
(这不会递归调用submit
你附加的处理程序,不用担心)
推荐阅读
- android - 使用 Flutter 从路径到文件的转换
- r - 如何绘制具有置信区间的双变量图,用于 R 中的 x 和 y 轴?
- google-sheets - Find values string inside a string on google sheets
- python - How to get the n most frequent or top values per column in python pandas?
- python-3.x - Good practice to implement a ThreadPool of intensive processing inside a Django App
- java - simulate touch events on Android
- reactjs - React Testing onClick Console.log
- c# - R1C1-formulas in Gembox.Spreadsheet
- python - 如何根据模糊条件从 Numpy 数组中选择值?
- macos - Powerpoint 的官方文档 AppleScript 命令在哪里?