SelectAndGo

Search with selected text by pressing s(Google), t(Translate) or d(Oxford) within 2 seconds.

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

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         SelectAndGo
// @namespace    com.gmail.fujifruity.greasemonkey
// @version      1.0
// @description  Search with selected text by pressing s(Google), t(Translate) or d(Oxford) within 2 seconds.
// @author       fujifruity
// @match        *://*/*
// @grant        GM.openInTab
// ==/UserScript==

(() => {
    const timeoutMs = 2000
    const log = (...msg) => console.log('SelectAndGo:', ...msg)

    function handleKeydown(event) {
        if (event.target.tagName == "INPUT" || event.ctrlKey == true || event.altKey == true) return
        const selection = window.getSelection().toString()
        switch (event.key) {
            case 's':
                GM.openInTab("https://www.google.com/search?q=" + selection, false)
                break
            case 't':
                GM.openInTab("https://translate.google.com/#en/ja/" + selection, false)
                break
            case 'i':
                GM.openInTab("https://www.google.com/search?tbm=isch&q=" + selection, false)
                break
            case 'o': {
                let url = "https://www.oxfordlearnersdictionaries.com/search/english/?q="
                // the website requires hyphen-separated words
                let query = selection.replace(/\s+/g, '-')
                GM.openInTab(url + query, false)
                break
            }
            case 'c':
                alert(window.getSelection().toString().length + ' characters')
                break
        }
    }

    function setShortcut() { window.addEventListener('keydown', handleKeydown) }
    function unsetShortcut() { window.removeEventListener('keydown', handleKeydown) }

    // set shortcuts on selectStart; unset the shortcuts in seconds.
    window.addEventListener('selectstart', (() => {
        setShortcut()
        // unset shortcuts in seconds.
        window.onmouseup = () => {
            setTimeout(unsetShortcut, timeoutMs)
            window.onmouseup = null
        }
        // unset shortcuts when selection is triggerd by ctrl+a
        window.onkeyup = () => {
            setTimeout(unsetShortcut, timeoutMs)
            window.onkeyup = null
        }
    }))

    log('selectstart listener is set')

})()