How to Copy Text to Clipboard with JavaScript
When designing innovative websites and apps, 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.
When someone has to copy an activation code, recovery key, a piece of code, etc., this capability is typically employed. You may also include features such as an alert or text on the screen (which could be a modal) to notify the user that the content has been copied to their clipboard.
Previously, you would have handled this with the document.execCommand() command, but it has since been deprecated. You may now utilize the Clipboard API to respond to clipboard instructions (cut, copy, and paste) as well as read from and write to the system clipboard asynchronously. In this tutorial, you will learn how to use the Clipboard API to write (copy) text and pictures to the clipboard. If you urgently require the program code, here it is:
<p id="myText">Hello World</p>
<button class="btn" onclick="copyContent()">Copy!</button>
<script>
let text = document.getElementById('myText').innerHTML;
const copyContent = async () => {
try {
await navigator.clipboard.writeText(text);
console.log('Content copied to clipboard');
} catch (err) {
console.error('Failed to copy: ', err);
}
}
</script>
If you don't mind waiting, let's learn more about the Clipboard API and see how it works with an example project. Checking The Browser Permission It is essential to recognize that the Clipboard API is only available for pages serving over HTTPS. Before attempting to write to the clipboard, you should additionally check for browser permissions to ensure that you have to write access. This is possible with the navigator.permissions
query:
navigator.permissions.query({ name: "write-on-clipboard" }).then((result) => {
if (result.state == "granted" || result.state == "prompt") {
alert("Write access granted!");
}
});
Reading The Clipboard Contents
You can read the contents of a clipboard in the same way that you can write. This raises privacy concerns, and you should be upfront and cautious while employing the function. You could want to link your writing and reading so that everything you read is solely what you previously wrote.
For example, when a user opens a verification code on one page, it is automatically copied to the clipboard. If you know they'll go to another page with that entry in the clipboard, you can read it and paste it into another field to save them even more time and effort!
To read the most recent clipboard input, we utilize the readText() function. This method also returns a promise that is fulfilled if the browser can access the clipboard content and rejected if it cannot:
navigator.clipboard
.readText()
.then((copiedText) => {
// Do something with copied text
});
In contrast to writing to the clipboard, asking to read the browser clipboard content results in a one-time popup asking the user to allow How to Copy Text to the Clipboard The asynchronous writeText() function will be used to copy text with the new Clipboard API. This function takes only one parameter: the text to be copied to the clipboard. This can be a string, a template literal including variables and other strings, or a variable storing a string. This function delivers a promise since it is asynchronous. If the clipboard has been successfully changed, this promise is fulfilled; otherwise, it is rejected:
navigator.clipboard.writeText("This is the text to be copied").then(() => {
console.log('Content copied to clipboard');
/* Resolved - text copied to clipboard successfully */
},() => {
console.error('Failed to copy');
/* Rejected - text failed to copy to the clipboard */
});
You can also try using the async/await alongside with the try/catch function:
async function copyContent() {
try {
await navigator.clipboard.writeText('This is the text to be copied');
console.log('Content copied to clipboard');
/* Resolved - text copied to the clipboard successfully */
} catch (err) {
console.error('Failed to copy: ', err);
/* Rejected - text failed to copy to the clipboard */
}
}
Here's a real-world example to demonstrate how it works. We're getting quotations via a public quote API in this example. The quotation and its author are then copied when you click the copy icon, demonstrating that you may change what you copy into the writeText()
method.
Conclusion
After reading this article, you should have a better understanding of how to copy text to the clipboard with JavaScript using the Clipboard API without needing to think outside the box or install any JavaScript libraries. Always take caution to be transparent and safe while writing to or reading from a user's local computer!