I would like to ramp on extension development by modifying an existing extension. I have zero experience with JavaScript, but i do have experience with C, C++, Java and Python. I chose the Regular Expression Search extension by bizsimon. Here is the JavaScript code of the content script which i am trying to understand.
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { sendResponse(chrome_regex_search(request.exp)); });
function chrome_regex_search(exp) {
var tw=document.createTreeWalker(document.getElementsByTagName("body")[0], NodeFilter.SHOW_TEXT, null, false);
while (node = tw.nextNode()) {
node.parentNode.innerHTML=node.parentNode.innerHTML.replace(/<font class="chrome_search_highlight"[^>]*>(.+)<\/font>/igm, '$1');
}
try {
var pattern=eval("/(>[^<]*)("+exp+")([^<]*<)/igm");
var tw=document.createTreeWalker(document.getElementsByTagName("body")[0], NodeFilter.SHOW_TEXT, null, false);
while(node=tw.nextNode()) {
node.parentNode.innerHTML=node.parentNode.innerHTML.replace(pattern, '$1<font class="chrome_search_highlight" style="background: yellow">$2</font>$3');
}
return {"count": document.getElementsByClassName("chrome_search_highlight").length};
} catch(e) {
return {"count": 0};
}
}
And here are my questions:
What does this code do?
node.parentNode.innerHTML=node.parentNode.innerHTML.replace(/]*>(.+)</font>/igm, '$1');
for your question #1: That code looks like it's trying to strip a <font>
tag from HTML, eg change <font ...>real content here</font>
to real content here
.
just a side comment: prefer using new Regexp(somestring)
to eval("/"+somestring+"/")
, as the eval can lead to a possible security hole. (see MDC docs for syntax particulars)
<font>
tag: specifically those that are of the "chrome_search_highlight" class. In other words, it's walking the node tree of the body element and removing previous search hit highlights. (>[^<]*)
group before, and similar group after, the regexp is there to help ensure that you're matching actual page text, not the name of an HTML element or an attribute name or value. Ie the regexp search hit must be preceded by a >
that is not followed by a <
until after the search hit. Off to bed...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.