Last active
December 7, 2023 23:10
-
-
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/
This file contains 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) | |
} | |
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
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.