fuzzyworld

dao-game / files / src / utils / clipboard.ts

clipboard.ts

885 B · history · blame

1export async function copyToClipboard(textToCopy): Promise<void> {
2 // navigator clipboard api needs a secure context (https)
3 if (navigator.clipboard && window.isSecureContext) {
4 // navigator clipboard api method'
5 return navigator.clipboard.writeText(textToCopy);
6 } else {
7 // text area method
8 let textArea = document.createElement("textarea");
9 textArea.value = textToCopy;
10 // make the textarea out of viewport
11 textArea.style.position = "fixed";
12 textArea.style.left = "-999999px";
13 textArea.style.top = "-999999px";
14 document.body.appendChild(textArea);
15 textArea.focus();
16 textArea.select();
17 return new Promise((res, rej) => {
18 // here the magic happens
19 document.execCommand('copy') ? res() : rej();
20 textArea.remove();
21 });
22 }
23}