[tweetmeme service=bit.ly]
The [recently in webkit] supported onbeforeunload
window event can be very useful to inform the user if they are about to loose some data which they haven’t saved yet etc. So, in your method that the event calls you will probably have some logic to decide if the method should return or not (returning a string from the method causes the message to be displayed to the user).
This is all very well and good, but we came across an instance where outside of this method we wanted to set a variable to stop the message, request a new window.location
(to download an file) and then turn the variable on again. The code looked a little like this:
window.shouldWarnTheUser = false; window.location = '/download/my.file'; window.shouldWarnTheUser = true;
And the onbeforeunload
callback looked a bit like this:
window.onbeforeunload = function() { if (window.shouldWarnTheUser) { return "Some warning!"; } }
This gave us different results between different browsers and took some time for us to figure out why.
Consider the following example:
window.onbeforeunload = function() { console.log("3"); } console.log("1"); window.location = '/download/my.file'; console.log("2");
Question:
What order do the numbers get logged out?
Answer:
- Webkit: 1, 2, 3. (Safari 4.0 and Chrome 4.0 on OS X 10.6.2)
- Firefox: 1, 3, 2. (FF 3.5 on OS X 10.6.2)
- Internet Exploder: 3, 1, 2. – What?! (IE 8 on Vista)
Both understandable depending on how you think the events are fired