wordSelect

word discover autoSelect!

  1. // ==UserScript==
  2. // @name wordSelect
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.0.1
  5. // @description word discover autoSelect!
  6. // @author @bpking
  7. // @match *://*/*
  8. // @grant none
  9. // @run-at document-idle
  10. // @license MIT
  11. // ==/UserScript==
  12.  
  13. (() => {
  14. 'use strict';
  15. const upevt = new MouseEvent('mouseup', {
  16. 'view': window,
  17. 'bubbles': true,
  18. 'cancelable': true
  19. });
  20. const downevt = new MouseEvent('mousedown', {
  21. 'view': window,
  22. 'bubbles': true,
  23. 'cancelable': true
  24. });
  25. const selectWord = () => {
  26. if (document.querySelector('wdautohl-customtag')) {
  27. document.querySelectorAll('wdautohl-customtag').forEach(word => {
  28. word.onmouseover = () => {
  29. const range = document.createRange();
  30. //必须选中单词的前后空格,否则沙拉查词无法获取单词的上下文
  31. if (word.previousSibling) {
  32. range.setStart(word.previousSibling, word.previousSibling.length - 1);
  33. } else {
  34. range.setStart(word, 0);
  35. }
  36. if (word.nextSibling) {
  37. range.setEnd(word.nextSibling, 1);
  38. } else {
  39. range.setEnd(word, word.length);
  40. }
  41.  
  42. //console.log('range.toString()', range.toString());
  43. window.getSelection().empty();
  44. window.getSelection().addRange(range);
  45. window.dispatchEvent(downevt);
  46. window.dispatchEvent(upevt);
  47. window.dispatchEvent(downevt);
  48. window.dispatchEvent(upevt);
  49. };
  50. });
  51.  
  52. }
  53. };
  54.  
  55. const debounce = function (fn, timeout) {
  56. let timer;
  57. return function () {
  58. if (timer) {
  59. clearTimeout(timer);
  60. }
  61. timer = setTimeout(function () {
  62. fn.apply();
  63. }, timeout);
  64. }
  65. }
  66.  
  67. const observer = new MutationObserver(debounce(selectWord, 1000));
  68. const options = {
  69. 'childList': true,
  70. 'attributes': true,
  71. 'characterData': true,
  72. 'subtree': true
  73. }
  74. observer.observe(document.body, options);
  75.  
  76. })();