How can I, without using any third-party libraries such as jQuery, disable the onbeforeunload
event when submitting a form?
I have:
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;
This question is not a duplicate of How to disable beforeunload action when user is submitting a form? or window.onbeforeunload - Only show warning when not submitting form because those are specifically dealing with jQuery.
document.getElementById("confirm_form").addEventListener("submit", function() {
window.onbeforeunload = null;
});
Or, if you want to do this for every form in the page:
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);
}