I'm stuck working out which one of these I should be using: beforeunload
or onbeforeunload
They both seem to be doing very similar things, but with different browser compatibility.
Some context:
I have a form. On page load I serialise the form and save it in a variable. If the user leaves the page I serialise the form and compare the two, to see if there's been any changes. However, if the form is submitted then the event should not be fired.
Example 1
I have this working as expected. I just don't understand the differences between the two:
window.onbeforeunload = function(e) {
if(strOnloadForm != strUnloadForm)
return "You have unsaved changes.";
}
With this line to stop it firing when you save the form (bound to .submit()
)
window.onbeforeunload = null;
Example 2
window.addEventListener("beforeunload", function( event ) {
if(strOnloadForm != strUnloadForm)
event.returnValue = "You have unsaved changes.";
});
With this line to stop it firing when you save the form (bound to .submit()
)
window.removeEventListener("beforeunload");
What the documentation says
I've read the documentation for onbeforeunload and beforeunload.
Under the onbeforeunload
section Notes it states:
You can and should handle this event through window.addEventListener() and the beforeunload event. More documentation is available there.1
Which makes me think I should be using the latter. However the documentation for removeEventHandler says this:
addEventListener()
and removeEventListener()
are not present in older browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of addEventListener()
and removeEventListener()
in implementations which do not natively support it.2
Could somebody please shed some light on the differences for these please, and the best one to use?
1https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Notes
2https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener#Polyfill_to_support_older_browsers
See Question&Answers more detail:
os