Lightning Aura Components – How to Perform Copy to Clipboard in Lightning Component

I have button onclick of that button the text present in the text area should be copied.In visualforce im able to perform this operation using document.execCommand('copy') but in lightning it says the function in not available.

copyText:function(component,event,helper)
{           
    var doc = component.find("text").get("v.value");
    console.log('doc=='+doc);
    doc.queryCommandSupported('copy');
    doc.execCommand('copy');

},

This i have used in the component,

<lightning:textarea aura:id="text"  name="myTextArea" label="Input 
Text" maxlength="300" />                                              

Best Answer

Currently I do not have option to select text of lightning:textarea as only focus and showHelpMessageIfInvalid methods are available for lightning:textarea. You can use html tag textarea, as proxy SecureElement object supports select method and proxy SecureDocument supports both queryCommandSupported and execCommand.

Component

<textarea id="text" value="Hello SF" maxlength="300" />  
<lightning:button variant="base" label="Copy to Clipboard" onclick="{!c.copyText}"/>

Controller

({
    copyText: function(cmp, event, helper) {
        var textareaElement = document.getElementById('text');
        textareaElement.select();
        document.queryCommandSupported('copy')
        document.execCommand('copy');
        textareaElement.blur();
    }
})
Related Topic