DEV Community

Cover image for Copying Items to Clipboard Without Using Clipboard API
Ertan Özdemir
Ertan Özdemir

Posted on

Copying Items to Clipboard Without Using Clipboard API

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;
Supported Browser List


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);
};
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

2- And set it's textContent as the value we want to copy.

textarea.textContent = content;
Enter fullscreen mode Exit fullscreen mode

3- Then we add our text area to body of DOM.

 document.body.appendChild(textarea);
Enter fullscreen mode Exit fullscreen mode

4- Select all the text in textarea.

textarea.select();
Enter fullscreen mode Exit fullscreen mode

5- We use execCommand("copy") for copying the content that we selected.

document.execCommand("copy");
Enter fullscreen mode Exit fullscreen mode

6- Finally, we remove the textarea from DOM.

document.body.removeChild(textarea);
Enter fullscreen mode Exit fullscreen mode

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 😋

Discussion (0)