无法突出显示最多6个gmail内容

时间:2018-07-18 06:49:55

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

我正在开发一个扩展,该扩展用于从服务器获取主题列表,并查找那些主题是否与当前打开的gmail消息匹配,如果找到,则突出显示该主题,否则不突出显示。但是,如果已经匹配了6个主题,则不应检查或突出显示其他主题。

我已使用treewalker来抓取gmail内容,因此匹配的内容将突出显示为

function searchPage(topics) {
    highlightAllWords(topics);
}

var highlightAllWords = function(topics) {
    Object.keys(topics.topics).forEach(function(topic) {
        highlightTopic(topic);
    })
}

function highlightTopic(topic) {
    let found = 0;
    if (topic == null || topic.length === 0) return;
    var topicRegex = new RegExp(topic, 'gi');
    var treeWalker = document.createTreeWalker(
        document.body,
        NodeFilter.SHOW_TEXT,
        {
            acceptNode: function(node) {
                var result = NodeFilter.FILTER_SKIP;
                if (topicRegex.test(node.nodeValue)) {
                    found += 1
                    console.log('found', found);
                    if (found <= 6) {
                        console.log('foound less than 6', found)
                        result = NodeFilter.FILTER_ACCEPT
                        return result;
                    }
                };
            }
        }, false
    )

    var skipTagName = {
        "NOSCRIPT": true,
        "SCRIPT": true,
        "STYLE": true
    }

    var nodeList = [];
    while (treeWalker.nextNode()) {
        if (!skipTagName[treeWalker.currentNode.parentNode.tagName]) {
            nodeList.push(treeWalker.currentNode);
        }
    }

    nodeList.forEach(function (n) {
        var rangeList = [];
        // find sub-string ranges
        var startingIndex = 0;
        do {
            // console.log(word, startingIndex, n.parentNode, n.textContent);
            startingIndex = n.textContent.indexOf(topic, startingIndex + 1);
            if (startingIndex !== -1) {
                var topicRange = document.createRange();
                topicRange.setStart(n, startingIndex);
                topicRange.setEnd(n, startingIndex + topic.length);
                rangeList.push(topicRange);
            }
        } while (startingIndex !== -1);

        // highlight all ranges
        rangeList.forEach(function (r) {
            highlightRange(r);
        });
    }); 
}


// highlight the keyword by surround it by `i`
var highlightRange = function (range) {
    const bgColorCode = '#000000';
    var anchor = document.createElement("A");
    var selectorName = anchor.className = "highlighted_text";
    anchor.classList.add("highlighted_text");

    // range.surroundContents(iNode) will throw exception if word across multi tag
    if (!ruleExistenceDict[bgColorCode]) {
        sheet.insertRule([".", selectorName, " { background: #", bgColorCode, " !important; }"].join(""), 0);
        ruleExistenceDict[bgColorCode] = true;
        console.log(sheet);
    }
    anchor.appendChild(range.extractContents());
    anchor.href = `https://google.com/?search=${
                        range.extractContents()
                    }`;
    range.insertNode(anchor);
};

突出显示gmail邮件中匹配的内容,但突出显示6个​​以上的内容。我已经截取了屏幕截图,它是这样的

enter image description here

在计数器增加并在treewalker.nextnode()中检查后更新

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

您的代码中有两个语法错误。您在此语句末尾缺少分号

found += 1;

其次,还有一个额外的“;”在函数(节点)的末尾。

然后您可以在以下代码段中将计数器检查添加为

var count=1;
while (treeWalker.nextNode() && count<=6) {
    if (!skipTagName[treeWalker.currentNode.parentNode.tagName]) {
        nodeList.push(treeWalker.currentNode);
        count=count+1;
    }
}

因此,功能HighlightTopic(topic)的最终脚本将类似于

function highlightTopic(topic) {
let found = 0;
if (topic == null || topic.length === 0) return;
var topicRegex = new RegExp(topic, 'gi');
var treeWalker = document.createTreeWalker(
    document.body,
    NodeFilter.SHOW_TEXT,
    {
        acceptNode: function(node) {
            var result = NodeFilter.FILTER_SKIP;
            if (topicRegex.test(node.nodeValue)) {
                found += 1;
                console.log('found', found);
                if (found <= 6) {
                    console.log('foound less than 6', found)
                    result = NodeFilter.FILTER_ACCEPT
                    return result;
                }
            }
        }
    }, false
)

var skipTagName = {
    "NOSCRIPT": true,
    "SCRIPT": true,
    "STYLE": true
}

var nodeList = [];
var count=1;
while (treeWalker.nextNode() && count<=6) {
    if (!skipTagName[treeWalker.currentNode.parentNode.tagName]) {
        nodeList.push(treeWalker.currentNode);
        count=count+1;
        console.log('count:'+count);
    }
}

nodeList.forEach(function (n) {
    var rangeList = [];
    // find sub-string ranges
    var startingIndex = 0;
    do {
        // console.log(word, startingIndex, n.parentNode, n.textContent);
        startingIndex = n.textContent.indexOf(topic, startingIndex + 1);
        if (startingIndex !== -1) {
            var topicRange = document.createRange();
            topicRange.setStart(n, startingIndex);
            topicRange.setEnd(n, startingIndex + topic.length);
            rangeList.push(topicRange);
        }
    } while (startingIndex !== -1);

    // highlight all ranges
    rangeList.forEach(function (r) {
        highlightRange(r);
    });
}); 

}

如果有效,请更新我。

谢谢

编辑:

并按如下所示更新功能highlightAllWords:

var highlightAllWords = function(topics) {

var count=1;
Object.keys(topics.topics).forEach(function(topic) {
    if(count<=6){

    highlightTopic(topic);
    console.log('counter:'+count);
    if (topic != null && topic.length != 0)
        count=count+1;

    }

})

}