[Greasemonkey] URL redirects

Edward Lee edilee at gmail.com
Fri Apr 22 21:55:15 EDT 2005

On 4/22/05, Alf Eaton <alf at hubmed.org> wrote:
> 2) Might Greasemonkey be able to hook into an earlier Firefox event for
> the purpose of URL redirecting, as at the moment the redirect doesn't
> happen until the original page has finished loading

At least for now, Greasemonkey scripts run after the page has loaded.
If they ran too early, scripts that depend on page content would fail.

> 1) Is there an easier way to write these patterns, perhaps as an array
> of 'matched URL', 'redirect URL' pairs that can be looped through?

Here you go. Because it uses replace to match and use $backreferences,
make sure to match the whole location because otherwise the original
location will be part of the redirected url. Such as matching
'http://gmail.google.com' with 'http://gmail.google.com/gmail?12345'
and replacing it with 'https://gmail.google.com' will make it

(function() {
var redirects = new Array();
function addRedirect(match, target) {
  if (typeof(match) != 'object') {
    match = [match];
    match: match,
    target: target

addRedirect(/^(http.*\/cgi\/reprint\/.+[^pdf])$/, '$1.pdf');
/^(http\:\/\/www\.cell\.com)(\/.*)$/], '$1.example.proxy.fr$2');

var _ = window.location;
for (var i = 0; i < redirects.length; i++) {
  var match = redirects[i].match;
  var target = redirects[i].target;
  for (var j = 0; j < match.length; j++) {
    var tmp = _.href.replace(match[j], target);
    if (tmp != _.href) {
      _.href = tmp;
}) ();

More information about the Greasemonkey mailing list