DEV Community

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

Posted on

4 2

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 😋

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more