Greasemonkey:突出显示HTML文件中的许多单词

kam*_*ame 1 html javascript greasemonkey highlight

我想用Greasemonkey来突出两个词,例如"巴塞尔,伯尔尼".如果我只使用巴塞尔,则以下版本有效.不是很好,但足够好.但是,当我使用两个单词时,突出显示不起作用.

// ==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>'
});
Run Code Online (Sandbox Code Playgroud)

编辑:有趣的是,该脚本适用于stackoverflow.com但不适用于google.com.为什么?那么如何修改脚本呢?

Jar*_*a X 5

正如我在评论中所说,在搜索巴塞尔和伯尔尼之后,google.com上的工作正常(通过控制台)...也许作为GM脚本它运行得太早

@wOxxOm提出了一个非常好的观点 - 更改innerHTML将会破坏页面中的事件处理程序,更好的方法是只更改文本节点.以下可能不是最有效的方法,但它是许多年前我写的一个关键词脚本的衍生物,当时的油脂不到一年!

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');
Run Code Online (Sandbox Code Playgroud)