File tree Expand file tree Collapse file tree 1 file changed +32
-1
lines changed Expand file tree Collapse file tree 1 file changed +32
-1
lines changed Original file line number Diff line number Diff line change @@ -16,6 +16,33 @@ function onError(btn) {
1616 btn . dataset . content = btn . dataset . original ;
1717}
1818
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+
1946export default function initGlobalCopyToClipboardListener ( ) {
2047 document . addEventListener ( 'click' , async ( e ) => {
2148 let target = e . target ;
@@ -33,7 +60,11 @@ export default function initGlobalCopyToClipboardListener() {
3360 await navigator . clipboard . writeText ( text ) ;
3461 onSuccess ( target ) ;
3562 } catch {
36- onError ( target ) ;
63+ if ( fallbackCopyToClipboard ( text ) ) {
64+ onSuccess ( target ) ;
65+ } else {
66+ onError ( target ) ;
67+ }
3768 }
3869 break ;
3970 }
You can’t perform that action at this time.
0 commit comments