首页 > 解决方案 > 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)


我希望在提交之前转换密码,但事实并非如此。

标签: javascriptasync-await

解决方案


您的处理程序根本没有运行,因为侦听器未正确连接:

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你附加的处理程序,不用担心)


推荐阅读