File tree 1 file changed +32
-1
lines changed
1 file changed +32
-1
lines changed Original file line number Diff line number Diff line change @@ -16,6 +16,33 @@ function onError(btn) {
16
16
btn . dataset . content = btn . dataset . original ;
17
17
}
18
18
19
+ /**
20
+ * Fallback to use if navigator.clipboard doesn't exist.
21
+ * Achieved via creating a temporary textarea element, selecting the text, and using document.execCommand.
22
+ */
23
+ function fallbackCopyToClipboard ( text ) {
24
+ if ( ! document . execCommand ) return false ;
25
+
26
+ const tempTextArea = document . createElement ( 'textarea' ) ;
27
+ tempTextArea . value = text ;
28
+
29
+ // avoid scrolling
30
+ tempTextArea . style . top = 0 ;
31
+ tempTextArea . style . left = 0 ;
32
+ tempTextArea . style . position = 'fixed' ;
33
+
34
+ document . body . appendChild ( tempTextArea ) ;
35
+
36
+ tempTextArea . select ( ) ;
37
+
38
+ // if unsecure (not https), there is no navigator.clipboard, but we can still use document.execCommand to copy to clipboard
39
+ const success = document . execCommand ( 'copy' ) ;
40
+
41
+ document . body . removeChild ( tempTextArea ) ;
42
+
43
+ return success ;
44
+ }
45
+
19
46
export default function initGlobalCopyToClipboardListener ( ) {
20
47
document . addEventListener ( 'click' , async ( e ) => {
21
48
let target = e . target ;
@@ -33,7 +60,11 @@ export default function initGlobalCopyToClipboardListener() {
33
60
await navigator . clipboard . writeText ( text ) ;
34
61
onSuccess ( target ) ;
35
62
} catch {
36
- onError ( target ) ;
63
+ if ( fallbackCopyToClipboard ( text ) ) {
64
+ onSuccess ( target ) ;
65
+ } else {
66
+ onError ( target ) ;
67
+ }
37
68
}
38
69
break ;
39
70
}
You can’t perform that action at this time.
0 commit comments