开发者

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.i开发者_开发问答nnerHTML;
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?


for(var i = 0; i < document.links.length; i++) {
 document.links[i].href += "?name=fc"
}

You should just use the document.links attribute. This will append "?name=fc" to all links (a's and img's etc).


//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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜