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 提交的版本,查看 最新版本

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。

您需要先安装用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         HjklNavigation
// @namespace    com.gmail.fujifruity.greasemonkey
// @version      1.0
// @description  Shortcuts for Google Search result. j or k to move focus, l to open. (I have no idea to do with h.)
// @author       fujifruity
// @include      https://www.google.com/search*
// @grant        GM.openInTab
// @license      MIT
// ==/UserScript==

{
    const googleUrl = "www.google.com"
    // Add another URL variable and @include above.
    // This script may handle most list-like elements.

    const results = (() => {
        switch (location.hostname) {
            case googleUrl: return document.getElementsByClassName('rc')
            // add another one here
            default: return null
        }
    })()

    function open(result) {
        switch (location.hostname) {
            case googleUrl: {
                const url = result.firstChild.firstChild.href
                GM.openInTab(url, false)
                break
            }
            // add another one here
        }
    }

    let focuseIdx = null

    function refocus(nextIdx) {
        if (focuseIdx == null) {
            focuseIdx = 0
        } else {
            results[focuseIdx].style.backgroundColor = null
            focuseIdx = nextIdx
        }
        results[focuseIdx].style.backgroundColor = 'lightyellow'
        results[focuseIdx].scrollIntoView({ behavior: "smooth", block: "center" })
    }

    function onKeydown(event) {
        if (event.target.tagName == "INPUT" || event.ctrlKey || event.altKey) return
        const result = results[focuseIdx]
        switch (event.key) {
            case 'j': {
                refocus((focuseIdx + 1) % results.length)
                break
            }
            case 'k': {
                refocus((focuseIdx - 1 + results.length) % results.length)
                break
            }
            case 'l': {
                open(result)
                break
            }
            case 'g': {
                refocus(0)
                break
            }
            case 'G': {
                refocus(results.length - 1)
                break
            }
        }
    }

    window.addEventListener('keydown', onKeydown)

}