-
-
Save ghostcode/5b5e61127326a3b6f5106bb871961e78 to your computer and use it in GitHub Desktop.
How to copy an image or a text to clipboard in Javascript (new way !) See https://copy-to-clipboard.now.sh/
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
// @return Promise<boolean> | |
async function askWritePermission() { | |
try { | |
// The clipboard-write permission is granted automatically to pages | |
// when they are the active tab. So it's not required, but it's more safe. | |
const { state } = await navigator.permissions.query({ name: 'clipboard-write' }) | |
return state === 'granted' | |
} catch (error) { | |
// Browser compatibility / Security error (ONLY HTTPS) ... | |
return false | |
} | |
} | |
// @params blob - The ClipboardItem takes an object with the MIME type as key, and the actual blob as the value. | |
// @return Promise<void> | |
const setToClipboard = async blob => { | |
const data = [new ClipboardItem({ [blob.type]: blob })] | |
await navigator.clipboard.write(data) | |
} | |
// Can we copy a text or an image ? | |
const canWriteToClipboard = await askWritePermission() | |
// Copy a PNG image to clipboard | |
if (canWriteToClipboard) { | |
const response = await fetch('/image/my-beautiful-image.png') | |
const blob = await response.blob() | |
await setToClipboard(blob) | |
} | |
// Copy a text to clipboard | |
if (canWriteToClipboard) { | |
const blob = new Blob(['Hello World'], { type: 'text/plain' }) | |
await setToClipboard(blob) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment