HighlightSelected

Highlight selected text on doubleclick

当前为 2018-06-21 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HighlightSelected
  3. // @namespace novhna
  4. // @description Highlight selected text on doubleclick
  5. // @include *
  6. // @version 0.0.1
  7. // @grant GM_getValue
  8. // @grant GM_setValue
  9. // ==/UserScript==
  10.  
  11. const highlighter = text => `<span
  12. class="tmp-highlighted"
  13. style="background-color: yellow;"
  14. >${text}</span>`
  15.  
  16. const replacer = selected => text => (text === selected
  17. ? highlighter(text)
  18. : text)
  19.  
  20. document.body.addEventListener('dblclick', () => {
  21. const selected = document.getSelection().toString().trim()
  22. if (!selected) return false
  23. const page = document.body.innerHTML
  24. const re = RegExp(`<.+?>|\\b(${selected})\\b`, 'g')
  25. console.log(selected, re)
  26.  
  27. const newPage = page.replace(re, replacer(selected))
  28. document.body.innerHTML = newPage
  29. })