When the user had made some changes in the page and accidentally clicks some links on the page, you might want to warn the user about the redirection and ask his permission for the operation.
Javascript makes it quite simple to do this operation, with the help of window.onbeforeunload():
window.onbeforeunload = checkRedirection;
function checkRedirection (evt) {
var message = ‘Are you sure you want to leave?‘;
if (typeof evt == ‘undefined’) {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
In case of jQuery you can use the code snippet below:
$(window).beforeunload(function() {
confirm(‘new message: ‘ + this.href + ‘ !’, this.href);
return false;
});/* The following code also works at times – But only in jquery */
$(window).unload(function(){ alert(‘blubb’): }); //Use of unload won’t work in normal javascript in this scenario
This would fire a popup, with the message (Are you sure you want to leave?), in case user clicks on any other links or buttons in the page.