export async function copy(text: string): Promise<void> {
if (navigator.clipboard.writeText) {
try {
return navigator.clipboard.writeText(text);
} catch (err) {
// fall through...
}
}
legacyCopy(text);
}
function legacyCopy(text: string): void {
const input = document.createElement('input');
document.body.appendChild(input);
try {
input.value = text;
input.focus();
if (input.setSelectionRange) {
input.setSelectionRange(0, input.value.length);
} else {
input.select();
}
const result = document.execCommand('copy');
if (!result) {
throw new Error('unsupported');
}
} finally {
document.body.removeChild(input);
}
}
clipboard.ts
引入使用:
import {copy} from 'clipboard.ts'
copy('clipboard')