最初高亮显示有效,但散列更改时无效

时间:2018-07-19 01:38:08

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

我正在开发一个扩展程序,它用于从服务器获取主题列表,并查找那些主题是否与当前打开的Gmail邮件匹配,如果找到,则突出显示该主题,否则不突出显示。

但是如果已经匹配了6个主题,则不应检查或突出显示其他主题。这个正在工作,但是现在我遇到了一个问题,例如,如果我从当前消息返回并再次出现该消息,则高亮将不会显示。另外,如果我打开另一条消息,则突出显示未完成。

如果我从以下代码段中删除了计数器检查的代码,它会起作用,但是它将突出显示所有匹配的主题,而不仅仅是最多6个主题。

var count = 1;
var highlightAllWords = function(topics) {
  Object.keys(topics.topics).forEach(function(topic) {
    if (count <= 6) {
      highlightTopic(topic);
      if (topic !== null || !topic.length) {
        count += 1;
      }
    }
  });
};

// init highlight CSS
var ruleExistenceDict = {};
var sheet = (function() {
  var style = document.createElement('style');
  style.appendChild(document.createTextNode('')); // WebKit hack @@
  document.head.appendChild(style);
  return style.sheet;
})();

var topicData = {
  topics: {
    hostname: 4,
    cto: 19,
    aws: 382,
    its: 26,
    repo: 15,
    unsubscribe: 65,
    bitbucket: 313,
    having: 28,
    devops: 414,
    frontend: 25,
    stepin: 105,
    username: 121,
    deployed: 24,
    vimeo: 460,
    gmail: 156,
    rds: 486,
    clicked: 9,
    lai: 850
  }
};

function fetchTopics() {
  // api call will be done here but for now its done with dummy object
  searchPage(topicData);
}

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

var count = 1;
var highlightAllWords = function(topics) {
  Object.keys(topics.topics).forEach(function(topic) {
    if (count <= 6) {
      highlightTopic(topic);
      if (topic !== null || !topic.length) {
        count += 1;
      }
    }
  });
};

function highlightTopic(topic) {
  // let found = 0;
  let isCompleted = false;
  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;
          // if (found <= 6) {
          result = NodeFilter.FILTER_ACCEPT;
          return result;
          // }
        }
      }
    },
    false
  );

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

  var nodeList = [];
  // let count = 1;
  console.log('count near nextNode', count);
  while (treeWalker.nextNode()) {
    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);
    });
  });
}

var highlightRange = function(range) {
  const bgColorCode = '#000000';
  var anchor = document.createElement('A');
  var selectorName = (anchor.className = 'highlighted_text');
  anchor.classList.add('highlighted_text');
  if (!ruleExistenceDict[bgColorCode]) {
    sheet.insertRule(
      [
        '.',
        selectorName,
        ' { background: #',
        bgColorCode,
        ' !important; }'
      ].join(''),
      0
    );
    ruleExistenceDict[bgColorCode] = true;
    console.log(sheet);
  }
  anchor.appendChild(range.extractContents());
  anchor.href = `https://app.com/profile/topics/${range.extractContents()}`;
  range.insertNode(anchor);
};

这是完整的代码:

https://gist.github.com/MilanRgm/5d6b9861be1326ba8b049ccfb6c3b376

1 个答案:

答案 0 :(得分:0)

您应该在函数内部声明count变量,以便每次刷新页面时,count将从1开始。请按以下方式更新您的代码:

var highlightAllWords = function(topics) {

  var count = 1;

  Object.keys(topics.topics).forEach(function(topic) {

    if (count <= 6) {
        highlightTopic(topic);

        if (topic !== null || !topic.length) {
           count += 1;
        }
    }
});
};