File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- export const copyToClipboard = async ( textToCopy : string ) => {
2- if ( navigator . clipboard && window . isSecureContext ) {
3- await navigator . clipboard . writeText ( textToCopy ) ;
4- } else {
5- const textArea = document . createElement ( "textarea" ) ;
6- textArea . value = textToCopy ;
7-
8- textArea . style . position = "absolute" ;
9- textArea . style . left = "-999999px" ;
10-
11- document . body . prepend ( textArea ) ;
12- textArea . select ( ) ;
13-
14- try {
15- document . execCommand ( 'copy' ) ;
16- } catch ( error ) {
17- console . error ( error ) ;
18- } finally {
1+ export const copyToClipboard = ( textToCopy : string ) : Promise < void > => {
2+ return new Promise ( ( resolve , reject ) => {
3+ if ( navigator . clipboard && window . isSecureContext ) {
4+ // Safari needs Transient Activation for writing to clipboard, pushing the write to callback queue
5+ // as a workaround
6+ setTimeout ( ( ) => {
7+ navigator . clipboard . writeText ( textToCopy )
8+ . then ( resolve )
9+ . catch ( reject ) ;
10+ } ) ;
11+ } else {
12+ const textArea = document . createElement ( "textarea" ) ;
13+ textArea . value = textToCopy ;
14+
15+ textArea . style . position = "absolute" ;
16+ textArea . style . left = "-999999px" ;
17+ document . body . prepend ( textArea ) ;
18+ textArea . select ( ) ;
19+
20+ try {
21+ const success = document . execCommand ( 'copy' ) ;
22+ success ? resolve ( ) : reject ( new Error ( 'Copy command failed' ) ) ;
23+ } catch ( err ) {
24+ reject ( err ) ;
25+ } finally {
1926 textArea . remove ( ) ;
27+ }
2028 }
21- }
22- }
29+ } ) ;
30+ } ;
31+
You can’t perform that action at this time.
0 commit comments