From 7620f2cba1bb25996cfcaa857c7cbbf464468e16 Mon Sep 17 00:00:00 2001 From: Khairul Hidayat Date: Sun, 18 Aug 2024 06:37:51 +0700 Subject: [PATCH] fix: copyToClipboard fix on non secure context --- src/lib/utils.ts | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 380b23e..ee82a1d 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -24,10 +24,27 @@ export const handleError = (err: unknown) => { }; export const copyToClipboard = async (text: string) => { + let textArea: HTMLTextAreaElement | undefined; + try { - await navigator.clipboard.writeText(text); + if (navigator.clipboard && window.isSecureContext) { + await navigator.clipboard.writeText(text); + } else { + textArea = document.createElement("textarea"); + textArea.value = text; + + textArea.style.position = "absolute"; + textArea.style.left = "-999999px"; + + document.body.prepend(textArea); + textArea.select(); + document.execCommand("copy"); + } + toast.success("Copied to clipboard"); } catch (err) { handleError(err); + } finally { + textArea?.remove(); } };