How can you replace a link's target in Greasemonkey?

允我心安 提交于 2019-12-05 01:06:46

问题


I'm trying to write a script in Greasemonkey that will replace a link's target with something else, but with my limited Javascript knowledge I don't really know how to do this.

Basically I'm trying to find all links containing a certain string of characters (ex: //a[contains(@href, 'xx')] ), and either replace them with another link, or append something to them (replacing 'abc123.com' with 'zyx987.com' or 'abc123.com' with 'abc123.com/folder').

If you could point me on the right path I'd greatly appreciate it.

edit: This is working code in case someone has the same question in the future:

var links,thisLink;
links = document.evaluate("//a[contains(@href, 'roarrr')]",
    document,
    null,
    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
    null);
for (var i=0;i<links.snapshotLength;i++) {
    var thisLink = links.snapshotItem(i);
    thisLink.href += 'test.html';
}

回答1:


var links = document.evaluate("//a[contains(@href, 'roarrr')]", document, null, 
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); 
for (var i=0; i < links.snapshotLength; i++) 
{ 
  var thisLink = links.snapshotItem(i); 
  thisLink.href += 'test.html'; 
} 



回答2:


You get desired a element(s), and set their src like this:

elem.src = 'http://example.com';

you can also use previous src value:

elem.src += 'index.html';


来源:https://stackoverflow.com/questions/2678615/how-can-you-replace-a-links-target-in-greasemonkey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!