Salesforce Interview Questions & Answers Book is now available!

Grab Now

LWC

Copy to Clipboard functionality in LWC

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

By Teja, ex-Salesforce engineer · Updated April 14, 2022 · 1 min read

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!

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion — one subscription.

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts