Sometimes your users might lose important information that they’ve been working on by accidentally leaving the page. They can either press the “previous page” or “next page” button by accident, or they can hit the “backspace” key on their keyboard, inadvertently click a link etc.

Luckily you can prevent them from losing their progress by using the following bit of JavaScript code:

window.onbeforeunload = function() {
    if (your_users_might_lose_their_work) {
        dialog_text = "IMPORTANT: Are you sure you want to leave this page?\n\n";
        dialog_text += "WARNING: If you leave this page, you will lose all your current progress.";
        return dialog_text;
    }
};

This code works perfectly fine with all modern browsers, with one small disclaimer: Firefox will not show your custom warning to your users, instead it will simply state “This page is asking you to confirm that you want to leave – data you have entered may not be saved.” However, that’s exactly what you usually want to say in this situation anyway.