How to copy text to the Clipboard | JavaScript

navigator.clipboard.writeText("Copy this to Clipboard");

Clipboard API

The Clipboard interface implements the Clipboard API, providing if the user grants permission to both read and write access to the contents of the system clipboard. The navigator.clipboard API is a recent addition to the specification and may not be fully implemented in all browsers.

Navigator.clipboard API

The system Clipboard is exposed through the global Navigator.clipboard property. This API provide separate methods to read or write:
  1. Writing to Clipboard : navigator.clipboard.writeText()
  2. Reading from Clipboard : navigator.clipboard.readText()

Copy to the Clipboard

Full Source | JavaScript
<!DOCTYPE html> <html> <body> <input type="text" value="Copy this to Clipboard" id="myTxt"> <button onclick="copyTo()">Copy</button> <script> function copyTo() { var mTxt = document.getElementById("myTxt"); navigator.clipboard.writeText(mTxt.value); alert("Clipboard content : " + mTxt.value); } </script> </body> </html>

Is your clipboard safe to use?

How can I copy text to clipboard with JavaScript
It's safe to assume that most of us consider the clipboard as temporary data sharing. Once you copy something previous data in the clipboard will be overwritten. People rely on this assumption when they copy sensitive information such as passwords. But, automatic copying to the clipboard may be dangerous, and therefore most browsers (except IE) make it very difficult. So, try to use the following simple trick:
function copyToClipboard(text) { window.prompt("Copy to clipboard - Press : Ctrl+C and Enter", text); }
The user is presented with the prompt box, where the text to be copied is already selected. Now it's enough to press Ctrl + C and Enter (to close the box). Now the clipboard copy operation is safe, because the user does it manually.
run this source code Browser View
Full Source | JavaScript
<!DOCTYPE html> <html> <body> <button id="myBtn" onclick="copyToClipboard(document.getElementById('myBtn').innerHTML)">Copy this to Clipboard</button> <script> function copyToClipboard(text) { window.prompt("Copy to clipboard - Press : Ctrl+C and Enter", text); } </script> </body> </html>
This method only supports single line and there is a limit on the amount of characters displayed in that dialog, and thus there is a limit on the amount of data to be copied.