Copy to Clipboard functionality in LWC

Let's look at how to implement the copy to clipboard functionality in LWC

Having the ability to copy text to the clipboard and use the paste option to paste the text in the clipboard can be life safe from an agent's point of view.

In this post am gonna walk you through how we can implement that functionality in LWC.

The approach is not going to be straightforward, it needs us to work with navigator API, having said that it's not that hard too.

Here is the controller file that implements the copy-to-clipboard functionality.  

import { api, LightningElement, wire } from "lwc";

export default class Clipboard extends LightningElement {

  message = 'salesforce casts';
  
  async handleCopy() {
    let msg = `hey ${this.message}`;

    if (navigator.clipboard && window.isSecureContext) {
      return navigator.clipboard.writeText(msg);
    } else {
      let textArea = document.createElement("textarea");
      textArea.value = msg;
      textArea.style.position = "fixed";
      textArea.style.left = "-999999px";
      textArea.style.top = "-999999px";
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      return new Promise((res, rej) => {
        document.execCommand("copy") ? res() : rej();
        textArea.remove();
      });
    }
  }
}
clipboard.js

Hope this helps!