I am writing JavaScript for a plugin that will be used on clients' sites, and need to use a beforeunload
handler to store some information to the user's cookies or localstorage for tracking purposes.
However, since I don't control the clients' sites, I'm concerned about the scenario where the client's page has already defined a beforeunload handler before we set ours. In particular, I'm worried about the case where the client's JavaScript creates a 'beforeunload' handler that returns a string to create an 'Are you sure you want to leave this page?'
-style popup, and the possibility that adding our handler after that may destroy or otherwise interfere with this functionality.
Based upon a little experimentation in the console in Chromium, it seems that if I add handlers using jQuery(window).on('beforeunload', handler)
, then all the handlers get executed in the order they were added and then the existence and content of any confirmation dialog is determined solely by the final non-undefined
return value. So if the last handler added with an explicit return returns null
, no message is shown, and if it returns a string, then a confirmation dialog with that string as its content is shown. This is the behaviour I want; it means that as long as I return undefined
from the beforeunload
handler that I add, I shouldn't break any of our clients' code.
Can I rely upon this behaviour across all browsers, though? How about if the client added their original beforeunload
handler via a mechanism other than jQuery, like explicitly assigning to window.onbeforeunload
or using window.addEventListener
? How is jQuery handling the assignment of multiple handlers behind the scenes?