Skip to content

Commit

Permalink
fix: navigator.clipboard 兼容问题 #3372 (#3403)
Browse files Browse the repository at this point in the history
  • Loading branch information
luocong2016 committed Dec 12, 2023
1 parent f4df2d5 commit d3600da
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 13 deletions.
11 changes: 6 additions & 5 deletions src/layouts/default/setting/components/SettingFooter.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
45 changes: 37 additions & 8 deletions src/utils/copyTextToClipboard.ts
Original file line number Diff line number Diff line change
@@ -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<void>((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错误, 拷贝失败!`);
}

0 comments on commit d3600da

Please sign in to comment.