jQuery Disable All Redirections (Links, Form Submissions, window.location changes etc)
Is it possible to use javascript to disable any code that would take the browser away from t开发者_运维技巧he current page?
I have tried the following code but it didn't work:
$(window).unload(function(e){
event.stopPropagation();
event.preventDefault();
return false;
});
I'm guessing this code doesn't work because by the time of unload(), it's too late.
Any other ideas?
Possible implementations: 1. disable any code that redirects 2. bind to all elements that can do this (links, forms, what else am i missing?)
You can pop up a message in the browser asking the user if they wish to leave the page. This works on every event that forces the browser to leave the current page (even form submissions and closing the browser).
Test Page: http://dl.dropbox.com/u/3937673/test.html
JavaScript:
window.onbeforeunload = function(e){
var e = e || window.event;
// For IE and Firefox (prior to 4)
if (e){
e.returnValue = 'Do you want to leave this page?';
}
// For Safari and Chrome
return "Do you want to leave this page?";
};
Or with jQuery:
$(window).bind('beforeunload', function(){
return "Do you want to leave this page?";
});
Just bind it to all of the elements that may start it,
var stopLeaving = function(e){
return confirm('Are you sure you want to leave this page?');
};
$('form').submit(stopLeaving);
$('a').click(stopLeaving);
it should be:
$(window).unload(function(e){
e.stopPropagation();
e.preventDefault();
return false;
});
but it won't work.
quote from api.jquery.com:
After this code executes, the alert will be displayed whenever the browser leaves the current page. It is not possible to cancel the unload event with .preventDefault(). This event is available so that scripts can perform cleanup when the user leaves the page.
http://api.jquery.com/unload/
so, the best you can do is to promt the user if he really wants to leave the page.
精彩评论