Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

javascript - Chrome extension, making a link from key words in the body

So that you understand my knowledge base, I am a computer engineering major, and am working a job right now at a medical company over the summer. I have little (almost zero web code experience) but that is mostly what my job wants me to do so I have been trying to figure it all out as fast as I can. I have used a lot of C, and Verilog and C++ in School, so computer "languages" are not new but I am having a hard time figuring this stuff all out.

Anyway, my first assignment has been to build an extension for Chrome that links into our Asterix phone server. All is has to do is find phone numbers on a webpage and turn them into a hyperlink, the hyperlink will be based on the phonenumber clicked, that part is trivial.

So, I read the W3 Schools stuff on HTML, JS, Ajax, Jquery, DOM ect.. so in the past 3 days I have learned a lot =)

This is what I produced:

It didn't seem like I needed a "backround.html" in my case because all I need to do is run a JS file once the page loads to find the phonenumbers and turn them into a link.

so I wrote a single manifest file, and a JS file to search the body for a number and put an tag around it, (currently going to www.google.com)

The good news is that it seems to work.

The bad news is that is makes Gmail freeze while loading, and makes hotmail not connect and not able to update and see new messages.

I didn't think you were even able to "break" the website in that way while making an extension.

All of my code is very small so I am just going to post it here.

manifest.json

   {
  "name": "Typenex Hyperlink-Dialer",

  "version": "1.0",
  "description": "This is a custom built extension for Typenex. This extension identifies phone numbers and allows the user to click the number to initiate a phonecall.",
  "permissions": [
    "tabs", "http://*/*", "https://*/*"
  ],

  "browser_action": {
      "default_title": "Typenex Hyperlink-Dialer",

      "default_icon": "typenex_logo.png"
  },

  "content_scripts" : [
    {
      "matches" : ["http://*/*", "https://*/*"],
      "js" : ["typenex_contentscript.js"],
      "run_at" : "document_idle",
      "all_frames" : false
    }
  ],

  "manifest_version": 2
}

typenex_contentscript.js

var arrayOfNumbers = [];
alert("hi");
var regex =  /d*[/-]*[0-9][0-9][0-9][/ -]*[0-9][0-9][0-9][/ -]*[0-9][0-9][0-9][0-9][ ]*/g;
newBody = document.body.innerHTML;
var i = 0;
do
{
    temp = regex.exec(newBody);
    if (temp != null)
        arrayOfNumbers[i] = temp;
    i++
}
while (temp)
for (var i = 0; i < arrayOfNumbers.length; i++)
{
    newBody = newBody.replace(arrayOfNumbers[i], "<a href='http://www.google.com'>" + arrayOfNumbers[i] + "</a>");
}
document.body.innerHTML = newBody;

I am grateful for any help I can get, if it seems like I am misunderstanding something and you know something I can read that could help that would be great, I have been Google'ing a lot but I might not know enough to even be asking the right question.

I am very open minded if any of you have a better method to tackle this simple extension =)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...