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


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.


    <script src="treewalker.js"></script>
    <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>


function onload() {

  document.queryselector('#testevent').onclick = function() {

  // 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.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

        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

  // and it ends here

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

code stolen from

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.

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.

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.