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?
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');