copyText.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * v-copyText 复制文本内容
  3. * Copyright (c) 2022 ruoyi
  4. */
  5. export default {
  6. beforeMount(el: any, { value, arg }: any) {
  7. if (arg === 'callback') {
  8. el.$copyCallback = value;
  9. } else {
  10. el.$copyValue = value;
  11. const handler = () => {
  12. copyTextToClipboard(el.$copyValue);
  13. if (el.$copyCallback) {
  14. el.$copyCallback(el.$copyValue);
  15. }
  16. };
  17. el.addEventListener('click', handler);
  18. el.$destroyCopy = () => el.removeEventListener('click', handler);
  19. }
  20. }
  21. };
  22. function copyTextToClipboard(input: string, { target = document.body } = {}) {
  23. const element = document.createElement('textarea');
  24. const previouslyFocusedElement = document.activeElement as HTMLInputElement;
  25. element.value = input;
  26. // Prevent keyboard from showing on mobile
  27. element.setAttribute('readonly', '');
  28. element.style.contain = 'strict';
  29. element.style.position = 'absolute';
  30. element.style.left = '-9999px';
  31. element.style.fontSize = '12pt'; // Prevent zooming on iOS
  32. const selection = document.getSelection();
  33. let originalRange;
  34. if (selection) {
  35. originalRange = selection?.rangeCount > 0 && selection.getRangeAt(0);
  36. }
  37. target.append(element);
  38. element.select();
  39. // Explicit selection workaround for iOS
  40. element.selectionStart = 0;
  41. element.selectionEnd = input.length;
  42. let isSuccess = false;
  43. try {
  44. isSuccess = document.execCommand('copy');
  45. } catch (err) {
  46. console.error(err);
  47. }
  48. element.remove();
  49. if (originalRange) {
  50. selection?.removeAllRanges();
  51. selection?.addRange(originalRange);
  52. }
  53. // Get the focus back on the previously focused element, if any
  54. if (previouslyFocusedElement) {
  55. previouslyFocusedElement.focus();
  56. }
  57. return isSuccess;
  58. }