Skip to content

Instantly share code, notes, and snippets.

@charisTheo
Created October 12, 2021 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charisTheo/2b890c4b0396081d83ae49a1ddfca951 to your computer and use it in GitHub Desktop.
Save charisTheo/2b890c4b0396081d83ae49a1ddfca951 to your computer and use it in GitHub Desktop.
async function copyImageToClipboard(img) {
const src = img.src
const imageMimeType = getImageMimeTypeFromUrl(src)
const blob = imageMimeType === 'image/svg'
? await getTextBlobFromUrl(src)
: await getImageBlobFromUrl(src)
await navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob
})
])
}
async function getTextBlobFromUrl(url) {
const response = await fetch(url);
const source = await response.text();
return new Blob([source], { type: 'text/plain' });
};
copyImageToClipboard(document.querySelector('.image-to-copy'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment