@@ -2,6 +2,7 @@ import { toast } from 'svelte-sonner';
22
33/**
44 * Copy text to clipboard with toast notification
5+ * Uses modern clipboard API when available, falls back to legacy method for non-secure contexts
56 * @param text - Text to copy to clipboard
67 * @param successMessage - Custom success message (optional)
78 * @param errorMessage - Custom error message (optional)
@@ -13,9 +14,32 @@ export async function copyToClipboard(
1314 errorMessage = 'Failed to copy to clipboard'
1415) : Promise < boolean > {
1516 try {
16- await navigator . clipboard . writeText ( text ) ;
17- toast . success ( successMessage ) ;
18- return true ;
17+ // Try modern clipboard API first (secure contexts only)
18+ if ( navigator . clipboard && navigator . clipboard . writeText ) {
19+ await navigator . clipboard . writeText ( text ) ;
20+ toast . success ( successMessage ) ;
21+ return true ;
22+ }
23+
24+ // Fallback for non-secure contexts
25+ const textArea = document . createElement ( 'textarea' ) ;
26+ textArea . value = text ;
27+ textArea . style . position = 'fixed' ;
28+ textArea . style . left = '-999999px' ;
29+ textArea . style . top = '-999999px' ;
30+ document . body . appendChild ( textArea ) ;
31+ textArea . focus ( ) ;
32+ textArea . select ( ) ;
33+
34+ const successful = document . execCommand ( 'copy' ) ;
35+ document . body . removeChild ( textArea ) ;
36+
37+ if ( successful ) {
38+ toast . success ( successMessage ) ;
39+ return true ;
40+ } else {
41+ throw new Error ( 'execCommand failed' ) ;
42+ }
1943 } catch ( error ) {
2044 console . error ( 'Failed to copy to clipboard:' , error ) ;
2145 toast . error ( errorMessage ) ;
0 commit comments