There are several ways to use your clipboard. One of them is Clipboard API. This API is designed to supersede accessing the clipboard using document.execCommand()
but if you have a web page that is served over HTTP
, it probably won't copy anything to your clipboard. Because of security concerns, it works over HTTPS
. In this blog post we will discuss how to achieve copying items without using Clipboard API.
Let's start
In this example we will use DOM
operations and execCommand()
method to create 'Copy to Clipboard' function. It shouldn't be forgotten that execCommand()
method is deprecated and no longer recommended but some browsers still support it. Here the list of these browsers;
Our Code:
const handleCopy = (content) => {
const textarea = document.createElement("textarea");
textarea.textContent = content;
document.body.appendChild(textarea);
textarea.select();
document.execCommand("copy");
document.body.removeChild(textarea);
};
Firstly we define handleCopy
function. It has parameter named content
. The content
parameter is the value we want to copy.
1- We create a new text area.
document.createElement("textarea")
2- And set it's textContent
as the value we want to copy.
textarea.textContent = content;
3- Then we add our text area to body of DOM
.
document.body.appendChild(textarea);
4- Select all the text in textarea.
textarea.select();
5- We use execCommand("copy")
for copying the content that we selected.
document.execCommand("copy");
6- Finally, we remove the textarea
from DOM
.
document.body.removeChild(textarea);
You did it! Now the content is on your clipboard 🎉🎉
Conclusion
In this post, I showed you how to copy texts to your clipboard. I hope it helps to you.
See you soon 😋
Top comments (0)