javascript - Chrome 扩展中的 TreeWalker

标签 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();

最佳答案

我最终使用了 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 而不是使用上述方法。

关于javascript - Chrome 扩展中的 TreeWalker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16409871/

相关文章:

javascript - AngularJS 或 Backbone 适合初学者

google-chrome-extension - 使用 OAuth2 切换 YouTube 用户会在 Chrome 中显示以前用户的数据

javascript - 如何在所有 HTML 页面中一次性弹出?

javascript - 如何用async/await解决厄运金字塔?

javascript - 如何更新 React.js 中的对象?

JavaScript Zlib 解压

javascript - 使用 Chrome 扩展更改 navigator.userAgent

javascript - 在滚动条上更改图像 Logo

javascript - 如何判断 angularjs 模态是否打开

google-chrome - 在此页面上检测到 Vue.js。 Devtools 检查不可用,因为它处于生产模式或被作者明确禁用