DEV Community

Cover image for How to read copied text from Clipboard using JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on Originally published at melvingeorge.me

How to read copied text from Clipboard using JavaScript?

Originally posted here!

To read a copied text from a clipboard in JavaScript, you can use the readText() method in the navigator.clipboard object.

// copy the text from clipboard
navigator.clipboard.readText().then((copiedText) => {
  console.log(copiedText); // copied text will be shown here.
});
Enter fullscreen mode Exit fullscreen mode
  • The readText() method returns a Promise.

Example on reading copied text

For example, suppose we want to display the copied text in the paragraph tag when we press a button.

Let's see how it's done.

First, let's create an empty paragraph tag and a button element.

<!-- Paragraph tag -->
<p id="textSpace"></p>
<!-- Button -->
<button id="btn">Click here to show the copied text in the paragraph</button>
Enter fullscreen mode Exit fullscreen mode

Now let's use JavaScript to listen for the click event in the button element and display the text in the paragraph tag.

// get reference to paragraph
const paragraph = document.getElementById("textSpace");

// get reference to the button
const button = document.getElementById("btn");

// add click event handler to the button
// so that after clicking the button
// the copied text will be displayed in the paragraph tag
button.addEventListener("click", () => {
  // copy the text from clipboard
  navigator.clipboard.readText().then((copiedText) => {
    paragraph.innerText = copiedText;
  });
});
Enter fullscreen mode Exit fullscreen mode

Feel free to share if you found this useful 😃.


Top comments (0)