I want to show a confirmation dialog if the user wants to leave the page with unsaved form data. What I have is:
window.onbeforeunload = function() {
if
Although window.onbeforeunload works, it's considered bad practice. It's better to use something like the following:
if (typeof window.addEventListener === 'undefined') {
window.addEventListener = function(e, callback) {
return window.attachEvent('on' + e, callback);
}
}
window.addEventListener('beforeunload', function() {
return 'Dialog Text Here';
});
First we check if window.addEventListener exists, which it does not in IE, else we polyfill it, and then we attach the event.