首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Chrome扩展中的TreeWalker

Chrome扩展中的TreeWalker
EN

Stack Overflow用户
提问于 2013-05-07 09:35:09
回答 2查看 309关注 0票数 2

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

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

代码语言:javascript
运行
复制
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();
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-08 00:41:27

我们使用下面的代码实现了这一点。

代码语言:javascript
运行
复制
match.setAttribute("title", regs[0]);
match.href = "#";
match.addEventListener("click", function(){ make_call('210',this.title); }, false);

然后,我们使用XMLHttpRequest将分机和电话号码传递给负责进行呼叫的外部脚本。

我们现在唯一的问题是,它不能与gmail或google地图中的电话号码一起工作。

票数 0
EN

Stack Overflow用户

发布于 2013-05-07 23:23:09

我最终使用了onclick,但现在我在使用XMLhttpRequest时遇到了问题,因为它使用的域与调用它的域不同。起源..。Access-Control-Allow-Origin不允许。

下面是我用于onclick事件的代码:

代码语言:javascript
运行
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16409871

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档