NoMouseGoogle

Shortcut for Google search results. j/k to move focus, l/h to open in new/background tab, n/p to go to next/previous page.

当前为 2022-07-21 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name NoMouseGoogle
  3. // @namespace com.gmail.fujifruity.greasemonkey
  4. // @version 1.11
  5. // @description Shortcut for Google search results. j/k to move focus, l/h to open in new/background tab, n/p to go to next/previous page.
  6. // @author fujifruity
  7. // @include https://www.google.com/search*
  8. // @include https://www.google.co.*/search*
  9. // @grant GM.openInTab
  10. // @license MIT
  11. // ==/UserScript==
  12.  
  13. {
  14. const items = [...document.querySelectorAll('#rso div[data-hveid][data-ved][lang], #rso video-voyager>div')]
  15. .filter(e => e.offsetParent != null /* is visible */)
  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 inScreen = (0 < r.top && r.top < window.innerHeight
  27. || 0 < r.bottom && r.bottom < window.innerHeight)
  28. if (!inScreen) {
  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 ? '#2a2a2a' : 'WhiteSmoke'
  43. }
  44. const select = item => {
  45. // Deselect current item.
  46. const currentItem = findCurrentItem()
  47. if (currentItem) {
  48. currentItem.style.backgroundColor = null
  49. currentItem.removeAttribute(tag)
  50. }
  51. // Select the item.
  52. item.setAttribute(tag, '')
  53. highlight(item)
  54. item.scrollIntoView({ behavior: "smooth", block: "center" })
  55. }
  56.  
  57. // Select the first item without scrolling.
  58. items[0].setAttribute(tag, '')
  59. highlight(items[0])
  60.  
  61. window.addEventListener('keydown', event => {
  62. if (event.target.tagName == "INPUT" || event.ctrlKey || event.altKey) return
  63. if (event.key == 'j') moveCursor(+1)
  64. if (event.key == 'k') moveCursor(-1)
  65. if (event.key == 'l') open(false)
  66. if (event.key == 'h') open(true)
  67. if (event.key == 'n') document.querySelector('#pnnext')?.click()
  68. if (event.key == 'p') document.querySelector('#pnprev')?.click()
  69. })
  70.  
  71. }