2013-05-07 25 views
2

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

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

'console.log'显示正确的值,因为它是在扩展的上下文中执行的,'alert'不是因为它在页面的上下文中。查看[isolated world](http://developer.chrome.com/extensions/content_scripts.html#execution-environment) – BeardFist 2013-05-07 02:02:55

+0

@BeardFist当用户点击链接时调用函数的最佳方式是什么?该功能必须包含用户点击的电话号码。显然建立一个点击拨号扩展。 – 2013-05-07 05:09:15

+0

只需使用['onclick'](https://developer.mozilla.org/en-US/docs/DOM/element.onclick)处理程序,以便它在您的代码中执行。 – BeardFist 2013-05-07 05:14:24

回答

0

我们使用下面的代码得到了这个工作。

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

然后,我们使用XMLHttpRequest,它将扩展名和电话号码传递给负责进行调用的外部脚本。

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

0

我最终使用的onclick但我现在使用的XMLHttpRequest与一个比它被称为不同的域遇到了问题。来源...不受Access-Control-Allow-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,而不是采用上述方法。

+0

您需要为您尝试获取的域添加[主机权限](http://developer.chrome.com/extensions/match_patterns.html)。 – BeardFist 2013-05-07 16:12:15