ClipBoard API in JavaScript

ClipBoard API in JavaScript

The Clipboard API in JavaScript allows you to read data from and write data to the system clipboard. This enables capabilities like copying text to the clipboard and pasting clipboard content into your web apps.

Check out this post on my Blog!


Copying Data to the Clipboard

The method navigator.clipboard.write() allows us to write data to the clipboard. The method returns a promise and takes 2 arguments:

  • The data to write (eg. string, text or DOM element/image)
  • The type of data. To copy plain text to the clipboard we can use the method above like this:
    navigator.clipboard.writeText('Sample text to save in clipboard!')
    .then(() => {
       console.log('Text copied!');
     })
     .catch(err => { 
       console.error(err.message);
    });
    

Reading Data from the Clipboard

The method navigator.clipboard.read() reads data from the clipboard and returns a promise. It takes one argument which is the type of data to read:

  • "text/plain" for plain text
  • "text/html" for HTML content
  • "image/*" for image data

To read plain text from the clipboard, we can use the method above like this:

navigator.clipboard.readText()
  .then(text => {
    console.log(text); 
  })
  .catch(err => {
    console.error(err);
});

Creating a Copy to Clipboard Button

Now let's create a practical example. You may have seen on many websites a button that let's you copy a code or some link. Let's see how we can build it. The HTML/CSS is simple and can be see in the codepen given below. For the JavaScript, we will first get the paragraph or text element using document.getElementById. Next, we will create a function that will save the innerText of the text element in the clipboard when the button is clicked.


Thank you for Reading! Check out this post on my Blog!