NoMouseGoogle

Shortcuts for Google Search results. j/k to move focus, l/h to open in new/background tab.

当前为 2021-12-25 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name NoMouseGoogle
  3. // @namespace com.gmail.fujifruity.greasemonkey
  4. // @version 1.6
  5. // @description Shortcuts for Google Search results. j/k to move focus, l/h to open in new/background tab.
  6. // @author fujifruity
  7. // @include https://www.google.com/search*
  8. // @grant GM.openInTab
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. {
  13. const items = [...document.querySelectorAll('#rso .g')].filter(
  14. e => e.querySelectorAll(':scope > div').length == 1
  15. )
  16. const open = inBackground => {
  17. const url = findCurrentItem().querySelector('a').href
  18. GM.openInTab(url, inBackground)
  19. }
  20. const tag = "noMouseGoogleCurrentItem"
  21. const findCurrentItem = () => items.find(e => e.hasAttribute(tag))
  22.  
  23. const moveCursor = step => {
  24. const currentItem = findCurrentItem()
  25. const r = currentItem.getBoundingClientRect();
  26. const isCurrentItemVisible = 0 < r.top && r.top < window.innerHeight
  27. || 0 < r.bottom && r.bottom < window.innerHeight
  28. if (!isCurrentItemVisible) {
  29. const dist = e => {
  30. const r = e.getBoundingClientRect()
  31. return Math.abs(window.innerHeight - (r.top + r.bottom))
  32. }
  33. const nearestItem = items.reduce((acc,e) => dist(acc) < dist(e) ? acc : e )
  34. select(nearestItem)
  35. return
  36. }
  37. const nextIdx = (items.indexOf(currentItem) + step + items.length) % items.length
  38. select(items[nextIdx])
  39. }
  40. const highlight = e => {
  41. const isDarkTheme = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
  42. e.style.backgroundColor = isDarkTheme ? '#1a1a1a' : 'WhiteSmoke'
  43. }
  44. const select = item => {
  45. // Deselect current item.
  46. const currentItem = findCurrentItem()
  47. currentItem?.setAttribute('style', "background-color: null;")
  48. currentItem?.removeAttribute(tag)
  49. // Select the item.
  50. item.setAttribute(tag, '')
  51. highlight(item)
  52. item.scrollIntoView({ behavior: "smooth", block: "center" })
  53. }
  54.  
  55. // Select the first item without scrolling.
  56. items[0].setAttribute(tag, '')
  57. highlight(items[0])
  58.  
  59. window.addEventListener('keydown', event => {
  60. if (event.target.tagName == "INPUT" || event.ctrlKey || event.altKey) return
  61. if (event.key == 'j') moveCursor(+1)
  62. if (event.key == 'k') moveCursor(-1)
  63. if (event.key == 'l') open(false)
  64. if (event.key == 'h') open(true)
  65. })
  66.  
  67. }