Search code examples
javascriptgreasemonkeyhttp-redirectuserscriptstampermonkey

How do I switch a page to a different domain using a userscript?


I need to replace specific text, in a URL, using Greasemonkey.

For example, if the page is:

http://adf.st/?u=https%3A%2F%2Finstagram.com%2Fp%2F4XOVEaD5Ca%2F

Then the script will use the following URL:

http://adfa.cc/?u=https%3A%2F%2Finstagram.com%2Fp%2F4XOVEaD5Ca%2F

Note: The rest of the text after adf.st/ is not fixed.


Solution

  • This is a standard-ish problem; use the pattern below.

    The @match line is set to the old domain, and newDomain is set to the desired domain.

    // ==UserScript==
    // @name        _Redirect from one domain to another
    // @match       *://adf.st/*
    // @run-at      document-start
    // @grant       none
    // ==/UserScript==
    
    var newDomain   = "adfa.cc";
    var newURL      = location.protocol + "//"
                    + newDomain                 //-- location.host
                    + location.pathname
                    + location.search
                    + location.hash
                    ;
    /*-- replace() puts the good page in the history instead of the
        bad page.
    */
    location.replace (newURL);