4

I want to redirect a URL to a different URL. For example, if I were to type in:

google.com

and hit enter, it should redirect me to:

yahoo.com

I was at a previous thread and found a code for this, but unfortunately, it works on ALL URLs, which I don't want. Also, once the redirect is complete (at yahoo.com) the page will reload again, endlessly looping.

EDIT: Current Code:

  // ==UserScript==
// @name        Google to Yahoo
// @description Redirects Google to Yahoo
// @include     http://*.google.*/*
// @version     1
// ==/UserScript==
    if(content.document.location == "http://google.com"){
            window.location.replace("http://yahoo.com")
}
Community
  • 1
  • 1
Snipahar
  • 51
  • 1
  • 1
  • 4
  • You're running this through Greasemonkey, correct? It's been a while since I did Greasemonkey, but the `@include` directive should have prevented it from working on all URLs. – Shoaib Jun 10 '12 at 20:18

1 Answers1

7

The script that you posted simply forwards the user, it never checks what page the user is loading. Since Greasemonkey is Javascript, you can use just get the URL of the current page and compare it.

Get the URL with

var current_location = content.document.location;

And then compare it. I think it would go like this:

if(content.document.location == "http://google.com"){
    window.location.replace("http://yahoo.com")
}

edit

Going on what Shoaib said, you can use the include directive in a Greasemonkey script. So, at the top you would put

// @include     http://*.google.*/*

This would run the script on every google subdomain in every country on every page and no others.

edit 2

Using the namespace directive would make it:

// ==UserScript==
// @name        Redirect Google
// @namespace   http://domain.com/directory
// @description Redirect Google to Yahoo!
// @include     http://*.google.*/*
// ==/UserScript==

window.location.replace("http://yahoo.com");
citruspi
  • 6,709
  • 4
  • 27
  • 43
  • About `"@namespace"`: According to this answer: [What is the Greasemonkey namespace needed for?](http://stackoverflow.com/a/386616/606539), the `@namespace` directive is used to avoid naming collisions. Typically, the value for `@namespace` should be set to "A URL that *you* control", where "you" is typically the script writer. If an owned URL is not available, then any "globally unique" text should be okay. In this (Great!) answer, it should be noted that `@namespace` is set as a placeholder and should probably be modified by anyone incorporating this script or publishing it in a repository. – Kevin Fegan Dec 02 '16 at 19:54