24 lines
806 B
TypeScript
24 lines
806 B
TypeScript
export async function copyText(text: string) {
|
|
if (!text) throw new Error('没有可复制的内容');
|
|
if (navigator.clipboard?.writeText) {
|
|
try {
|
|
await navigator.clipboard.writeText(text);
|
|
return;
|
|
} catch {
|
|
// HTTP deployments and restrictive browser policies may reject Clipboard API.
|
|
}
|
|
}
|
|
|
|
const textarea = document.createElement('textarea');
|
|
textarea.value = text;
|
|
textarea.setAttribute('readonly', '');
|
|
textarea.style.position = 'fixed';
|
|
textarea.style.left = '-9999px';
|
|
document.body.appendChild(textarea);
|
|
textarea.select();
|
|
textarea.setSelectionRange(0, textarea.value.length);
|
|
const copied = document.execCommand('copy');
|
|
textarea.remove();
|
|
if (!copied) throw new Error('浏览器未允许写入剪贴板,请手工选择参数复制');
|
|
}
|