copy-to-clipboard icon indicating copy to clipboard operation
copy-to-clipboard copied to clipboard

Use navigator.clipboard.writeText when available

Open silverwind opened this issue 5 years ago • 5 comments

This is a new promise-based API available available in some browsers which does not require DOM interaction to copy a string:

https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText https://jsfiddle.net/p73yv6re/

silverwind avatar Nov 20 '19 23:11 silverwind

I think a downside of this is it looks like you can only copy text, and can't specify the format. Am I incorrect here?

mlsad3 avatar Aug 21 '20 07:08 mlsad3

writeText is only for text. For other formats, there is write.

silverwind avatar Aug 21 '20 07:08 silverwind

To use the new api but still support older browsers i'm using this implementation. But might be good to add this to copy-to-clipboard.

async onClick() {
        try {
            await navigator.clipboard.writeText(shareUrl);
        } catch {
            // Otherwise we use copy-to-clipboard library that tries to use execCommand which is deprecated in modern browsers
            // when browser does not allow clipboard copy it will show a modal with the link in it
            copy(shareUrl);
        }
}

martinbroos avatar Nov 13 '20 09:11 martinbroos

I guess with this API available, this module is pretty much obsolete, so one option could be to not support it, letting this module exist only as a "legacy solution".

silverwind avatar May 25 '21 10:05 silverwind

I guess with this API available, this module is pretty much obsolete, so one option could be to not support it, letting this module exist only as a "legacy solution".

the new clipboard API just works on HTTPS or localhost. In some usage scenarios, such as intranet environments without domain name resolution and custom certificates, the new API is not available.

Reverier-Xu avatar Feb 19 '23 08:02 Reverier-Xu