Javascript to check any redirection to another page


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.

Feel free to leave a reply here...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: