Last active
December 21, 2024 20:46
-
-
Save magasine/0e262e8b8d066da596c46e8f06388c12 to your computer and use it in GitHub Desktop.
! Whatsapp, Copy reference to
This file contains hidden or 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: (function () { | |
const getSelectedTextWithBreaks = () => { | |
const selection = window.getSelection(); | |
if (!selection.rangeCount) return ""; | |
const range = selection.getRangeAt(0); | |
const container = document.createElement("div"); | |
container.appendChild(range.cloneContents()); | |
container.querySelectorAll("br").forEach((br) => br.replaceWith("\n\n")); | |
container.querySelectorAll("p").forEach((p) => { | |
p.after("\n\n"); | |
p.replaceWith(...p.childNodes); | |
}); | |
return container.textContent.replace(/\n{2,}/g, "\n\n").trim(); | |
}; | |
const copyUsingClipboardAPI = async (text) => { | |
try { | |
await navigator.clipboard.writeText(text); | |
alert(`Texto copiado para o clipboard!\n---\n${text}`); | |
} catch { | |
fallbackCopy(text); | |
} | |
}; | |
const fallbackCopy = (text) => { | |
const textarea = document.createElement("textarea"); | |
textarea.value = text; | |
textarea.style.position = "fixed"; | |
textarea.style.opacity = "0"; | |
document.body.appendChild(textarea); | |
textarea.focus(); | |
textarea.select(); | |
try { | |
document.execCommand("copy"); | |
alert( | |
`Texto copiado para o clipboard usando método alternativo!\n---\n${text}` | |
); | |
} catch (err) { | |
prompt("Pressione Ctrl+C para copiar o texto:", text); | |
} | |
document.body.removeChild(textarea); | |
}; | |
const selectedText = getSelectedTextWithBreaks(); | |
const title = document.title; | |
const url = location.href; | |
const promptText = `*${title}*\n${ | |
selectedText ? `\n${selectedText}\n` : "" | |
}\n${url}`; | |
if (navigator.clipboard?.writeText) { | |
copyUsingClipboardAPI(promptText); | |
} else { | |
fallbackCopy(promptText); | |
} | |
})(); | |
// Bookmarklet | |
// Allows you to select text on a web page and collect title, selection and URL to compose a single reference text, to be posted on WhatsApp. | |
// Installation link: https://dschep.github.io/GistMarklets/#0e262e8b8d066da596c46e8f06388c12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment