NoMouseGoogle

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

当前为 2022-01-19 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name NoMouseGoogle
  3. // @namespace com.gmail.fujifruity.greasemonkey
  4. // @version 1.7
  5. // @description Shortcut 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 div[data-hveid][data-ved]')]
  14. const open = inBackground => {
  15. const url = findCurrentItem().querySelector('a').href
  16. GM.openInTab(url, inBackground)
  17. }
  18. const tag = "noMouseGoogleCurrentItem"
  19. const findCurrentItem = () => items.find(e => e.hasAttribute(tag))
  20.  
  21. const moveCursor = step => {
  22. const currentItem = findCurrentItem()
  23. const r = currentItem.getBoundingClientRect();
  24. const isCurrentItemVisible = 0 < r.top && r.top < window.innerHeight
  25. || 0 < r.bottom && r.bottom < window.innerHeight
  26. if (!isCurrentItemVisible) {
  27. const dist = e => {
  28. const r = e.getBoundingClientRect()
  29. return Math.abs(window.innerHeight - (r.top + r.bottom))
  30. }
  31. const nearestItem = items.reduce((acc,e) => dist(acc) < dist(e) ? acc : e )
  32. select(nearestItem)
  33. return
  34. }
  35. const nextIdx = (items.indexOf(currentItem) + step + items.length) % items.length
  36. select(items[nextIdx])
  37. }
  38. const highlight = e => {
  39. const isDarkTheme = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
  40. e.style.backgroundColor = isDarkTheme ? '#2a2a2a' : 'WhiteSmoke'
  41. }
  42. const select = item => {
  43. // Deselect current item.
  44. const currentItem = findCurrentItem()
  45. currentItem?.setAttribute('style', "background-color: null;")
  46. currentItem?.removeAttribute(tag)
  47. // Select the item.
  48. item.setAttribute(tag, '')
  49. highlight(item)
  50. item.scrollIntoView({ behavior: "smooth", block: "center" })
  51. }
  52.  
  53. // Select the first item without scrolling.
  54. items[0].setAttribute(tag, '')
  55. highlight(items[0])
  56.  
  57. window.addEventListener('keydown', event => {
  58. if (event.target.tagName == "INPUT" || event.ctrlKey || event.altKey) return
  59. if (event.key == 'j') moveCursor(+1)
  60. if (event.key == 'k') moveCursor(-1)
  61. if (event.key == 'l') open(false)
  62. if (event.key == 'h') open(true)
  63. })
  64.  
  65. }