Chrome扩展程序中的TreeWalker

时间:2013-05-07 01:35:09

标签: javascript google-chrome-extension

我有一个Chrome扩展程序,用ahref标记替换了一个电话号码。在这个ahref标签中我想调用一个javascript函数。为了简化我使用“javascript:alert('hey')”作为href值。当我执行下面的操作时,我得到警报功能的“regs is not defined”,但是对于console.log,它显示正确的值。我试图附加一个现有的问题,因为它是相关的,但有人删除它,并要求我发布一个新的问题。

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

var re = /(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]??)\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]??|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})/
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 all ready been highlighted
if(!node.parentNode.classList.contains('highlighted_text')) {
 var match = document.createElement('A');
 match.appendChild(document.createTextNode(regs[0]));
 console.log(regs[0]);
 match.href = "javascript:alert(regs[0])";
 console.log(node.nodeValue);

// 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();

2 个答案:

答案 0 :(得分:0)

我最终使用了onclick,但现在我遇到了使用XMLhttpRequest的问题,其域名不同于调用它的域名。 Access-Control-Allow-Origin不允许使用Origin ..

这是我用于onclick事件的代码:

match.setAttribute("onclick", "function make_call(extension, phone) { xmlhttp=new XMLHttpRequest();xmlhttp.open('GET','http://[Domain]/click2call.php?extension='+extension+'&phone='+phone,false); xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xmlhttp.send(null); } ; make_call('210','"+regs[0]+"'); return false; ");

我将看到使用addEventListener而不是使用上述方法。

答案 1 :(得分:0)

我们使用以下代码进行了此操作。

match.setAttribute("title", regs[0]);
match.href = "#";
match.addEventListener("click", function(){ make_call('210',this.title); }, false);

然后我们使用XMLHttpRequest将扩展名和电话号码传递给负责拨打电话的外部脚本。

我们现在唯一的问题是它不适用于gmail或谷歌地图中的电话号码。