0

I have a generic utility LWC to copy a bunch of text to clipboard on a button click. Content of the LWC is generated dynamically and could contain a list of items, each item can contain Hyperlinks as well. To sum it up, if I have a LWC that generates this below, how do I copy the content of this div to a clipboard with the hyperlink on a button click ?

<template>
<div class="container">
<a href="https://www.google.com"> Go to Google </a>
</div>
<template>

So far, I've tried this in my LWC JS and it throws an error

    const container = this.template.querySelector(".container");
    const range = document.createRange();
    range.selectNode(container);
    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);      
    const successful = document.execCommand('copy');

Error that's thrown is Failed to execute 'addRange' on 'Selection': parameter 1 is not of type 'Range'.]

Also, I've tried dynamically adding a textarea(hidden) to the dom and copy, but that doesn't support copying Hyperlinks, but only text.

How do I get to copy the entire div(with hyperelink) to clipboard here ?

2
  • 2
    This example works fine for me. I clicked on copy and pasted it in word and the URL was copied properly. Please see the example here. The only error I got was the template tag wasn't closed properly.
    – manjit5190
    May 5, 2020 at 5:13
  • Yes, it does work as I need in the playground. I'm not entirely sure, but the Playground works a bit different from a real SF org, where in the Locker Service returns a Proxy object when you do a querySelector, and hence the selectNode on the container throws an error.
    – mereMortal
    May 5, 2020 at 19:02

2 Answers 2

0

Look like now document.execCommand('copy'); is deprecated and navigator.clipboard.writeText() is not allowed by Lightning Security Locker, which means in 2023 there is no way to implement this functionality inside LWC.

0

I was able to achieve this functionality, it looks a little bit of DRY code but worked for me:

copyUrlToClipboard() {
    let url = this.receivedUrl;
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(url)
        .then(() => {
            this.showToast('Success', 'URL copied to clipboard', 'success');
        })
        .catch(err => {
            this.showToast('Error', 'URL did not copied, please try again', 'error');
            console.error('Failed to copy text: ', err);
        });
    } else {
        let input = document.createElement("input");
        input.value = url;
        document.body.appendChild(input);
        input.focus();
        input.select();
        document.execCommand("Copy");
        input.remove();
        this.showToast('Success', 'URL copied to clipboard', 'success');
    }
}

Please let me know if this works for you!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .