Thought leadership from the most innovative tech companies, all in one place.

How To Copy/Paste Text Into Clipboard Using JavaScript

image

Copy/Paste text into Clipboard can be done using Navigator.

A Navigator is an interface in JavaScript that gives the information about the user agent (here browser), helps to manage browser permissions, and comes with some really useful utility functions to know the state and identity of the user agent.

Navigator object can be used using a read-only window.navigator or simply navigator property.

Some of the useful properties of Navigator are

  1. navigator.onLine — returns true if the browser has network connectivity, otherwise, returns false.

  2. navigator.clipboard — Used to copy/paste the content into the clipboard

  3. navigator.geolocation — Used to get the device location.

  4. navigator.permissions — Used to get the Permission Status of the APIs covered by Permissions API.

In this article, we'll check navigator.clipboard property.

Copy Text

  1. Copying text from an input box
<input type="text" id="copy-text-input" placeholder="Enter text to be copied" />
<button>Copy Text</button>

HTML for clipboard copy from an input box

Here we are copying the content from the input box on the button click.

let copyButton = document.getElementsByTagName("button");
copyButton.addEventListener("click", function () {
  navigator.clipboard
    .writeText(document.getElementById("copy-text-input").value)
    .then(
      (success) => console.log("text copied"),
      (err) => console.log("error copying text")
    );
});

JS for clipboard copy from an input box

navigator.clipboard.writeText() accepts a DOMString, here we are reading the value from the text box.

The function returns a Promise, which is resolved once the content on the clipboard is updated.

  1. Copying from an HTML Tag content
<p id="copy-text">Hey, there!</p>
<button>Copy Text</button>

HTML for clipboard copy from a tag

document.addEventListener("DOMContentLoaded", function () {
  let copyButton = document.getElementsByTagName("button");
  copyButton.addEventListener("click", function () {
    navigator.clipboard
      .writeText(document.getElementById("copy-text").innerText)
      .then(
        (success) => console.log("text copied"),
        (err) => console.log("error copying text")
      );
  });
});

JS for clipboard copy from a tag

In the writeText() you can pass the innerText of the target element to copy text.

Paste Text

To paste the content into Clipboard, use the readText() on navigator.clipboard.

<button>Show the Copied Text</button>
<p id="clipboard-paste"></p>

HTML for clipboard paste

We'll paste content in the clipboard-paste tag innerText.

document.addEventListener('DOMContentLoaded',function(){
            let pasteButton = document.getElementsByTagName('button')[0];
            pasteButton.addEventListener('click', function () {
                navigator.clipboard
                    .readText()
                    .then(
                        cliptext =>
                            (document.getElementById('clipboard-paste').innerText = cliptext),
                            err => console.log(err)
                    );
            });

JS for clipboard paste

Similar to writeText(), readText() also returns a Promise which is resolved when there are permissions given to paste the content. When trying to paste, the browser asks for the below permission.

image

If you block the permission, the Promise is rejected with the message ‘DOMException: Read permission denied.'

Conclusion

  • Use navigator.clipboard to get access to the clipboard.

  • Use writeText() to copy text into the clipboard.

  • Use readText() to paste the text.

  • Make sure you have given browser permissions for Clipboard to avoid Promise rejections.

References:

https://developer.mozilla.org/en-US/docs/Web/API/Navigator/clipboard

That's all! Hope this article was useful!.




Continue Learning