fix: navigator.clipboard 兼容问题 #3372 (#3403)

This commit is contained in:
luocong2016 2023-12-12 15:25:13 +08:00 committed by GitHub
parent f4df2d5a4b
commit d3600daf5c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 13 deletions

View File

@ -46,13 +46,14 @@
const appStore = useAppStore(); const appStore = useAppStore();
function handleCopy() { function handleCopy() {
copyText(JSON.stringify(unref(appStore.getProjectConfig), null, 2), null); copyText(JSON.stringify(unref(appStore.getProjectConfig), null, 2), null).then(() => {
createSuccessModal({
createSuccessModal({ title: t('layout.setting.operatingTitle'),
title: t('layout.setting.operatingTitle'), content: t('layout.setting.operatingContent'),
content: t('layout.setting.operatingContent'), });
}); });
} }
function handleResetSetting() { function handleResetSetting() {
try { try {
appStore.setProjectConfig(defaultSetting); appStore.setProjectConfig(defaultSetting);

View File

@ -1,12 +1,41 @@
import { message } from 'ant-design-vue'; import { message } from 'ant-design-vue';
// `navigator.clipboard` 可能因浏览器设置或浏览器兼容而造成兼容问题
export function copyText(text: string, prompt: string | null = '已成功复制到剪切板!') { export function copyText(text: string, prompt: string | null = '已成功复制到剪切板!') {
navigator.clipboard.writeText(text).then( if (navigator.clipboard) {
function () { return navigator.clipboard
prompt && message.success(prompt); .writeText(text)
}, .then(() => {
function (error: Error) { prompt && message.success(prompt);
message.error('复制失败!' + error.message); })
}, .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错误, 拷贝失败!`);
} }