Created
January 2, 2021 11:28
-
-
Save nmaxcom/80cb59fc7566181a4b923e5983683693 to your computer and use it in GitHub Desktop.
UserScript to quickly search terms or open non href'd websites
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const log = (msg) => | |
console.log( | |
`%c*SearchScript*: ${msg}`, | |
"color:white;background-color:#20A6E8;padding:3px" | |
); | |
const URIregx = /^((?:https?:\/\/)?(?:[\w-]+\.)+(\w+)\/?([\w-.?=&+%\@\:]+\/?)*)$/i, | |
KEYCODE_FOR_NEWTAB = 79, // `o` key | |
KEYCODE_FOR_SAMETAB = 78; // `n` key | |
function main(event) { | |
if ( | |
document.activeElement.isContentEditable || | |
["TEXTAREA", "INPUT"].includes(document.activeElement.nodeName) | |
) { | |
log("Abort, selection detected within an editable input"); | |
return; | |
} | |
let seleccion = window.getSelection().toString().trim(), | |
selecType, | |
selecContent; | |
if (seleccion) { | |
let uriMatch = URIregx.exec(seleccion); | |
if (uriMatch) | |
[selecType, selecContent] = [ | |
"URI", | |
uriMatch[0].startsWith("http") ? uriMatch[0] : "http://" + uriMatch[1], | |
]; | |
else [selecType, selecContent] = ["TEXT", encodeURIComponent(seleccion)]; | |
} else return; | |
if (event.keyCode === KEYCODE_FOR_NEWTAB) | |
selecType === "TEXT" | |
? window.open("https://www.google.es/search?q=" + selecContent) | |
: window.open(selecContent); | |
if (event.keyCode === KEYCODE_FOR_SAMETAB) | |
selecType === "TEXT" | |
? (document.location = "https://www.google.es/search?q=" + selecContent) | |
: (document.location = selecContent); | |
} | |
document.addEventListener("keydown", (event) => { | |
if (event.keyCode === KEYCODE_FOR_NEWTAB || event.keyCode === KEYCODE_FOR_SAMETAB) | |
main(event); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment