Clipboard Copy Functionality in Lightning Web Components

Let’s explore the implementation of the copy to clipboard functionality in Lightning Web Components (LWC).

Possessing the capability to copy text to the clipboard and subsequently paste it can be a crucial asset from an agent’s perspective.

In this post, I will guide you through the process of implementing this functionality in Lightning Web Components (LWC).

The approach is not entirely straightforward, as it requires working with the navigator API. However, it’s not overly challenging either.

Below 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();
      });
    }
  }
}