HjklNavigation

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

目前為 2021-01-15 提交的版本,檢視 最新版本

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

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

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         HjklNavigation
// @namespace    com.gmail.fujifruity.greasemonkey
// @version      1.2
// @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.

    let focusIdx = null

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

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

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

    function onKeydown(event) {
        if (event.target.tagName == "INPUT" || event.ctrlKey || event.altKey) return
        const result = results[focusIdx]
        switch (event.key) {
            case 'j': {
                refocus((focusIdx + 1) % results.length)
                break
            }
            case 'k': {
                refocus((focusIdx - 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)

}