From d3600daf5c55cc884f4a0311ee7335bdad529a1a Mon Sep 17 00:00:00 2001 From: luocong2016 Date: Tue, 12 Dec 2023 15:25:13 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20navigator.clipboard=20=E5=85=BC=E5=AE=B9?= =?UTF-8?q?=E9=97=AE=E9=A2=98=20#3372=20(#3403)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../setting/components/SettingFooter.vue | 11 ++--- src/utils/copyTextToClipboard.ts | 45 +++++++++++++++---- 2 files changed, 43 insertions(+), 13 deletions(-) diff --git a/src/layouts/default/setting/components/SettingFooter.vue b/src/layouts/default/setting/components/SettingFooter.vue index 13c5e5764..b61da43e4 100644 --- a/src/layouts/default/setting/components/SettingFooter.vue +++ b/src/layouts/default/setting/components/SettingFooter.vue @@ -46,13 +46,14 @@ const appStore = useAppStore(); function handleCopy() { - copyText(JSON.stringify(unref(appStore.getProjectConfig), null, 2), null); - - createSuccessModal({ - title: t('layout.setting.operatingTitle'), - content: t('layout.setting.operatingContent'), + copyText(JSON.stringify(unref(appStore.getProjectConfig), null, 2), null).then(() => { + createSuccessModal({ + title: t('layout.setting.operatingTitle'), + content: t('layout.setting.operatingContent'), + }); }); } + function handleResetSetting() { try { appStore.setProjectConfig(defaultSetting); diff --git a/src/utils/copyTextToClipboard.ts b/src/utils/copyTextToClipboard.ts index 74fc795b8..236e91473 100644 --- a/src/utils/copyTextToClipboard.ts +++ b/src/utils/copyTextToClipboard.ts @@ -1,12 +1,41 @@ import { message } from 'ant-design-vue'; +// `navigator.clipboard` 可能因浏览器设置或浏览器兼容而造成兼容问题 export function copyText(text: string, prompt: string | null = '已成功复制到剪切板!') { - navigator.clipboard.writeText(text).then( - function () { - prompt && message.success(prompt); - }, - function (error: Error) { - message.error('复制失败!' + error.message); - }, - ); + if (navigator.clipboard) { + return navigator.clipboard + .writeText(text) + .then(() => { + prompt && message.success(prompt); + }) + .catch((error) => { + message.error('复制失败!' + error.message); + return error; + }); + } + if (Reflect.has(document, 'execCommand')) { + return new Promise((resolve, reject) => { + try { + const textArea = document.createElement('textarea'); + textArea.value = text; + // 在手机 Safari 浏览器中,点击复制按钮,整个页面会跳动一下 + textArea.style.width = '0'; + textArea.style.position = 'fixed'; + textArea.style.left = '-999px'; + textArea.style.top = '10px'; + textArea.setAttribute('readonly', 'readonly'); + document.body.appendChild(textArea); + textArea.select(); + document.execCommand('copy'); + document.body.removeChild(textArea); + + prompt && message.success(prompt); + resolve(); + } catch (error) { + message.error('复制失败!' + error.message); + reject(error); + } + }); + } + return Promise.reject(`"navigator.clipboard" 或 "document.execCommand" 中存在API错误, 拷贝失败!`); }