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');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…