You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
38 lines
1.0 KiB
38 lines
1.0 KiB
import { message } from 'ant-design-vue' |
|
|
|
export function copyText(text: string, prompt: string | null = '已成功复制到剪切板!') { |
|
// 浏览器禁用了非安全域的 navigator.clipboard 对象 |
|
// 在线上环境会报错 TypeError: Cannot read properties of undefined (reading 'writeText') |
|
if (navigator.clipboard && window.isSecureContext) { |
|
navigator.clipboard.writeText(text).then( |
|
() => { |
|
prompt && message.success(prompt) |
|
}, |
|
(error: Error) => { |
|
message.error(`复制失败!${error.message}`) |
|
}, |
|
) |
|
} |
|
else { |
|
const textarea = document.createElement('textarea') |
|
textarea.value = text |
|
document.body.appendChild(textarea) |
|
textarea.select() |
|
|
|
try { |
|
// 尝试执行复制操作 |
|
const success = document.execCommand('copy') |
|
if (success) { |
|
message.success('复制成功') |
|
} |
|
else { |
|
message.error('复制失败') |
|
} |
|
} |
|
catch (error) { |
|
message.error(`复制失败:${error}`) |
|
} |
|
|
|
document.body.removeChild(textarea) |
|
} |
|
}
|
|
|