Skip to content

Instantly share code, notes, and snippets.

@valacar
Created March 13, 2018 01:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valacar/284f841fc5481316dd5262192db516a8 to your computer and use it in GitHub Desktop.
Save valacar/284f841fc5481316dd5262192db516a8 to your computer and use it in GitHub Desktop.
[userscript] Search for selected text
// ==UserScript==
// @name Search for selected text
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author Valacar
// @include https://*
// @include http://*
// @grant GM_openInTab
// ==/UserScript==
// Instructions:
// highlight text on any page, and press y to search on youtube or w to search on wikipedia
(function() {
'use strict';
function searchWikipediaForSelectedText() {
let selectedText = getSelection()
.toString()
.trim()
.replace(/ /g, '_');
if (selectedText) {
GM_openInTab("https://en.wikipedia.org/wiki/" + selectedText);
}
}
function searchYouTubeForSelectedText() {
let selectedText = getSelection()
.toString()
.trim()
.replace(/ /g, '+');
if (selectedText) {
GM_openInTab("https://www.youtube.com/results?search_query=" + selectedText);
}
}
window.addEventListener("keydown",
function(event) {
if (event.defaultPrevented ||
/(input|textarea)/i.test(document.activeElement.nodeName)) {
return;
}
switch (event.key) {
case "y":
/* fall through */
case "Y":
searchYouTubeForSelectedText();
break;
case "w":
/* fall through */
case "W":
searchWikipediaForSelectedText();
break;
default:
return;
}
event.preventDefault();
},
true
);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment