* 复制文本到剪贴板(跨平台兼容)
* @param text 要复制的文本
* @returns 是否成功
*/
static async copyToClipboard(textData: string): Promise<boolean> {
try {
// 首先尝试现代剪贴板API
if (navigator.clipboard && navigator.clipboard.writeText) {
try {
await navigator.clipboard.writeText(textData);
console.log('[SandBlockEditorUtils] 使用现代剪贴板API复制成功');
return;
} catch (clipboardError) {
console.warn('[SandBlockEditorUtils] 现代剪贴板API失败,尝试备用方案:', clipboardError);
// 如果是焦点问题,尝试先获取焦点
if (clipboardError.name === 'NotAllowedError') {
// eslint-disable-next-line
try {
// 尝试获取焦点
window.focus();
document.body.focus();
await new Promise((resolve) => setTimeout(resolve, 100)); // 等待100ms
await navigator.clipboard.writeText(textData);
console.log('[SandBlockEditorUtils] 获取焦点后复制成功');
return;
} catch (retryError) {
console.warn('[SandBlockEditorUtils] 重试后仍失败,使用传统方法:', retryError);
}
}
}
}
// 回退方案:使用传统的execCommand方法
console.log('[SandBlockEditorUtils] 使用传统复制方法');
const textArea = document.createElement('textarea');
textArea.value = textData;
textArea.style.position = 'fixed';
textArea.style.left = '-9999px';
textArea.style.top = '-9999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
const successful = document.execCommand('copy');
document.body.removeChild(textArea);
if (!successful) {
throw new Error('传统复制方法也失败了');
}
console.log('[SandBlockEditorUtils] 传统复制方法成功');
} catch (error) {
console.error('[SandBlockEditorUtils] 所有复制方法都失败了:', error);
throw error;
}
}