diff --git a/src/utils/index.ts b/src/utils/index.ts index d061183cc..2cd96b4db 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -1,8 +1,27 @@ -export const copyToClipboard = async (content: string): Promise => { - return navigator.clipboard - .writeText(content) - .then(() => true) - .catch(() => false); +export const copyToClipboard = async (content: string) => { + // Navigator clipboard api needs a secure context (https) + if (navigator.clipboard && window.isSecureContext) { + await navigator.clipboard.writeText(content); + } else { + // Use the 'out of viewport hidden text area' trick + const textArea = document.createElement('textarea'); + textArea.value = content; + + // Move textarea out of the viewport so it's not visible + textArea.style.position = 'absolute'; + textArea.style.left = '-999999px'; + + document.body.prepend(textArea); + textArea.select(); + + try { + document.execCommand('copy'); + } catch (error) { + console.error(error); + } finally { + textArea.remove(); + } + } }; export const saveToFile = (