
Posted on • Edited on • Originally published atpantelis.theodosiou.me
Copy to Clipboard with JavaScript
When creating advanced web pages and applications, you may want to include the copy feature. This allows your users to copy text by simply clicking a button or icon rather than highlighting the text and pressing a couple of keys on the keyboard.
This capability is typically used when someone has to copy an activation code, recovery key, code snippet, or other similar information. You can also include features such as an alert or text on the screen (which could be a modal) to notify the user that the text has been copied to their clipboard.
Prior to its deprecation, you would have handled this with thedocument.execCommand()
command. Despite being frequently used, it struggles with huge text. Since it's synchronous, the user experience is negatively impacted. Additionally, there are problems with permissions that differ between browsers.
These issues are resolved with theAsync Clipboard API.
In this blog post, we'll examine a technique for using the Clipboard API to copy text and images to the clipboard.
The Asynchronous Clipboard API
Now that the Clipboard API is available, you can read from and write to the system clipboard asynchronously as well as respond to clipboard actions (cut, copy, and paste).
Clipboard API permissions
The clipboard can be accessed, which creates various security issues. To reduce security threats, the Clipboard API has been made safe.
- Only pages provided through HTTPS are supported by the Clipboard API.
- Only when the page is the active browser tab is access to the clipboard permitted.
- It is never okay to read from the clipboard without permission.
The two permissions connected to the Clipboard API are listed below:
clipboard-write
permission: Limits who can use the write method.clipboard-read
permission: Limits who can use the read technique of the clipboard.
According to how we use the Clipboard API, developers must always ask the browser's permission before doing any operation. Usingnavigator.permissions
we must look for theclipboard-write
permission to see if we have write access.
navigator.permissions.query({name:"write-on-clipboard"}).then((result)=>{if(result.state=="granted"||result.state=="prompt"){console.log("Write access granted!");}});
Using the subsequent code, we can also confirm thatclipboard-read
access exists:
navigator.permissions.query({name:"read-text-on-clipboard"}).then((result)=>{if(result.state=="granted"||result.state=="prompt"){console.log("Read access granted!");}});
Text to Clipboard
Let's discuss how to copy text to the clipboard right now. With the new Clipboard API, we must utilize thewriteText()
function, which only accepts one parameter: copying text to the clipboard.
exportconstApp=()=>{constcopyText=async()=>{try{awaitnavigator.clipboard.writeText("Some text to copy");console.log("Clipboard content has been copied.");}catch(error){console.error("Failed to copy content to clipboard.");console.log(err.name,err.message);}};return(<divclassName="wrapper"><buttonclassName="btn"onClick={copyText}>copytext</button></div>);};
Result
Image to Clipboard
To copy photos, we must use the Clipboard API'swrite()
method, which accepts just one parameter, an array holding the data to be copied to the clipboard, like the previous function.
For instance, by using the following code, we can retrieve a photo from any remote URL and copy it to the clipboard.
exportconstApp=()=>{constcopyImage=async()=>{try{constresponse=awaitfetch("/logo-with-shadow.png");constblob=awaitresponse.blob();awaitnavigator.clipboard.write([newClipboardItem({[blob.type]:blob,}),]);console.log("Image copied to clipboard.");}catch(error){console.error("Failed to copy image to clipboard.");console.log(error.name,error.message);}};return(<divclassName="wrapper"><buttonclassName="btn"onClick={copyImage}>copyimage</button></div>);};
Result
Up until this point, onlytext/plain
text/html
andimage/png
were supported by the Async Clipboard API for copying to and pasting from the system clipboard. The browser often does this sanitization in order to, for instance, eliminate embeddedscript
components or#"https://en.wikipedia.org/wiki/Zip_bomb">decompression bomb assaults.
Summary
This concise tutorial has explained how to use the new Clipboard API to copy text and other data, such as photos, to the clipboard. When writing to or reading from a user's local computer, use caution to keep the process secure and transparent.
If you found this post helpful or enjoyed it, consider supporting me bybuying me a coffee. Your support helps me create more valuable content. ☕ Thank you!
Top comments(2)

- Educationuniversity
- WorkCEO
- Joined
Сongratulations 🥳! Your article hit the top posts for the week -dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍

- LocationThessaloniki, Greece
- EducationB.Sc in Computer Science
- WorkSoftware Developer at Athens Technology Center
- Joined
Thanks@fruntend!
For further actions, you may consider blocking this person and/orreporting abuse