4

How would I go about overriding/catching a javascript redirect?

For example:

window.location.href="http://example.com";

The value "http://example.com" would be caught and maybe altered.

Trevor
  • 1,333
  • 6
  • 18
  • 32
  • This might help? http://stackoverflow.com/questions/3522090/event-when-window-location-href-changes – Asken Oct 17 '11 at 07:01

3 Answers3

6

AFAIK you can catch this event but you cannot alter the target url. You could only prompt the user if he wants to cancel the redirect. For this you could subscribe to the before unload event:

window.onbeforeunload = function (e) {
    var e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = 'Are you sure you want to leave the site?';
    }

    // For Safari
    return 'Are you sure you want to leave the site?';
};
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

You could try using __defineSetter()__ but it may not work on host objects.

alex
  • 479,566
  • 201
  • 878
  • 984
  • Thanks, I'm not completely sure how to use this, is it possible you can provide a small example? – Trevor Oct 17 '11 at 06:45
0

Find all code that uses this:

window.location.href="http://example.com";

and change it to this:

openURL("http://example.com");

Then, implement this function where you can control the redirect however you would like:

function openURL(url) {
    // examine url and decide if you want to modify it
    window.location = url;
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979