[Greasemonkey] newsbie-question how to change and replace a link with greasemonkey

Neil Greenwood neil.greenwood.lists at gmail.com
Mon Feb 6 08:22:32 EST 2006


On 05/02/06, Tina Weller <blond.woman at googlemail.com> wrote:
>
> thx all for your help. i found a little script, which should exactly do
> what
> I want. The problem is, that this litte script works well replacing
> visible
> text. But it does not replace the links. Can anyone tell my why this is
> so?
> If I understand it right, it should replace all the text:


Hi Tina,

The reason is to do with how the script is collecting the elements to
replace.

// DumbQuotes
> [snip]
> textnodes = document.evaluate(
>     "//text()",
>     document,
>     null,
>     XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
>     null);


It's the line above, which gets all the text nodes. This means it gets all
the text in the document (including extra whitespace), but not the text or
URLs of links.

To get what you want, you might try something like:

linknodes = document.evaluate(
    "//a",
    document,
    null,
    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
    null);

for (var i = 0; i < textnodes.snapshotLength; i++) {
>     node = textnodes.snapshotItem(i);
>     s = node.data;
>     for (key in replacements) {
>     s = s.replace(regex[key], replacements[key]);
>     }
>     node.data = s;
> }


To process them, you'd change this loop to do something like the following:


for (var i = 0; i < linknodes.snapshotLength; i++) {
    link = linknodes.snapshotItem(i);
    linkUri = link.href;
    linkText = link.text;
    // do your replacement here on linkUri and/or linkText
}


HTH. Completely untested, so watch out!

Neil.


More information about the Greasemonkey mailing list