On a web page I can use the javascript onbeforeunload event to warn a user they are about to leave the page.

window.onbeforeunload = function() {
    return 'Woah there, are you sure you want to leave this great page?'; 

For an example see https://rawgit.com/jonnymoo/b960c889a6152ffd4a1ff32437991442/raw/leave.html

Under what context (if any) is this a good device to use?

For example I can imagine that if it is over used it may annoy a user and drive them away from your service. On the other hand if under used, you could possibly lose work unexpectedly. Are there any best practice guidelines?

1 Answer 1


I can think of at least the following as good candidates:

  1. If a user is filling details into a form and you are not persisting the data across pages.

For instance, a user providing his address at checkout on an online shopping site, may decide to go back to add a couple more details. In such a case you may wish to ensure that users are aware that their data will be lost if they navigate away from the page.

  1. If you are expecting the user to be redirected onto an important page.

For example, if you are redirecting a user to a payment gateway, it could be one of the options to prevent users from navigating away by mistake.

Note that although these are possible cases for use of onbeforeunload, I would strongly prefer to use alternate methods, whenever possible.

A key reason for avoiding it is, as you pointed out, some browsers may not fully support the feature.

Another reason being that you could always design your application better to avoid this. In case 1 above, you could ensure that the data is saved in view-state so that user gets the data prepopulated when they come back to the checkout page. In case 2, you could provide a nice warning on the page asking users to wait while the page redirects (as most websites do).

  • 1
    I think you make a really good point with "I would strongly prefer to use alternative methods". I wonder if it is possible to always design a better experience than using onbeforeunload. Maybe this is actually a key indicator that the design is wrong in the first place?
    – Jonny
    Nov 19, 2016 at 14:30
  • I agree. It could provide an indication of scope for improvement. Nov 19, 2016 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.