copyToClipboard.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * Copies text to clipboard by creating an almost invisible textarea,
  3. * adding text there, then running execCommand('copy').
  4. * Falls back to prompt() when the easy way fails (hello, Safari!)
  5. * From http://stackoverflow.com/a/30810322
  6. *
  7. * @param {String} textToCopy
  8. * @param {String} fallbackString
  9. * @return {Promise}
  10. */
  11. module.exports = function copyToClipboard (textToCopy, fallbackString) {
  12. fallbackString = fallbackString || 'Copy the URL below'
  13. return new Promise((resolve) => {
  14. const textArea = document.createElement('textarea')
  15. textArea.setAttribute('style', {
  16. position: 'fixed',
  17. top: 0,
  18. left: 0,
  19. width: '2em',
  20. height: '2em',
  21. padding: 0,
  22. border: 'none',
  23. outline: 'none',
  24. boxShadow: 'none',
  25. background: 'transparent'
  26. })
  27. textArea.value = textToCopy
  28. document.body.appendChild(textArea)
  29. textArea.select()
  30. const magicCopyFailed = () => {
  31. document.body.removeChild(textArea)
  32. window.prompt(fallbackString, textToCopy)
  33. resolve()
  34. }
  35. try {
  36. const successful = document.execCommand('copy')
  37. if (!successful) {
  38. return magicCopyFailed('copy command unavailable')
  39. }
  40. document.body.removeChild(textArea)
  41. return resolve()
  42. } catch (err) {
  43. document.body.removeChild(textArea)
  44. return magicCopyFailed(err)
  45. }
  46. })
  47. }