Skip to content

Instantly share code, notes, and snippets.

@yinxin630
Created August 5, 2020 09:29
Show Gist options
  • Save yinxin630/32dace8f27cf18ca0587e6dc8b98f42e to your computer and use it in GitHub Desktop.
Save yinxin630/32dace8f27cf18ca0587e6dc8b98f42e to your computer and use it in GitHub Desktop.
export default async function copyToClipboard(str: string) {
if (navigator?.clipboard) {
return navigator.clipboard.writeText(str);
}
if (document?.execCommand) {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
el.select();
const execCopyResult = document.execCommand('copy');
document.body.removeChild(el);
return execCopyResult ? Promise.resolve() : Promise.reject();
}
return Promise.reject();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment