Hey guys 😃
A very popular feature on websites is the ability to copy an element to your clipboard. It's easy to find libraries to copy text, BUT what about images?
Note: The asynchronous Clipboard API methods are a recent addition to the specification, and may not be fully implemented to the specification in all browsers. Be sure to review the compatibility tables for each method before using them, to ensure that support is broad enough for your needs.
Because of the potential for abuse, two permissions are defined that allow user agents to give use control over how the Async APIs are used.
To avoid the risk of abuse and as a security measure, 2 permissions are required to use the Clipboard API correctly.
clipboard-writepermission controls access to the
clipboard-readpermission controls access to the
In this article, we will only focus on the
copy feature to be able to copy a text or an image to the clipboard.
As with many new APIs,
navigator.clipboard is only supported for pages served over HTTPS. To help prevent abuse, clipboard access is only allowed when a page is the active tab.
NOTE: Pages in active tabs can
write to the clipboard without requesting permission.
If you want to access to the data from the clipboard, see here.
Below is a function that shows whether the user can copy text or an image:
To copy an item to the clipboard such as image or text, nothing could be simpler. The Clipboard API provides the
writeText() (only works for text) methods .
Warning: Not all browsers support the methods suggested below. So be careful if you want to use them in production. See here for current compatibility)
To copy text to the clipboard, call
navigator.clipboard.writeText(). A Promise is resolved once the clipboard's contents have been updated. The promise is rejected if the caller does not have permission to write to the clipboard.
To copy an image to the clipboard, call
navigator.clipboard.write() (that is the same as the
writeText method but it's more generic and also works for copying text).
Pass an array of
ClipboardItem objects as a parameter to the
CAUTION: At the time of writing, only PNG files are supported and you can only pass one image to the clipboard.
That's it, if you want to support certain browsers, you will have to be patient before using this new API (almost finished !)