Skip to content

Instantly share code, notes, and snippets.

@ghostcode
Forked from viclafouch/clipboard.js
Created October 17, 2023 04:04
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 ghostcode/5b5e61127326a3b6f5106bb871961e78 to your computer and use it in GitHub Desktop.
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/
// @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