HighlightSelected

Highlight selected text on doubleclick

  1. // ==UserScript==
  2. // @name HighlightSelected
  3. // @namespace novhna
  4. // @description Highlight selected text on doubleclick
  5. // @include *
  6. // @version 0.0.2
  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. const replacer = selected => text => text === selected
  16. ? highlighter(text)
  17. : text
  18. const cleaner = () => document
  19. .querySelectorAll('span.tmp-highlighted')
  20. .forEach(tag => tag.outerText = tag.innerText)
  21.  
  22. document.body.addEventListener('dblclick', () => {
  23. cleaner()
  24. const selected = document.getSelection().toString().trim()
  25. if (!selected) return false
  26. const page = document.body.innerHTML
  27. const re = RegExp(`<.+?>|\\b(${selected})\\b`, 'g')
  28. console.log(`[${selected}]`, re)
  29.  
  30. const newPage = page.replace(re, replacer(selected))
  31. document.body.innerHTML = newPage
  32. })