在使用纯JS提交表单时禁用beforeunload?

问题描述 投票:0回答:1

我如何在不使用任何第三方库(例如jQuery)的情况下,在提交表单时禁用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?window.onbeforeunload - Only show warning when not submitting form的重复,因为它们专门处理jQuery。

javascript onbeforeunload
1个回答
1
投票
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);
}
© www.soinside.com 2019 - 2024. All rights reserved.