This repository has been archived by the owner on Sep 2, 2024. It is now read-only.
forked from getAlby/nostr-wallet-connect
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: copy to clipboard on non-https sites (#440)
Co-authored-by: René Aaron <[email protected]>
- Loading branch information
1 parent
875ed2f
commit 1dface9
Showing
1 changed file
with
37 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,43 @@ | ||
import { toast } from "src/components/ui/use-toast"; | ||
|
||
export function copyToClipboard(content: string) { | ||
if (navigator.clipboard && window.isSecureContext) { | ||
navigator.clipboard.writeText(content); | ||
} else { | ||
// Fallback for older browsers | ||
const textArea = document.createElement("textarea"); | ||
textArea.value = content; | ||
textArea.style.position = "absolute"; | ||
textArea.style.opacity = "0"; | ||
document.body.appendChild(textArea); | ||
textArea.select(); | ||
new Promise((res, rej) => { | ||
document.execCommand("copy") ? res(content) : rej(); | ||
export async function copyToClipboard(content: string) { | ||
const copyPromise = new Promise((resolve, reject) => { | ||
if (navigator.clipboard && window.isSecureContext) { | ||
navigator.clipboard.writeText(content).then(resolve).catch(reject); | ||
} else { | ||
// Fallback for older browsers | ||
const textArea = document.createElement("textarea"); | ||
textArea.value = content; | ||
textArea.style.position = "absolute"; | ||
textArea.style.opacity = "0"; | ||
document.body.appendChild(textArea); | ||
selectElement(textArea); | ||
if (document.execCommand("copy")) { | ||
resolve(content); | ||
} else { | ||
reject(); | ||
} | ||
textArea.remove(); | ||
} | ||
}); | ||
|
||
try { | ||
await copyPromise; | ||
toast({ title: "Copied to clipboard." }); | ||
} catch (e) { | ||
toast({ | ||
title: "Failed to copy to clipboard.", | ||
variant: "destructive", | ||
}); | ||
} | ||
toast({ title: "Copied to clipboard." }); | ||
} | ||
|
||
function selectElement(element: Element) { | ||
const selection = window.getSelection(); | ||
if (selection) { | ||
selection.removeAllRanges(); | ||
const range = document.createRange(); | ||
range.selectNode(element); | ||
selection.addRange(range); | ||
} | ||
} |