Search code examples
javascriptgoogle-chromehyperlinkuserscripts

How to change all links in a page?


For pages like this IP-direct, Google search:

http://62.0.54.118/search?&q=42&oq=42&sourceid=chrome&ie=UTF-8&filter=0


How can I change all the links in that page from search?q to search?&q=?

For example, I want to make the link:

http://62.0.54.118/search?q=42&ei=Xf5bUqHLOKeQ0AWV4YG4Cg&start=10&sa=N&filter=0

into:

http://62.0.54.118/search?&q=42&ei=Xf5bUqHLOKeQ0AWV4YG4Cg&start=10&sa=N&filter=0


How can I make Chrome change the links by automatic script or something like that?


Solution

  • To change those links, on a static page (like your example):

    1. Search for applicable links.
    2. Loop through the links and change them. (Typically using regex.)

    A complete userscript would like like this:

    // ==UserScript==
    // @name     _Modify select Google search links
    // @include  http://YOUR_SERVER.COM/YOUR_PATH/*
    // @include  http://62.0.54.118/*
    // ==/UserScript==
    
    var qLinks  = document.querySelectorAll ("a[href*='?q=']");
    
    for (var J = qLinks.length - 1;  J >= 0;  --J) {
        var oldHref = qLinks[J].getAttribute ('href');
        var newHref = oldHref.replace (/\?q=/, "?&q=");
    
        //console.log (oldHref + "\n" + newHref);
        qLinks[J].setAttribute ('href', newHref);
    }
    


    Save the file as GoogleLinkModify.user.js and then drag it to the extensions page to install. (Or install the Tampermonkey extension and install the script via Tampermonkey).


    Important:

    1. For AJAX-driven pages, install Tampermonkey and use waitForKeyElements().
    2. Google pages are a PITA to script. Beware that even though you change the href, many Google pages will ignore that and also sneakily redirect links just as you click on them. See or open other questions for more on that.