我的chrome扩展的用例是
一旦用户加载了他/她的电子邮件,内容脚本就应该从打开的邮件中读取文本,并查找电子邮件中的任何文本是否与提供的主题对象匹配。如果匹配,它应该创建一个url。例如,如果我的主题对象是
var topic = [{
'name': 'Hello'
},
{'name': 'how are'}
]
在我打开的邮件页面中,如果有一个叫做“你好”的单词,那么这个文本
应该转换为超链接hello。
original -> Hello world, how are you. This is the dummy text.
那就应该是
<a href="https://www.google.com/search/?q=Hello">Hello</a> world, <a href="https://www.google.com/search/?q=how are you">how are you</a>. This is the dummy text
我不知道,所以我在谷歌搜索,在stackoverflow中找到了一个答案。我试图理解那个代码,但对我来说不起作用。我试图了解treewalk,但未能成功。这是我抄的
内容和脚本。js(我承认这是一个
copied code
)
这里是节点。textContent不会获取电子邮件主题和正文。
function onLoad() {
console.log('loaded');
// document.addEventListener('click', init);
var re = /Mumbai/g;
var regs;
var walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
function(node) {
if ((regs = re.exec(node.textContent))) {
if (!node.parentNode.classList.contains('highlighted_text')) {
var match = document.createElement('A');
match.appendChild(document.createTextNode(regs[0]));
match.href = 'http://www.url.com/';
// 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();
// and it ends here
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', onLoad);
} else {
onLoad();
}
这是舱单
"background": {
"scripts": [
"extension/js/background.js"
],
"persistent": true
},
"options_page": "index.html",
"content_scripts": [
{
"matches": ["https://mail.google.com/*", "http://mail.google.com/*"],
"js": ["extension/js/content.js"],
"css": ["extension/css/main.css"]
}
],
"permissions": [
"contextMenus",
"tabs",
"storage",
"https://mail.google.com/*",
"http://mail.google.com/*"
],