Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果文本与提供的对象相匹配,则将其超链接_Javascript_Google Chrome_Google Chrome Extension - Fatal编程技术网

Javascript 如果文本与提供的对象相匹配,则将其超链接

Javascript 如果文本与提供的对象相匹配,则将其超链接,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,我的chrome扩展的用例是 一旦用户加载了他/她的电子邮件,内容脚本就应该从打开的邮件中读取文本,并查找电子邮件中的任何文本是否与提供的主题对象匹配。如果匹配,它应该创建一个url文本 var topic = [{ 'name': 'Hello' }, {'name': 'how are'} ] 在我打开的邮件页面中,如果有一个单词叫做“hello”,那么该文本 应转换为超链接hello original -> Hello world, how are you. This is th

我的chrome扩展的用例是

一旦用户加载了他/她的电子邮件,内容脚本就应该从打开的邮件中读取文本,并查找电子邮件中的任何文本是否与提供的主题对象匹配。如果匹配,它应该创建一个url文本

var topic = [{
 'name': 'Hello'
},
{'name': 'how are'}
]
在我打开的邮件页面中,如果有一个单词叫做“hello”,那么该文本 应转换为超链接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
这是舱单

"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/*"
],

这里是一个演示扩展,您可以检查它,然后基于它将逻辑实现到您自己的扩展中


例如,此扩展将把页面中找到的每个
“da”
都变成一个链接,在本例中指向
http://www.url.com/“

在加载整个页面时,它将运行一次,然后在每次哈希更改时(当您打开新邮件时)运行一次

注意:您需要下载才能使扩展正常工作

Manifest.json:

{
  "manifest_version": 2,

  "name": "Example",
  "version": "1.0",

  "content_scripts": [{
    "matches": ["*://mail.google.com/*"],
    "js": ["jquery-3.3.1.min.js", "content.js"]
  }]
}
Content.js

function searchPage() {

    var re = /da/g; // example regex that the function will use for search
    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
    );

    walker.nextNode();
}

// Run when the whole document loads
$(window).bind("load", function() {
    searchPage();
});

// Run on every hash change (when opening new mail)
$(window).on('hashchange', function() {
    searchPage();
});

创建超链接后,应将用户重定向到何处?复制的代码段按预期工作。只需替换
var re=/Mumbai/g与您需要的单词匹配,并
匹配。href='0http://www.url.com/';与您希望它指向的站点。或者我遗漏了你这里的问题?它应该重定向到类似google.com/?q=thathighlightedtextI的内容。我将该部分替换为var re='Mumbai',并加载扩展,然后刷新页面,查看它是否为文本Mumbai创建了链接,但它不起作用。此外,你可以看到,我使用了console.log('loaded'),它在文档加载后也不会显示。该变量是regex,您不能仅用一个字符串字替换它,因为console.log没有显示,您必须将
manifest.json
添加到问题中。非常感谢您的解决方案。我是如何将它映射到对象的,而不是像我在问题topic object中那样的单个字符串('da')?这取决于您存储或修改对象的位置。如果您需要从可使用的扩展的其他部分获取它,如果您在content.js中对它进行了硬编码,您可以迭代对象并使用从对象值构造正则表达式。您推荐哪一种?从后台脚本调用api并使用扩展消息传递或在$(window.bind(“load”,content_script.ii中的function(){})内调用api通过迭代对象并使用RegExp构造函数,您的意思是说我在函数(节点)的作用域内迭代对象并检查它是否匹配?我已经标记了您的解决方案,但需要帮助以清楚地了解最佳方式,因为我需要更快地了解这一点,这是我的第一次尝试。最短的可能路线可能是最好的,这一切取决于您从何处获取对象。如果每次希望content.js运行时都必须从外部源调用API,那么从那里调用API并获取对象。在任何情况下,您都可以将对象分解为任何部分,从中提取搜索页面所需的数据,然后在将这些单词作为参数传递给该函数(例如)后,为每个单词调用该函数“将这些单词作为参数传递给该函数后,为它们调用函数”部分。请给我一个简单的例子好吗?
function searchPage() {

    var re = /da/g; // example regex that the function will use for search
    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
    );

    walker.nextNode();
}

// Run when the whole document loads
$(window).bind("load", function() {
    searchPage();
});

// Run on every hash change (when opening new mail)
$(window).on('hashchange', function() {
    searchPage();
});