[英]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.). 假设我有一个页面,我想在其中向每个网址(还包括图片等)附加一个参数(例如
?name=fc
)。
I'm trying to do this with greasemonkey using a regex, but it doesn't seem to work (ie, 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. 我的JavaScript知识几乎为零,所以请多多包涵。
So the question is, what's wrong with that JavaScript? 所以问题是,JavaScript有什么问题?
for(var i = 0; i < document.links.length; i++) {
document.links[i].href += "?name=fc"
}
You should just use the document.links attribute. 您应该只使用document.links属性。 This will append "?name=fc" to all links (a's and img's etc).
这会将“?name = fc”附加到所有链接(a和img等)。
//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' src
s 正如Mike Lewis在另一个答案中指定的那样,代替
loop 1 and 3
您可以使用他的答案编写一个循环,但是对于图像的src
仍然需要loop 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.