gmail与以下代码

时间:2018-05-28 08:48:59

标签: javascript google-chrome google-chrome-extension

我的chrome扩展程序的用例是突出显示文本,并在gmail消息中创建这些突出显示的文本,如果文本与主题列表匹配。为此我尝试了只有6个主题,虽然gmail崩溃了。实际上,主题列表将是1000 +

我所做的是在文档加载时,我调用了fetchTopics函数(在实际api中调用以获取主题)并在该函数内部迭代了topicData对象并将主题逐个传递给searchPage函数和分配给re变量,以检查提供的主题是否与gmail收件箱内的文本匹配。

这是我的代码

var topicData = [
    {
        id: 1,
        name: 'Courses'
    },
    {
        id: 2,
        name: 'miss'
    },
    {
        id: 3,
        name: 'out'
    },
    {
        id: 4,
        name: 'your'
    },
    {
        id: 5,
        name: 'savings'
    },
    {
        id: 6,
        name: 'and'
    }
];

function fetchTopics() {
    // const apiUrl = `http://localhost:3020/v2/emails`;
    // const headers = new Headers();
    // headers.append('Content-Type', 'application/json');
    return topicData.map(datum => {
        return searchPage(datum.name);
    });
    // fetch(apiUrl, {
    //  method: 'GET',
    //  headers
    // })
    //  .then(function(response) {
    //      return response.json();
    //  })
    //  .then(function(data) {
    //      topicData.map(datum => searchPage(data.name));
    //  })
    //  .catch(function(err) {
    //      console.log('err', err);
    //  });
}

/*  the searchPage function takes an argument which is going
to set the variable re. Then iterate through topic array and call the searchPage function
for each value inside it while passing that value to the function
*/
function searchPage(topic) {
    console.log('topic', topic);
    var re = new RegExp(topic, '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 = `https://app.com/CustomTopic/${
                        regs[0]
                    }`;
                    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() {
    document.addEventListener('click', init);
    fetchTopics();
});

0 个答案:

没有答案