copyText.ts 1.8 KB

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