Skip to content

Instantly share code, notes, and snippets.

@fliptopbox
Created September 18, 2019 21:26
Show Gist options
  • Save fliptopbox/4c8260ae949899cf208df0c94971451e to your computer and use it in GitHub Desktop.
Save fliptopbox/4c8260ae949899cf208df0c94971451e to your computer and use it in GitHub Desktop.
Bookmarklet to present various links to research recources.
(function(){
const body = document.querySelector("body");
const sources = {
"google": "https://www.google.com/search?q=@",
"amazon": "https://www.amazon.co.uk/s?k=@",
"gutenberg": "https://www.gutenberg.org/ebooks/authors/search/?query=@",
"etymology": "https://www.etymonline.com/search?q=@",
"dictionary": "https://www.dictionary.com/browse/@",
"wikipedia": "https://en.wikipedia.org/wiki/@"
};
const results = document.querySelector("results") || document.createElement("results");
function phrase() {
const selection = document.getSelection();
const { focusNode = null } = selection;
let text = focusNode ? focusNode.data : null;
let {extentOffset, baseOffset, anchorOffset, focusOffset} = selection || null;
const start = anchorOffset || 0;
const end = focusOffset || 0;
text = text && text.trim() ? text.slice(start, end) : null;
text = text || window.prompt("Search phrase");
console.log(">> [%s]",
text,
start, end,
extentOffset, baseOffset,
anchorOffset, focusOffset,
selection);
return text;
}
function redirect(string, href = url) {
return text ? window.location.href = `${url}${string}` : null;
}
const query = phrase();
const hrefs = Object.keys(sources).map(k => {
const url = sources[k].replace("@", query);
const style = `padding: 0 0.3em;`;
const html = `<a href="${url}" target="${k}" style="${style}">${k}</a>`;
return html;
});
if(!document.querySelector("results")) {
body.append(results);
results.onclick = (e) => {
if(!e.altKey) {
results.parentNode.removeChild(results);
}
return true;
}
}
results.innerHTML = `<a href="#">X</a> "${query}" : ${hrefs.join(" ")}`;
results.style = `
position: fixed;
z-index:654321;
top: 0;
left: 0;
right: 0;
background: black;
color: white;
padding: 1em;
font-size: 14px;
`;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment