index.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. export default function copyTextToClipboard(input, {target = document.body} = {}) {
  2. const element = document.createElement('textarea');
  3. const previouslyFocusedElement = document.activeElement;
  4. element.value = input;
  5. // Prevent keyboard from showing on mobile
  6. element.setAttribute('readonly', '');
  7. element.style.contain = 'strict';
  8. element.style.position = 'absolute';
  9. element.style.left = '-9999px';
  10. element.style.fontSize = '12pt'; // Prevent zooming on iOS
  11. const selection = document.getSelection();
  12. let originalRange = false;
  13. if (selection.rangeCount > 0) {
  14. originalRange = selection.getRangeAt(0);
  15. }
  16. target.append(element);
  17. element.select();
  18. // Explicit selection workaround for iOS
  19. element.selectionStart = 0;
  20. element.selectionEnd = input.length;
  21. let isSuccess = false;
  22. try {
  23. isSuccess = document.execCommand('copy');
  24. } catch {}
  25. element.remove();
  26. if (originalRange) {
  27. selection.removeAllRanges();
  28. selection.addRange(originalRange);
  29. }
  30. // Get the focus back on the previously focused element, if any
  31. if (previouslyFocusedElement) {
  32. previouslyFocusedElement.focus();
  33. }
  34. return isSuccess;
  35. }