云南省网站建设_网站建设公司_C#_seo优化
2025/12/19 21:14:49 网站建设 项目流程

/**
* 复制文本到剪贴板(跨平台兼容)
* @param text 要复制的文本
* @returns 是否成功
*/
static async copyToClipboard(textData: string): Promise {
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;}
}

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询