最初高亮显示有效,但散列更改时无效 [英] Highlighting works initially but does not when hash changes

查看:69
本文介绍了最初高亮显示有效,但散列更改时无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am developing an extension, which is about fetching the list of topics from the server and find if those topics match with the currently opened Gmail messages or not, if found then highlight that topic otherwise don't.

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

But if already 6 topics are matched, then it should not check or highlight other topics. This one is working but now I have a problem like if I go back from the current message and again come to that message then highlight won't be shown. Also if I open another message, the highlight is not done.

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

If I remove the code of counter check from the following snippet it works but this will highlight all the topics that are matched instead of just max 6 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;
      }
    }
  });
};

// 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

推荐答案

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

You should declare the count variable inside the function, so that every time you refresh the page, the count will start from 1 again. Please update your code as follows:

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;
        }
    }
});
};

这篇关于最初高亮显示有效,但散列更改时无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆