纯JS提交表单时禁用beforeunload?

Disable beforeunload when submitting a form with pure JS?

如何在不使用任何第三方库(例如 [=25=)的情况下,在提交表单时禁用 onbeforeunload 事件?

我有:

HTML:

<form id="confirm_form">
    <input id="confirm_btn" type="submit" value="Confirm Action">
</form>

JS:

function onLeave() {
    return "Are you sure you wish to leave without performing the action?";
}
window.onbeforeunload = onLeave;

这个问题不是 How to disable beforeunload action when user is submitting a form? or window.onbeforeunload - Only show warning when not submitting form 的重复问题,因为它们专门针对 jQuery。

document.getElementById("confirm_form").addEventListener("submit", function() {
    window.onbeforeunload = null;
});

或者,如果您想对页面中的每个表单都执行此操作:

function remove_onbeforeunload() {
    window.onbeforeunload = null;
}
let forms = document.getElementsByTagName("form");
for(let i = 0; i < forms.length; i++) {
    forms.item(i).addEventListener("submit", remove_onbeforeunload);
}