Search code examples
javascriptgreasemonkey

Changing all urls on page loading


Let's suppose I have a page in which I'd like to append a parameter (for example ?name=fc) to each and every url (also images etc.).

I'm trying to do this with greasemonkey using a regex, but it doesn't seem to work (i.e., the links on the page don't change).

Here is my code

var txt = document.documentElement.innerHTML;
var exp = "/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig" ;
document.documentElement.innerHTML =( txt.replace(exp, "$1?name=fc"));

My JavaScript knowledge is almost zero, so bear with me.

So the question is, what's wrong with that JavaScript?


Solution

  • //loop 1: change links <a href="..."
    var links = document.getElementsByTagName('a');
    for(var i = 0, len = links.length; i < len; ++i)
       links[i].href = links[i].href + "?name=fc";
    
    //loop 2: change images <img src="..."
    var imgs = document.getElementsByTagName('img');
    for(var i = 0, len = imgs.length; i < len; ++i)
       imgs[i].href = imgs[i].href + "?name=fc";
    
    //loop 3: change image maps <area href="..."
    var areas = document.getElementsByTagName('area');
    for(var i = 0, len = areas.length; i < len; ++i)
       areas[i].href = areas[i].href + "?name=fc";
    

    As specified by Mike Lewis in the other answer in place of loop 1 and 3 you could write one single loop using his answer, but still you need the loop 2 for images' srcs