HjklNavigation

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

当前为 2021-03-16 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HjklNavigation
  3. // @namespace com.gmail.fujifruity.greasemonkey
  4. // @version 1.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 googleUrl = "www.google.com"
  14. // Add another URL variable and @include above.
  15. // This script may fits most list-like elements.
  16.  
  17. let focusIdx = null
  18.  
  19. const results = (() => {
  20. switch (location.hostname) {
  21. case googleUrl: return document.querySelectorAll('.hlcw0c > .g')
  22. // add another case here
  23. default: return null
  24. }
  25. })()
  26.  
  27. const open = (result, isBackground) => {
  28. switch (location.hostname) {
  29. case googleUrl: {
  30. const url = result.getElementsByTagName('a')[0].href
  31. GM.openInTab(url, isBackground)
  32. break
  33. }
  34. // add another case here
  35. }
  36. }
  37.  
  38. const refocus = nextIdx => {
  39. if (focusIdx == null) {
  40. focusIdx = 0
  41. } else {
  42. results[focusIdx].style.backgroundColor = null
  43. focusIdx = nextIdx
  44. }
  45. results[focusIdx].style.backgroundColor = 'lightyellow'
  46. results[focusIdx].scrollIntoView({ behavior: "smooth", block: "center" })
  47. }
  48.  
  49. window.addEventListener('keydown', event => {
  50. if (event.target.tagName == "INPUT" || event.ctrlKey || event.altKey) return
  51. const result = results[focusIdx]
  52. switch (event.key) {
  53. case 'j': {
  54. refocus((focusIdx + 1) % results.length)
  55. break
  56. }
  57. case 'k': {
  58. refocus((focusIdx - 1 + results.length) % results.length)
  59. break
  60. }
  61. case 'l': {
  62. open(result, false)
  63. break
  64. }
  65. case 'h': {
  66. open(result, true)
  67. break
  68. }
  69. case 'g': {
  70. refocus(0)
  71. break
  72. }
  73. case 'G': {
  74. refocus(results.length - 1)
  75. break
  76. }
  77. }
  78. })
  79.  
  80. }