Chris Pietschmann

husband, father, hacker, entrepreneur, futurist, innovator, autodidact

NAVIGATION - SEARCH

JavaScript: window.onbeforeunload Event - Show “Are you sure you want to leave this page?” Message

browser_beforeunload_messageAll web developers have likely seen how inconvenient it can be for a user to edit some data in an application, then click a link/button to go on to the next task, but only to later realize that all changes made were never saved. This can pose a major problem for users, until they get it down that they need to click the “Save” button before leaving the page. Wouldn’t it be nice for the app to remind them to click the “Save” button?

Everyone has seen the “Are you sure you want to leave this page?” message (as shown to the right.). It is actually rather simple to implement, but has seemingly been a secret most web developers are unaware of. Good for us, it is actually really simple to do through the window.onbeforeunload event.

Handle window.onbeforeunload event using jQuery

$(window).bind('beforeunload', function() {
    return 'You have unsaved changes. If you leave the page these changes will be lost.';
});

Handle window.onbeforeunload event using straight JavaScript

window.onbeforeunload = function(e) {
    return 'You have unsaved changes. If you leave the page these changes will be lost.';
};

Browser Support

The onbeforeunload event was first introduced with Internet Explorere 4, and has since been implemented by all the other web browsers. So basically, what ever browser your users are using, you will be able to take advantage of this.

blog comments powered by Disqus