cover-img

How to copy to clipboard in javascript

JavaScript Web APIs got a bunch of methods to enhance the user experience of web applications. Learn how Copy-Paste is possible using JavaScript.

2 May, 2022

19

19

1

Copy-Paste is a fundamental need in application usage. Our users need this feature in the applications and websites as much as we developers need it while programming 😉. In this article, we will learn the JavaScript APIs available to help with copy-paste programmatically.

What is Clipboard?

A clipboard is short-term storage to keep some information and data for some moment. The operating system provides this storage for applications to keep relevant data for a shorter duration such that the application/program can read it at a later point in time. The clipboard's content is usually managed in the computer's RAM(Random Access Memory).

How to copy to the clipboard?

JavaScript provides Asynchronous web APIs to copy the content to the clipboard. The JavaScript navigator object has the helpful clipboard API methods. The `writeText()' method is responsible for copying(or writing) to the clipboard.


The writeText() method takes the value to copy(or write to the clipboard) as an argument. You must also handle the error using a try-catch block. The code snippet above shows how to copy to the clipboard using the writeText method.

How to paste?

The method readText() is used to read the content from the clipboard,, and thus, you can paste it to a target application.


Support of the clipboard APIs in JavaScript

Several web browsers already support the clipboard APIs. You can check the current support from here. As a measure, you must check for the navigator.clipboard availability using a simple if-else condition as we have seen in the code snippets above.

Try it Out

You can try out the Copy-Paste functionality using JavaScript clipboard APIs from here,

Clipboard API Demo on Web APIs Playground

Also, check the extensive API documentation from the MDN Doc.

That's all for now. I hope you found this article helpful.

Let's connect, I keep sharing tips & knowledge on these platforms:

javascript

javascript project

web development

js

asynchronous

19

19

1

javascript

javascript project

web development

js

asynchronous

Tapas Adhikary
Educator @tapaScript | Teaching JavaScript/React/FullStack | Writer | YouTuber | Founder reactplay.io

More Articles