0

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> ]");
Chris McFarland
  • 6,059
  • 5
  • 43
  • 63
Steve
  • 1
  • possible duplicate of [Is there a Chrome extension to add mailto links to email addresses?](http://stackoverflow.com/questions/12209628/is-there-a-chrome-extension-to-add-mailto-links-to-email-addresses) (the concepts and answers are identical: Look for some string and replace the found string with something, possibly a HTML element) – Rob W Aug 08 '13 at 07:32
  • close but not a good fit. I need to replace a range of strings with a series of corresponding strings, each of which includes a link, but I don't want to replace anything that isn't plain text and I want to avoid things like spans, h1, etc. – Steve Aug 09 '13 at 02:20
  • Take a few minutes to try and understand the answer in the duplicate. Once you understand it, you will be able to tweak your code to get it working as desired. – Rob W Aug 09 '13 at 08:38
  • Okay, I struggled through it and I see what you mean. I'm barely understanding what I'm doing with this but you definitely pointed me in the right direction. Thanks! – Steve Aug 13 '13 at 23:40

0 Answers0