Last active
January 16, 2021 15:04
-
-
Save ThatRyanPerson/c3d50439e41f5e19b2b4a51c5f8f88a9 to your computer and use it in GitHub Desktop.
Bookmarklet to automagically create and copy a watch to the clipboard based on the selected text
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
javascript:(async function () { | |
/* Based on this bookmarklet by Makyen: https://chat.stackexchange.com/transcript/11540?m=55327802 | |
* which is based on this code by Tim Down to get selected text: https://stackoverflow.com/a/5379408/208273 | |
*/ | |
var text = ""; | |
const activeEl = document.activeElement; | |
const activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null; | |
if ((activeElTagName == "textarea" || activeElTagName == "input") && /^(?:text|textarea|search|password|tel|url)$/i.test(activeEl.type) && (typeof activeEl.selectionStart == "number")) { | |
text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd); | |
} else if (window.getSelection) { | |
text = window.getSelection().toString(); | |
} | |
text = text.toLowerCase().trim(); | |
const textRegex = text.replaceAll(".", "\\.").replaceAll(" ", "[\\W_]*+"); | |
try { | |
await navigator.clipboard.writeText(`!!/watch ${textRegex}`); | |
} catch (err) { | |
alert('Failed to copy watch text. ', err); | |
return; | |
} | |
const plainSearch = encodeURIComponent(`"${text}"`); | |
const urlSearch = encodeURIComponent(`url:"${text}"`); | |
const codeSearch = encodeURIComponent(`code:"${text}"`); | |
/* Simpler (and faster) bookending than Makyen's because we will never include ^ or $ in the regex */ | |
const searchTerm = encodeURIComponent(`\\b(?s:${textRegex})\\b`); | |
const searchTitle = `&title_is_regex=1&title=${searchTerm}`; | |
const searchBody = `&body_is_regex=1&body=${searchTerm}`; | |
const searchUsername = `&username_is_regex=1&username=${searchTerm}`; | |
/* Tabs open in reverse order of window calls. Calls are ordered (approximately) from slowest to fastest for ease of tabbing through */ | |
window.open(`https://metasmoke.erwaysoftware.com/search?utf8=%E2%9C%93${searchTitle}${searchBody}${searchUsername}&or_search=1`); | |
window.open(`https://stackexchange.com/search?q=${urlSearch}`); | |
window.open(`https://stackexchange.com/search?q=${codeSearch}`); | |
window.open(`https://stackexchange.com/search?q=${plainSearch}`); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment