I'm attempting to make a Chrome extension that on load finds the first instance of a string and adds some details, as well as a link.
From what I can tell a TreeWalker is the best approach, so I've adapted this example (Dom TreeWalker).
This works well (though my implementation is inefficient). But I want the effect to be subtle, so I added a requirement that the string needs to appear in a paragraph to cut down on the chances of replacing the text in any menus or titles.
Now the behaviour is erratic (some replacements are made, others are not).
I know my .replace
implementation at the end is not the right solution.
Any ideas?
var companies = [
"Apples",
"Black Beans",
"Sweet Potatoes"
];
var re = new RegExp(companies.join("|"), "i");
var walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
function(node) {
var matches = node.textContent.match(re);
//look for matching text but also accept only those in paragraphs
if((matches) && (node.parentNode.nodeName == "P")) {
return NodeFilter.FILTER_ACCEPT;
} else {
return NodeFilter.FILTER_SKIP;
}
},
false);
var nodes = [];
while(walker.nextNode()) {
nodes.push(walker.currentNode);
}
node=nodes[0]; //just replace the first hit within a paragraph
node.parentNode.innerHTML = node.parentNode.innerHTML.replace("Apples", "Apples [nutritional fact <a href='http://nutritionalinfo.com/apples'>Apples</a> ]");
node.parentNode.innerHTML = node.parentNode.innerHTML.replace("Black Beans", "Black Beans [nutritional fact <a href='http://nutritionalinfo.com/apples'>Apples</a> ]");
node.parentNode.innerHTML = node.parentNode.innerHTML.replace("Sweet Potatoes", "Sweet Potatoes[nutritional fact <a href='http://nutritionalinfo.com/apples'>Apples</a> ]");