copyTextToClipboard.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { message } from 'ant-design-vue';
  2. // `navigator.clipboard` 可能因浏览器设置或浏览器兼容而造成兼容问题
  3. export function copyText(text: string, prompt: string | null = '已成功复制到剪切板!') {
  4. if (navigator.clipboard) {
  5. return navigator.clipboard
  6. .writeText(text)
  7. .then(() => {
  8. prompt && message.success(prompt);
  9. })
  10. .catch((error) => {
  11. message.error('复制失败!' + error.message);
  12. return error;
  13. });
  14. }
  15. if (Reflect.has(document, 'execCommand')) {
  16. return new Promise<void>((resolve, reject) => {
  17. try {
  18. const textArea = document.createElement('textarea');
  19. textArea.value = text;
  20. // 在手机 Safari 浏览器中,点击复制按钮,整个页面会跳动一下
  21. textArea.style.width = '0';
  22. textArea.style.position = 'fixed';
  23. textArea.style.left = '-999px';
  24. textArea.style.top = '10px';
  25. textArea.setAttribute('readonly', 'readonly');
  26. document.body.appendChild(textArea);
  27. textArea.select();
  28. document.execCommand('copy');
  29. document.body.removeChild(textArea);
  30. prompt && message.success(prompt);
  31. resolve();
  32. } catch (error) {
  33. message.error('复制失败!' + error.message);
  34. reject(error);
  35. }
  36. });
  37. }
  38. return Promise.reject(`"navigator.clipboard" 或 "document.execCommand" 中存在API错误, 拷贝失败!`);
  39. }