HjklNavigation

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

当前为 2021-10-31 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HjklNavigation
  3. // @namespace com.gmail.fujifruity.greasemonkey
  4. // @version 1.5.3
  5. // @description Shortcuts for Google Search result. 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 = inForeground => {
  17. const url = findCurrentItem().querySelector('a').href
  18. GM.openInTab(url, inForeground)
  19. }
  20. const tag = "hjklNavigationCurrentItem"
  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 isVisible = 0 < r.top && r.top < window.innerHeight || 0 < r.bottom && r.bottom < window.innerHeight
  27. if (!isVisible) {
  28. const dist = e => {
  29. const r = e.getBoundingClientRect()
  30. return Math.abs(window.innerHeight - (r.top + r.bottom))
  31. }
  32. const nearest = items.reduce((acc,e) => dist(acc) < dist(e) ? acc : e )
  33. select(nearest)
  34. return
  35. }
  36. const nextIdx = (items.indexOf(currentItem) + step + items.length) % items.length
  37. select(items[nextIdx])
  38. }
  39. const highlight = e => {
  40. e.style.backgroundColor = 'WhiteSmoke'
  41. e.setAttribute(tag, '')
  42. }
  43. const select = item => {
  44. // deselect current item
  45. const currentItem = findCurrentItem()
  46. currentItem?.setAttribute('style', "background-color: null;")
  47. currentItem?.removeAttribute(tag)
  48. highlight(item)
  49. item.scrollIntoView({ behavior: "smooth", block: "center" })
  50. }
  51. highlight(items[0])
  52.  
  53. window.addEventListener('keydown', event => {
  54. if (event.target.tagName == "INPUT" || event.ctrlKey || event.altKey) return
  55. switch (event.key) {
  56. case 'j': {
  57. moveCursor(+1)
  58. break
  59. }
  60. case 'k': {
  61. moveCursor(-1)
  62. break
  63. }
  64. case 'l': {
  65. open(true)
  66. break
  67. }
  68. case 'h': {
  69. open(false)
  70. break
  71. }
  72. }
  73. })
  74.  
  75. }