HjklNavigation

Shortcuts for Google Search result. j or k to move focus, l to open. (I have no idea to do with h.)

当前为 2020-12-21 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HjklNavigation
  3. // @namespace com.gmail.fujifruity.greasemonkey
  4. // @version 1.1
  5. // @description Shortcuts for Google Search result. j or k to move focus, l to open. (I have no idea to do with h.)
  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 handle most list-like elements.
  16.  
  17. let focusIdx = null
  18.  
  19. const results = (() => {
  20. switch (location.hostname) {
  21. case googleUrl: return document.getElementsByClassName('rc')
  22. // add another one here
  23. default: return null
  24. }
  25. })()
  26.  
  27. function open(result) {
  28. switch (location.hostname) {
  29. case googleUrl: {
  30. const url = result.firstChild.firstChild.href
  31. GM.openInTab(url, false)
  32. break
  33. }
  34. // add another one here
  35. }
  36. }
  37.  
  38. function 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. function onKeydown(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)
  63. break
  64. }
  65. case 'g': {
  66. refocus(0)
  67. break
  68. }
  69. case 'G': {
  70. refocus(results.length - 1)
  71. break
  72. }
  73. }
  74. }
  75.  
  76. window.addEventListener('keydown', onKeydown)
  77.  
  78. }