当前位置: 首页 > news >正文

复制文本到剪贴板(跨平台兼容)

/**
* 复制文本到剪贴板(跨平台兼容)
* @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;}
}
http://www.zskr.cn/news/125070.html

相关文章:

  • 2025年12月金包银品牌TOP10品牌:工艺/品控/售后三维分析,新手避坑首选 - 小白条111
  • 第十七节:高并发秒杀方案各类小问题总结
  • 赫斯特 (Hurst)计算——重标极差法(R/S法)
  • 英语_阅读_Incorrect beliefs_待读
  • 基于深度学习的非机动车头盔检测系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
  • OOP-实验六
  • 看三泽纱千香负能量发言有感
  • RAG的系列文章,有空可以看看
  • Day65-F:\硕士阶段\Java\课程资料\1、黑马程序员Java项目《苍穹外卖》企业级开发实战\sky-take-out-Git-苍穹外卖-swagger-接口文档
  • 计算机图形学|三维变换与变换矩阵
  • 数据安全新选择:访答本地知识库的隐私守护之道
  • 详细介绍:ThinkPHP 5.1 程序在 Nginx 和 Apache 下的性能对比
  • 实实在在不夸大值得推荐的银川AI搜索优化公司——智美天创
  • 个人经验记录
  • 聊天软件项目系统设计总结
  • 完整教程:xorrisofs的系统架构与开源地址
  • 2025年12月篮球场运动木地板,实木运动木地板,枫木运动木地板厂家推荐,高性能与可靠性兼具的优质品牌 - 品牌鉴赏师
  • RPA在财务领域的应用,重塑管理会计发展格局 - 详解
  • Day6 16. 位置互换 -卡码网C++基础课
  • Java毕业设计如何顺利凭借
  • langfuse-LLM 模版评估选择
  • 升级二进制kubernetes集群(小版本升级)
  • AI也会说谎?揭秘可靠RAG让智能助手不再胡说八道
  • Day6 14. 句子缩写 -卡码网C++基础课
  • 实用指南:VirtualBox 6.1.50 新建 Windows 7 Ultimate SP1 64位虚拟机完整流程指南
  • why name should be short
  • 河南山特UPS电源标杆|艾佩斯20年专注全场景电源解决方案 - 朴素的承诺
  • 2025中国电线电缆品牌推荐:全场景电力传输的优质之选 - 黑马榜单
  • 寒假/日常实习经历
  • 为什么员工绩效评估不起作用