|Web Apps In The Browser - BeforeUnload|
|Written by Mike James|
|Monday, 18 February 2013|
Page 2 of 2
Using beforeunload really does solve most of the browser accidentally closing your app problems. The fix can even be retrofitted to existing web pages. For example, if you have a web page that uses a text editor or simply displays a form, you can add:
to the very end of the body of the page and have a good chance of avoiding the user closing the page by accident. Of course, in an ideal world you would also add code to check that there was some data to lose before bothering the user - but better to be over cautious than annoy a user by losing even a small amount of data.
The next question is: Can we do better?
The worst thing about beforeunload is that you can't customize it. You can add a small text message to Chrome and IE but you can't even do this with Firefox. The default dialog boxes are reasonably self-explanatory with Firefox being the best in that it actually mentions the possibility of data loss even though it doesn't let you customize it. Another problem is that Chrome actually uses a different dialog box if the user tries to refresh the page.:
This is likely to be particularly confusing to the innocent user who might well think that refreshing the page will preserve any data they have typed in. Make sure that you craft a short message that mentions data loss for both Chrome and IE to use - and perhaps for Firefox in the future.
Next we come to the question of full customization. You will find many a question on the web about how to show a custom dialog box. The answer is you can't and this is by design.
For security reasons the beforeunload event is locked down. You can't do many of the usual things - no alert, no popups and so on. All that you can do is cancel the event so that the default dialog displays.
The reason is that it was supposed that if the beforeunload event was customizable then malware could redirect a user to another page or site or supply them with false information in some form. The best way to stop this was to take control of what happens out the programmers hands. The same is true of the unload event.
I don't think this is particularly sensible as there are ways of intercepting user actions that should trigger a new page load and popping up an annoying dialog box but we have to learn to live with it.
or email your comment to: email@example.com
To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, Facebook, Google+ or Linkedin, or sign up for our weekly newsletter.
|Last Updated ( Tuesday, 19 March 2013 )|