SimpleShortcuts

Simple keyboard shortcuts for arbitrary sites.

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

// ==UserScript==
// @name         SimpleShortcuts
// @namespace    com.gmail.fujifruity.greasemonkey
// @version      0.3
// @description  Simple keyboard shortcuts for arbitrary sites.
// @author       fujifruity
// @include      http://*/*
// @include      https://*/*
// @grant        none
// @license      MIT
// ==/UserScript==

{
    'use strict';

    const log = (...msg) => console.log("SimpleShortcuts:", ...msg)

    class Website {
        constructor(urlHead, shortcuts) {
            this.urlHead = urlHead;
            this.shortcuts = shortcuts;
        }
    }

    class Shortcut {
        constructor(key, action) {
            this.key = key;
            this.action = action;
        }
    }

    const websites = [
        new Website(
            "https://www.amazon.com",
            [new Shortcut('/', () => document.getElementById('twotabsearchtextbox').focus())]
        ), new Website(
            "https://www.google.com",
            [
                new Shortcut('/', () => { document.getElementsByClassName('gLFyf gsfi')[0].focus() }),
                new Shortcut('n', () => { document.getElementById('pnnext').click() })
            ]
        )
    ]

    window.addEventListener('keydown', event => {
        const isInput = ["INPUT", "TEXTAREA"].includes(event.target.tagName)
        if (isInput) return
        const website = websites.find(w => location.href.startsWith(w.urlHead))
        const shortcut = website?.shortcuts?.find(s => s.key == event.key)
        if (shortcut) {
            shortcut.action()
            event.preventDefault()
            log(event)
        }
    })

    log("shortcuts set")
}