5

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.

1

3 Answers 3

7

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?'; }; 
Sign up to request clarification or add additional context in comments.

4 Comments

Well, if you can catch it, you can alter the target: return false, hence cancel the event and fire a new one with the correct URL...
@Boldewyn: Returnign false should not work. You must return a string only.
That's true, I've already tried that, although I wouldn't know how to get the target. I'd only use this answer a last resort.
The event e doesn't seem to contain the target url.
0

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

1 Comment

Thanks, I'm not completely sure how to use this, is it possible you can provide a small example?
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; } 

2 Comments

Some calls I don't have control over, so I'd need a way to catch arbitrary redirects.
I don't know of any way to catch arbitrary javascript redirects in all browsers from ordinary javascript.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.