clipboard.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // Polyfill for Navigator.clipboard.writeText
  2. if (!navigator.clipboard) {
  3. navigator.clipboard = {
  4. writeText: text => {
  5. // A <span> contains the text to copy
  6. const span = document.createElement('span');
  7. span.textContent = text;
  8. span.style.whiteSpace = 'pre'; // Preserve consecutive spaces and newlines
  9. // Paint the span outside the viewport
  10. span.style.position = 'absolute';
  11. span.style.left = '-9999px';
  12. span.style.top = '-9999px';
  13. const win = window;
  14. const selection = win.getSelection();
  15. win.document.body.appendChild(span);
  16. const range = win.document.createRange();
  17. selection.removeAllRanges();
  18. range.selectNode(span);
  19. selection.addRange(range);
  20. let success = false;
  21. try {
  22. success = win.document.execCommand('copy');
  23. } catch (err) {
  24. return Promise.error();
  25. }
  26. selection.removeAllRanges();
  27. span.remove();
  28. return Promise.resolve();
  29. }
  30. }
  31. }