I have a strange issue from a client in that our code, which they include uses onbeforeunload() to trigger a dialog, but they are also including another companies code which also binds this event handler.
Is it possible for both to execute at the same time?
I’ve been reading this, http://oreilly.com/catalog/9780596101992 “JavaScript: The Definitive Guide, Fifth Edition” to try and help better understand what is happening in the browsers internals and the Javascript stack, but it’s proving quite mind bending.
I understand from reading the book that some events can be executed all at the same time if they are attached using the Level 2 API addEventListener() but the order will be up to the browser. However there is no mention of the onbeforeunload() event. Just the onunload().
Which leads me to the second part of the question. If an event is triggered in onbeforeunload() am I right in thinking that unless it returns true, the onunload() will never be called?
If anyone can shed some light on it, or hook me up with a nice tutorial/guide on either having multiple event handlers assigned to the same event, or specifically on these two events that would be ace.
Not literally at the same time, no — Javascript in browsers is (currently) single-threaded. So there can be multiple handlers for the
onbeforeunloadevent, but they’ll be called serially, not simultaneously. At least in theory; in practice, it looks like only one of them is called (see below).If any
onbeforeunloadhandler cancels the unload, noonunloadhandler will be called. You cancel the unload by doing two things (because browsers differ here): First, you assign a string to thereturnValueproperty of theeventobject, and then you return that string out of the function. Details here and here. (The string is used as a prompt, allowing the user to decide whether to cancel the unload.)Quick Test
So much for theory, let’s look at what actually happens:
On Chrome, IE, and Firefox, I only ever see a notification from one of the
onbeforeunloadhandlers, even when I say it’s okay to go ahead and leave. I expect this is probably because otherwise, a sufficiently-irritating page could just register a bunch of handlers and keep nagging the user to stay on the page.After the (one) question, if I allow navigation to continue, I get both unload messages.