It could be that because the page has already started unloading by the time that the onunload event is triggered that the page finishes unloading before the alert gets displayed. Usually you can get away with one statement in an onunload though.
Out of interest, what would you suggest as a cross-browser way of informing the user that they are, for example, about to navigate away from a page and in so doing will lose their unsaved work.
Example where this might be useful: composing a message on SitePoint when you accidentally click on a link which takes you away from your current page.
It seems that SP is using the beforeonunload technique, as if you try to navigate away from an unposted message in Chrome, you get a pop up asking you if you really want to do this, whereas Opera will happily navigate you away from the page and your post is lost.
Or, am I approaching the problem from the wrong angle and should I be asking “What’s the best way to autosave a user’s work in case they navigate away from an unposted message”.
What I’d do is to save a draft on a times basis (every 1 minutes, for example) whether that be locally or via an ajax request, and use the onunload event to to fire off another save too. That way you can have an undo system, or step back to one of the previous drafts.[/quote]
Yes, that’s the better way to do things. An undo system is a better interface than a warning system.
Ah ok, that sounds good.
I’ve been doing a bit of reading and it seems that browsers are blocking alerts which fire onunload.
I’m guessing that a save would be unaffected.
Just out of interest, what are you trying to do?
Do you really want an alert box to pop up when the user attempts to leave the site, or are you trying to implement something else and this was just pseudo-code?
I am having the same problem with a site where users are entering critical data into a page using CKEditor.
They click on a Save button on the page to save the data, the same function being executed when the page is unloaded or the window is closed.
I am using “body onunload” which works fine in IE8, but doesn’t work at all in Firefox or Chrome.
None of the other solutions I have found seem to work for Firefox or Chrome and then don’t work for IE8 either.
The users are getting grouchy because they just moved from IE8 to Chrome for entering this data, and Chrome has a habit of updating itself and updating the page, which causes the report content to be lost.
Ideally I want to find an Unload trigger that works in IE8, Chrome and Firefox, but an alternative would be if I could save the data that they were typing every minute, a solution that I see mentioned here. Not sure how to go about that though. Could someone please point me in the right direction.
Since posting this I have investigated autosaves and there is an Autosave plugin for CKEditor which I am now looking at.
Hopefully this will resolve my problem, since I just can’t get any OnUnload functions to work on all browsers.