SelectAndGo

Search with selected text by pressing s(Google), t(Translate) or o(Oxford) within 2 seconds.

  1. // ==UserScript==
  2. // @name SelectAndGo
  3. // @namespace com.gmail.fujifruity.greasemonkey
  4. // @version 1.3
  5. // @description Search with selected text by pressing s(Google), t(Translate) or o(Oxford) within 2 seconds.
  6. // @author fujifruity
  7. // @match *://*/*
  8. // @grant GM.openInTab
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. {
  13. const timeoutMs = 2000
  14.  
  15. const shortcuts = selection => ({
  16. s: () => GM.openInTab("https://www.google.com/search?q=" + selection, false),
  17. t: () => GM.openInTab("https://translate.google.com/#en/ja/" + selection, false),
  18. i: () => GM.openInTab("https://www.google.com/search?tbm=isch&q=" + selection, false),
  19. m: () => GM.openInTab("https://www.google.com/maps/search/" + selection, false),
  20. o: () => {
  21. const url = "https://www.oxfordlearnersdictionaries.com/search/english/?q="
  22. // the website requires hyphen-separated words
  23. const query = selection.replace(/\s+/g, '-')
  24. GM.openInTab(url + query, false)
  25. },
  26. c: () => alert(selection.length + ' characters') // count chars
  27. })
  28.  
  29. const onKeydown = event => {
  30. if (["INPUT", "TEXTAREA"].includes(event.target.tagName)) return
  31. if (event.ctrlKey || event.altKey) return
  32. const selection = window.getSelection().toString()
  33. shortcuts(selection)[event.key]()
  34. }
  35.  
  36. const unsetShortcut = () => window.removeEventListener('keydown', onKeydown)
  37.  
  38. window.addEventListener('selectstart', () => {
  39. window.addEventListener('keydown', onKeydown)
  40. // unset shortcuts in seconds.
  41. window.onmouseup = () => {
  42. setTimeout(unsetShortcut, timeoutMs)
  43. window.onmouseup = null
  44. }
  45. // unset shortcuts when selection is triggerd by ctrl+a
  46. window.onkeyup = () => {
  47. setTimeout(unsetShortcut, timeoutMs)
  48. window.onkeyup = null
  49. }
  50. })
  51.  
  52. }