[SalesForce] Copy to the Clipboard in Lightning Component

I'm creating Lightning Component that displays Classic version of the Current URL record page with a button that onclick copy to the clipboard that URL.

Just a simple functionality that saves time for Lightning Users, when they need to send a URL of the record to non-Lightning users.

Cmp:

<lightning:button class="slds-align_right slds-button slds-button_neutral" iconName="utility:copy_to_clipboard" variant="border-filled" label="Copy" onclick="{! c.copyClassic }"/>
<textarea readonly="true" id="urlClassic">https://name.my.salesforce.com/{!v.recordId}</textarea>

Controller:

({
   copyClassic : function(cmp, event){
     var urlClassic = document.getElementById('urlClassic');
     urlClassic.select();
     document.queryCommandSupported('copy');
     document.execCommand('copy');
     //urlClassic.remove();

     var source = event.getSource();
     source.set('v.label', 'COPIED!');
     setTimeout(function(){
      source.set('v.label', 'Copy');
     }, 2000);
} })

It is working on first time when I open record and clicked the button. It selecting the url and copy to the clipboard. But if I open a new record in the same window, Textarea displays new URL and button changed to 'COPIED!' but the URL is not selected and not copied.

I assume it may have something to do with the fact that Lightning Component is SPA and when I open new record in the same window it's not refreshing the page.

It's working when I add remove() method but then if user would like to copy URL again (while still on the same page) will have to refresh the page to perform the same action.

Does anyone has similar issue or idea to solve this problem?

Best Answer

I've always found that when selecting elements in the DOM, instead of using "id" and "document.getElementById", it's better to use "aura:id" and "cmp.find('xxxxx').getElement()".

For example, change the textarea element to:

<textarea readonly="true" aura:id="urlClassic">https://name.my.salesforce.com/{!v.recordId}</textarea>

And change your selection code in your controller to:

cmp.find('urlClassic').getElement().select();

Give this a try and see if it fixes the issues you're seeing. I tried it very quickly in a sandbox and it seems to work reliably. However, my environment is based on console and Lightning Experience, not a SPA like you said you have. But, since it's still Lightning, it should work.