Skip to content

Instantly share code, notes, and snippets.

@viclafouch
Last active December 7, 2023 23:10
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save viclafouch/36d3edf58633a25c8b973588cc13480e to your computer and use it in GitHub Desktop.
Save viclafouch/36d3edf58633a25c8b973588cc13480e 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)
}
@kevin700brands
Copy link

How do I use this bro?

@kevin700brands
Copy link

Does it work in IOS as well?

@elusive
Copy link

elusive commented Jan 16, 2022

people are so funny.

thanks to the author for the great work!

@ShadabEdneed
Copy link

thank you brother, this is very helpful for me.

@ArtemZolotukh1n
Copy link

Error in askWritePermission: Type '"clipboard-write"' is not assignable to type 'PermissionName'.

Checked what permissions are available and found out that only: "geolocation" | "notifications" | "persistent-storage" | "push" | "screen-wake-lock" | "xr-spatial-tracking" - can be used.

@viclafouch
Copy link
Author

in TypeScript yes @ArtemZolotukh1n, because it has not been added to the dom lib.. But it's working. You can fix by doing :

 const { state } = await navigator.permissions.query({ name: 'clipboard-write' as PermissionName })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment