HjklNavigation

Introduces (h)jkl navigation into Google Search result. (As an example. You can easily customize this script for other websites.)

当前为 2020-10-25 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HjklNavigation
  3. // @namespace com.gmail.fujifruity.greasemonkey
  4. // @version 0.1
  5. // @description Introduces (h)jkl navigation into Google Search result. (As an example. You can easily customize this script for other websites.)
  6. // @author fujifruity
  7. // @include https://www.google.com/search*
  8. // @grant GM.openInTab
  9. // ==/UserScript==
  10.  
  11. (() => {
  12. function log(...msg) { return console.log("HjklNavigation:", ...msg) }
  13. function cssOf(elem) { return document.defaultView.getComputedStyle(elem, '') }
  14.  
  15. let focusedIdx = null
  16.  
  17. const googleUrl = "www.google.com"
  18. // add another one here
  19.  
  20. const results = (() => {
  21. switch (location.hostname) {
  22. case googleUrl: return document.getElementsByClassName('rc')
  23. // add another one here
  24. default: return null
  25. }
  26. })()
  27.  
  28. function open(result) {
  29. switch (location.hostname) {
  30. case googleUrl: {
  31. const url = result.firstChild.firstChild.href
  32. GM.openInTab(url, false)
  33. break
  34. }
  35. // add another one here
  36. }
  37. }
  38.  
  39. function refocus(nextIdx) {
  40. if (focusedIdx == null) {
  41. focusedIdx = 0
  42. } else {
  43. results[focusedIdx].style.backgroundColor = null
  44. focusedIdx = nextIdx
  45. }
  46. results[focusedIdx].style.backgroundColor = 'lightyellow'
  47. results[focusedIdx].scrollIntoView({ behavior: "smooth", block: "center" })
  48. }
  49.  
  50. function handler(event) {
  51. if (event.target.tagName == "INPUT" || event.ctrlKey || event.altKey) return
  52. const result = results[focusedIdx]
  53. switch (event.key) {
  54. case 'j': {
  55. log('j: down')
  56. refocus((focusedIdx + 1) % results.length)
  57. break
  58. }
  59. case 'k': {
  60. log('k: up')
  61. refocus((focusedIdx - 1 + results.length) % results.length)
  62. break
  63. }
  64. case 'g': {
  65. log('g: home')
  66. refocus(0)
  67. break
  68. }
  69. case 'G': {
  70. log('G: end')
  71. refocus(results.length-1)
  72. break
  73. }
  74. case 'l': {
  75. log('l: open')
  76. open(result)
  77. break
  78. }
  79. }
  80. }
  81.  
  82. window.addEventListener('keydown', handler)
  83. })()