index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. export default function copyTextToClipboard(text, {target = document.body} = {}) {
  2. if (typeof text !== 'string') {
  3. throw new TypeError(`Expected parameter \`text\` to be a \`string\`, got \`${typeof text}\`.`);
  4. }
  5. const element = document.createElement('textarea');
  6. const previouslyFocusedElement = document.activeElement;
  7. element.value = text;
  8. // Prevent keyboard from showing on mobile
  9. element.setAttribute('readonly', '');
  10. element.style.contain = 'strict';
  11. element.style.position = 'absolute';
  12. element.style.left = '-9999px';
  13. element.style.fontSize = '12pt'; // Prevent zooming on iOS
  14. const selection = document.getSelection();
  15. const originalRange = selection.rangeCount > 0 && selection.getRangeAt(0);
  16. target.append(element);
  17. element.select();
  18. // Explicit selection workaround for iOS
  19. element.selectionStart = 0;
  20. element.selectionEnd = text.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. }