@@ -22,7 +22,7 @@ export const useClipboard = (textToCopy: string): UseClipboardResult => {
22
22
setIsCopied ( false ) ;
23
23
} , 1000 ) ;
24
24
} catch ( err ) {
25
- const isCopied = simulateClipboardWrite ( ) ;
25
+ const isCopied = simulateClipboardWrite ( textToCopy ) ;
26
26
if ( isCopied ) {
27
27
setIsCopied ( true ) ;
28
28
timeoutIdRef . current = window . setTimeout ( ( ) => {
@@ -44,12 +44,16 @@ export const useClipboard = (textToCopy: string): UseClipboardResult => {
44
44
} ;
45
45
46
46
/**
47
+ * Provides a fallback clipboard method for when browsers do not have access
48
+ * to the clipboard API (the browser is older, or the deployment is only running
49
+ * on HTTP, when the clipboard API is only available in secure contexts).
50
+ *
47
51
* It feels silly that you have to make a whole dummy input just to simulate a
48
52
* clipboard, but that's really the recommended approach for older browsers.
49
53
*
50
54
* @see {@link https://web.dev/patterns/clipboard/copy-text?hl=en }
51
55
*/
52
- function simulateClipboardWrite ( ) : boolean {
56
+ function simulateClipboardWrite ( textToCopy : string ) : boolean {
53
57
const previousFocusTarget = document . activeElement ;
54
58
const dummyInput = document . createElement ( "input" ) ;
55
59
@@ -70,12 +74,26 @@ function simulateClipboardWrite(): boolean {
70
74
style . border = "0" ;
71
75
72
76
document . body . appendChild ( dummyInput ) ;
77
+ dummyInput . value = textToCopy ;
73
78
dummyInput . focus ( ) ;
74
79
dummyInput . select ( ) ;
75
80
76
- const isCopied = document . execCommand ( "copy" ) ;
77
- dummyInput . remove ( ) ;
81
+ /**
82
+ * The document.execCommand method is officially deprecated. Browsers are free
83
+ * to remove the method entirely or choose to turn it into a no-op function
84
+ * that always returns false. You cannot make any assumptions about how its
85
+ * core functionality will be removed.
86
+ *
87
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Clipboard }
88
+ */
89
+ let isCopied : boolean ;
90
+ try {
91
+ isCopied = document ?. execCommand ( "copy" ) ?? false ;
92
+ } catch {
93
+ isCopied = false ;
94
+ }
78
95
96
+ dummyInput . remove ( ) ;
79
97
if ( previousFocusTarget instanceof HTMLElement ) {
80
98
previousFocusTarget . focus ( ) ;
81
99
}
0 commit comments