OnTheFly
OnTheFly

Reputation: 2101

Can i detect and prevent JavaScript-driven redirect from within Firefox extension?

Basically, i want to make Firefox obey "Warn me when web sites try to redirect or reload the page" user preference. Currently, this is really open sesame for any kind of doorway writers etc.

Please find the detailed description of this misbehaviour in related superuser post.

Upvotes: 3

Views: 1250

Answers (2)

Wladimir Palant
Wladimir Palant

Reputation: 57681

You can use Object.watch() to intercept changes of some properties like window.location:

function onLocationChange(id, oldval, newval)
{
  if (confirm("Do you want to navigate to " + newval + "?"))
    return newval;
  else
    return oldval;
}
wnd.watch("location", onLocationChange);
wnd.document.watch("location", onLocationChange);
wnd.location.watch("href", onLocationChange);

You would have to similarly intercept assignments to other window.location properties like host or pathname. The big disadvantage of this approach: there can be only one watcher. If the page installs its own watcher or simply calls wnd.unwatch("location") all your detection will be gone.

How to get to the window before any page JavaScript has a chance to run depends on whether you are using the Add-on SDK or whether you have a classic add-on. If you are using the Add-on SDK then you use the page-mod module with contentScriptWhen parameter set to start. In the code example above you replace wnd by unsafeWindow (the window has to be accessed directly, otherwise it won't work).

In a classic add-on you register an observer for the content-document-global-created notification. Here you also have to access the window directly:

var wnd = XPCNativeWrapper.unwrap(subject);

See documentation on XPCNativeWrapper.unwrap().

Upvotes: 3

pseudosavant
pseudosavant

Reputation: 7244

A "JavaScript-driven redirect" would be done by using the window.location property. All you would need to do is replace that property's setter function as soon as the page loads.

Here is a John Resig blog post on defining setters and getters for properties. http://ejohn.org/blog/javascript-getters-and-setters/

I wasn't able to override the default window.location setter using client side js, but it may be possible using a more privileged extension environment though.

Upvotes: 1

Related Questions