"chrome extension, making a link from key words in the body" Code Answer

1

i wondered a few times on what's the best way to get the text nodes and meant to look at treewalking, so i did this time. following is the test page i made, i can't say if this is the best way but may suite your needs.

treewalker.html

<html>
  <head>
    <style>
    </style>
    <script src="treewalker.js"></script>
  </head>
  <body>
    <div>this is a div</div>
    <div><div id='testevent'>test event</div>this is a div 000-000-0000</div>
    <div>this is a div 000-000-0000</div>
     <div>this is<a href='sf'>bleh 000-000-0000 a div</a></div>
  </body>
</html>

treewalker.js

function onload() {

  document.queryselector('#testevent').onclick = function() {
    alert('clicked')
  };

  // here starts the bit for your content script
  var re = /(d*[/-]*[0-9][0-9][0-9][/ -]*[0-9][0-9][0-9][/ -]*[0-9][0-9][0-9][0-9][ ]*)/g;
  var regs;

  var walker = document.createtreewalker(
  document.body, nodefilter.show_text, function(node) {
    if((regs = re.exec(node.textcontent))) {
      // make sure the text nodes parent doesnt have an attribute we add to know its allready been highlighted
      if(!node.parentnode.classlist.contains('highlighted_text')) {
        var match = document.createelement('a');
        match.appendchild(document.createtextnode(regs[0]));
        match.href = 'http://www.google.com';

        // add an attribute so we know this element is one we added
        // im using a class so you can target it with css easily
        match.classlist.add('highlighted_text');

        var after = node.splittext(regs.index);
        after.nodevalue = after.nodevalue.substring(regs[0].length);
        node.parentnode.insertbefore(match, after);
      }
    }
    return nodefilter.filter_skip;
  }, false);

  // make the walker step through the nodes
  walker.nextnode();

  // and it ends here
}

(function() {
  document.addeventlistener("domcontentloaded", onload);
})();

code stolen from

http://paul.kinlan.me/dom-treewalker/
thats where i got the treewalker code from. problem with his sample is it wraps the match using innerhtml on the parent (a lot of the examples do), this kills the event in the test page.

http://www.the-art-of-web.com/javascript/search-highlight/
showed how to split the text node properly. and for all i know is a better way of doing this, but i was interested in the treewalker way.

edit
i just updated it because if you ran the old version (click the edited link below to see it) failed on the html in this new version. for some reason that i really dont understand it wouldn't wrap the second numner. this new version doesn't work the way all the examples i saw did and seems an abusive way to use treewalker...but it works!

By saeleko on January 19 2022

Answers related to “chrome extension, making a link from key words in the body”

Only authorized users can answer the Search term. Please sign in first, or register a free account.