Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

javascript - Greasemonkey: Highlight many words in a HTML-File

I want to use Greasemonkey to highlight two words e.g. "Basel, Bern". If I use only Basel the version below works. Not very well but well enough. But when I use two words the highlighting doesn't work.

// ==UserScript==
// @name        highlight-some-words
// @description highlight some words in html
// @grant       none
// ==/UserScript==

document.body.innerHTML= document.body.innerHTML.replace(/Basel|Bern/g, function(m){
    return '<span style="background-color:lightgreen">'+m+'</span>'
});

EDIT: Interesting, the script works on stackoverflow.com but not google.com. Why? And how to modify the script then?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As I said in the comment, works fine (through console) on google.com AFTER searching for Basel and Bern ... perhaps as a GM script it is running too early

@wOxxOm raises a very good point - changing innerHTML will mess up event handlers in the page, a better way to do it would be to change only text nodes. The following is probably not the most efficient way of doing this, but it's a derivative of a greasemonkey script i wrote many many years ago, back when greasemonkey was less than a year old!!

function highlightWord(word) {
    var xpath = "//text()[contains(., '" + word + "')]";
    var texts = document.evaluate(xpath, document.body, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
    for (n = 0; n < texts.snapshotLength; n++) {
        var textNode = texts.snapshotItem(n);
        var p = textNode.parentNode;
        var a = [];
        var frag = document.createDocumentFragment();
        textNode.nodeValue.split(word).forEach(function(text, i) {
            var node;
            if (i) {
                node = document.createElement('span');
                node.style.backgroundColor = 'lightgreen';
                node.appendChild(document.createTextNode(word));
                frag.appendChild(node);
            }
            if (text.length) {
                frag.appendChild(document.createTextNode(text));
            }
            return a;
        });
        p.replaceChild(frag, textNode);
    }
}
highlightWord('Basel');
highlightWord('Bern');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...