click-to-copy.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. (function() {
  2. function fallbackCopyTextToClipboard(text, pasteTo = false) {
  3. var textArea = document.createElement("textarea");
  4. textArea.value = text;
  5. // Avoid scrolling to bottom
  6. textArea.style.top = "0";
  7. textArea.style.left = "0";
  8. textArea.style.position = "fixed";
  9. document.body.appendChild(textArea);
  10. textArea.focus();
  11. textArea.select();
  12. try {
  13. var successful = document.execCommand('copy');
  14. var msg = successful ? 'successful' : 'unsuccessful';
  15. console.log('Fallback: Copying text command was ' + msg);
  16. toastr.success('Copied!');
  17. pasteToElement(pasteTo, text);
  18. } catch (err) {
  19. console.error('Fallback: Oops, unable to copy', err);
  20. }
  21. document.body.removeChild(textArea);
  22. }
  23. function copyTextToClipboard(text, pasteTo = false) {
  24. if (!navigator.clipboard) {
  25. fallbackCopyTextToClipboard(text);
  26. return;
  27. }
  28. navigator.clipboard.writeText(text).then(function() {
  29. console.log('Async: Copying to clipboard was successful!');
  30. toastr.success('Copied!');
  31. pasteToElement(pasteTo, text);
  32. }, function(err) {
  33. console.error('Async: Could not copy text: ', err);
  34. });
  35. }
  36. function pasteToElement(_elem, _text) {
  37. if(_elem && _elem.length) {
  38. // if rte
  39. if(_elem.is('.ql-container') && _elem[0].__quill) {
  40. let qlRoot = _elem[0].__quill.root;
  41. if($.trim($(qlRoot.innerHTML).text()) === '') {
  42. _elem[0].__quill.clipboard.dangerouslyPasteHTML(0, _text);
  43. _elem[0].__quill.root.focus();
  44. }
  45. }
  46. else _elem.val(_text);
  47. }
  48. }
  49. function init() {
  50. $(document)
  51. .off('click.click-to-copy', '.click-to-copy')
  52. .on('click.click-to-copy', '.click-to-copy', function(event) {
  53. let self = $(this);
  54. copyTextToClipboard(self.text(),
  55. self.is('[auto-paste]') ? self.closest('form').find(self.attr('auto-paste')) : false);
  56. });
  57. window.copyTextToClipboard = copyTextToClipboard;
  58. }
  59. addMCInitializer('click-to-copy', init);
  60. }).call(window);