SelectAndGo

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

目前為 2021-03-05 提交的版本,檢視 最新版本

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    const onKeydown = (event) => {
        if (event.target.tagName == "INPUT" || event.ctrlKey || event.altKey) 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': {
                const url = "https://www.oxfordlearnersdictionaries.com/search/english/?q="
                // the website requires hyphen-separated words
                const query = selection.replace(/\s+/g, '-')
                GM.openInTab(url + query, false)
                break
            }
            case 'c':
                // count chars
                alert(window.getSelection().toString().length + ' characters')
                break
        }
    }

    const unsetShortcut = () => window.removeEventListener('keydown', onKeydown)

    log('listen selectstart')
    window.addEventListener('selectstart', () => {
        window.addEventListener('keydown', onKeydown)
        // 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
        }
    })

}