How to copy to Clipboard in Salesforce Lightning Web Component?

How to copy to Clipboard in Salesforce Lightning Web Component?

navigator.clipboard.writeText() can be used to copy text to Clipboard in Salesforce Lightning Web Component.

Sample Lightning Web Component:

HTML:

<template>
    <lightning-card>
        <div style="padding:0.5rem;background:grey">
            <div class="slds-text-color_inverse">
                Sample Clipboard Text
                <lightning-button-icon
                    icon-name={iconName}
                    size="medium"
                    alternative-text={altText}
                    onclick={handleCopy}
                    class="slds-p-around_x-small">
                </lightning-button-icon>
            </div>
        </div>
    </lightning-card>
</template>

JavaScript:

import { LightningElement } from 'lwc';

export default class SampleLightningWebComponent extends LightningElement {

    iconName = 'utility:copy';
    altText = 'Copy Text';

    handleCopy() {

        console.log(
            'Inside Handle Copy'
        );

        if (
            navigator.clipboard && 
            window.isSecureContext
        ) {

            this.iconName = 'utility:check';
            this.altText = 'Text Copied';
            return navigator.clipboard.writeText(
                'Sample Clipboard Text'
            );

        }

    }

}

js-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>60.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>

Leave a Reply