Google Search Terms Highlight

Automatically highlights search terms & full phrases in pages opened by Google search results.

当前为 2016-06-10 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Google Search Terms Highlight
  3. // @namespace GSTH
  4. // @version 3.0
  5. // @run-at document-start
  6. // @description Automatically highlights search terms & full phrases in pages opened by Google search results.
  7. // @include *
  8. // @grant GM_getValue
  9. // @grant GM_setValue
  10. // @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
  11. // @icon https://www.google.ca/images/google_favicon_128.png
  12. // @author drhouse
  13. // ==/UserScript==
  14.  
  15. $(document).ready(function () {
  16.  
  17. var ref = document.referrer;
  18.  
  19. if (location.href.toString().indexOf("https://www.google.") != -1 && ref.indexOf("https://www.google.") != -1){
  20. var gsearchmark = GM_getValue("googleSearchTerm", "");
  21. var tokens = [].concat.apply([], gsearchmark.split('"').map(function(v,i){
  22. return i%2 ? v : v.split(' ');
  23. })).filter(Boolean);
  24. var oldre = /(?:^|\b)(xx)(?=\b|$)/;
  25. //walk(document.body, newre(oldre));
  26. var keys = $.map( tokens, function( value, key ) {
  27. function newre(e){
  28. return RegExp(e.toString().replace(/\//g,"").replace(/xx/g, value), "i");
  29. }
  30.  
  31. function handleText(node, targetRe) {
  32. var match, targetNode, followingNode, wrapper;
  33. match = targetRe.exec(node.nodeValue);
  34. if (match) {
  35. targetNode = node.splitText(match.index);
  36. followingNode = targetNode.splitText(match[0].length);
  37. wrapper = document.createElement('span');
  38. $(wrapper).css('background-color', 'yellow');
  39. targetNode.parentNode.insertBefore(wrapper, targetNode);
  40. wrapper.appendChild(targetNode);
  41.  
  42. if (node.nodeValue.length === 0) {
  43. node.parentNode.removeChild(node);
  44. }
  45. if (followingNode.nodeValue.length === 0) {
  46. followingNode.parentNode.removeChild(followingNode);
  47. }
  48. match = followingNode
  49. ? targetRe.exec(followingNode.nodeValue)
  50. : null;
  51. }
  52. }
  53.  
  54. function walk(node, targetRe) {
  55. var child;
  56. switch (node.nodeType) {
  57. case 1: // Element
  58. for (child = node.firstChild;
  59. child;
  60. child = child.nextSibling) {
  61. walk(child, targetRe);
  62. }
  63. break;
  64.  
  65. case 3: // Text node
  66. handleText(node, targetRe);
  67. break;
  68. }
  69. }
  70. walk(document.body, newre(oldre));
  71. });
  72. }
  73.  
  74. if (location.href.toString().indexOf("https://www.google.") != -1 && location.href.toString().indexOf("/search") != -1){
  75. var googleSearchTerm = $("#lst-ib").val();
  76. GM_setValue("googleSearchTerm", googleSearchTerm);
  77. }
  78. });