Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 the 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?)

like image 796
user599146 Avatar asked Mar 07 '11 22:03

user599146


1 Answers

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?";
});
like image 124
Rocket Hazmat Avatar answered Oct 21 '22 10:10

Rocket Hazmat