Guest User

Untitled

a guest
Jul 18th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.76 KB | None | 0 0
  1. function searchPage(topics) {
  2. highlightAllWords(topics);
  3. }
  4.  
  5. var highlightAllWords = function(topics) {
  6. Object.keys(topics.topics).forEach(function(topic) {
  7. highlightTopic(topic);
  8. })
  9. }
  10.  
  11. function highlightTopic(topic) {
  12. let found = 0;
  13. if (topic == null || topic.length === 0) return;
  14. var topicRegex = new RegExp(topic, 'gi');
  15. var treeWalker = document.createTreeWalker(
  16. document.body,
  17. NodeFilter.SHOW_TEXT,
  18. {
  19. acceptNode: function(node) {
  20. var result = NodeFilter.FILTER_SKIP;
  21. if (topicRegex.test(node.nodeValue)) {
  22. found += 1
  23. console.log('found', found);
  24. if (found <= 6) {
  25. console.log('foound less than 6', found)
  26. result = NodeFilter.FILTER_ACCEPT
  27. return result;
  28. }
  29. };
  30. }
  31. }, false
  32. )
  33.  
  34. var skipTagName = {
  35. "NOSCRIPT": true,
  36. "SCRIPT": true,
  37. "STYLE": true
  38. }
  39.  
  40. var nodeList = [];
  41. while (treeWalker.nextNode()) {
  42. if (!skipTagName[treeWalker.currentNode.parentNode.tagName]) {
  43. nodeList.push(treeWalker.currentNode);
  44. }
  45. }
  46.  
  47. nodeList.forEach(function (n) {
  48. var rangeList = [];
  49. // find sub-string ranges
  50. var startingIndex = 0;
  51. do {
  52. // console.log(word, startingIndex, n.parentNode, n.textContent);
  53. startingIndex = n.textContent.indexOf(topic, startingIndex + 1);
  54. if (startingIndex !== -1) {
  55. var topicRange = document.createRange();
  56. topicRange.setStart(n, startingIndex);
  57. topicRange.setEnd(n, startingIndex + topic.length);
  58. rangeList.push(topicRange);
  59. }
  60. } while (startingIndex !== -1);
  61.  
  62. // highlight all ranges
  63. rangeList.forEach(function (r) {
  64. highlightRange(r);
  65. });
  66. });
  67. }
  68.  
  69.  
  70. // highlight the keyword by surround it by `i`
  71. var highlightRange = function (range) {
  72. const bgColorCode = '#000000';
  73. var anchor = document.createElement("A");
  74. var selectorName = anchor.className = "highlighted_text";
  75. anchor.classList.add("highlighted_text");
  76.  
  77. // range.surroundContents(iNode) will throw exception if word across multi tag
  78. if (!ruleExistenceDict[bgColorCode]) {
  79. sheet.insertRule([".", selectorName, " { background: #", bgColorCode, " !important; }"].join(""), 0);
  80. ruleExistenceDict[bgColorCode] = true;
  81. console.log(sheet);
  82. }
  83. anchor.appendChild(range.extractContents());
  84. anchor.href = `https://google.com/?search=${
  85. range.extractContents()
  86. }`;
  87. range.insertNode(anchor);
  88. };
Add Comment
Please, Sign In to add comment