mirror of
https://github.com/snowykami/neo-blog.git
synced 2025-09-26 11:06:23 +00:00
refactor: 精简复制到剪贴板的实现,移除冗余注释和回退逻辑
This commit is contained in:
@ -7,23 +7,17 @@
|
||||
* 返回 Promise<boolean>,表示是否成功复制
|
||||
*/
|
||||
export async function copyToClipboard(text: string): Promise<boolean> {
|
||||
// 优先使用现代 Clipboard API
|
||||
try {
|
||||
if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return true;
|
||||
}
|
||||
} catch (err) {
|
||||
// 忽略并回退到老方法
|
||||
// console.warn('navigator.clipboard.writeText failed, falling back to execCommand', err);
|
||||
}
|
||||
|
||||
// 回退到 textarea + execCommand 方案(在许多旧浏览器上可用)
|
||||
if (typeof document === 'undefined') return false;
|
||||
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.value = text;
|
||||
// 防止页面滚动,把元素放到不可见但可选中的位置
|
||||
textarea.setAttribute('readonly', '');
|
||||
textarea.style.position = 'fixed';
|
||||
textarea.style.left = '-9999px';
|
||||
@ -31,7 +25,6 @@ export async function copyToClipboard(text: string): Promise<boolean> {
|
||||
textarea.style.opacity = '0';
|
||||
document.body.appendChild(textarea);
|
||||
|
||||
// 保存当前 selection(以便恢复)
|
||||
const selection = document.getSelection();
|
||||
let originalRange: Range | null = null;
|
||||
if (selection && selection.rangeCount > 0) {
|
||||
@ -42,9 +35,7 @@ export async function copyToClipboard(text: string): Promise<boolean> {
|
||||
textarea.setSelectionRange(0, textarea.value.length);
|
||||
|
||||
try {
|
||||
// 使用 any 绕开 TypeScript 中关于 execCommand 的弃用声明
|
||||
const successful = (document as any).execCommand('copy');
|
||||
// 清理并恢复 selection
|
||||
const successful = document.execCommand('copy');
|
||||
document.body.removeChild(textarea);
|
||||
if (selection) {
|
||||
selection.removeAllRanges();
|
||||
@ -52,7 +43,6 @@ export async function copyToClipboard(text: string): Promise<boolean> {
|
||||
}
|
||||
return Boolean(successful);
|
||||
} catch (err) {
|
||||
// 清理并恢复 selection
|
||||
document.body.removeChild(textarea);
|
||||
if (selection) {
|
||||
selection.removeAllRanges();
|
||||
|
Reference in New Issue
Block a user