trumbowyg.pasteembed.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /* ===========================================================
  2. * trumbowyg.pasteembed.js v1.0
  3. * Url paste to iframe with noembed. Plugin for Trumbowyg
  4. * http://alex-d.github.com/Trumbowyg
  5. * ===========================================================
  6. * Author : Max Seelig
  7. * Facebook : https://facebook.com/maxse
  8. * Website : https://www.maxmade.nl/
  9. */
  10. (function($) {
  11. 'use strict';
  12. var defaultOptions = {
  13. enabled: true,
  14. endpoints: [
  15. 'https://noembed.com/embed?nowrap=on',
  16. 'https://api.maxmade.nl/url2iframe/embed'
  17. ]
  18. };
  19. $.extend(true, $.trumbowyg, {
  20. plugins: {
  21. pasteEmbed: {
  22. init: function(trumbowyg) {
  23. trumbowyg.o.plugins.pasteEmbed = $.extend(true, {}, defaultOptions, trumbowyg.o.plugins.pasteEmbed || {});
  24. if (!trumbowyg.o.plugins.pasteEmbed.enabled) {
  25. return;
  26. }
  27. trumbowyg.pasteHandlers.push(function(pasteEvent) {
  28. try {
  29. var clipboardData = (pasteEvent.originalEvent || pasteEvent).clipboardData,
  30. pastedData = clipboardData.getData('Text'),
  31. endpoints = trumbowyg.o.plugins.pasteEmbed.endpoints,
  32. request = null;
  33. if (pastedData.startsWith('http')) {
  34. pasteEvent.stopPropagation();
  35. pasteEvent.preventDefault();
  36. var query = {
  37. url: pastedData.trim()
  38. };
  39. var content = '';
  40. var index = 0;
  41. if (request && request.transport) {
  42. request.transport.abort();
  43. }
  44. request = $.ajax({
  45. crossOrigin: true,
  46. url: endpoints[index],
  47. type: 'GET',
  48. data: query,
  49. cache: false,
  50. dataType: 'jsonp',
  51. success: function(res) {
  52. if (res.html) {
  53. index = 0;
  54. content = res.html;
  55. } else {
  56. index += 1;
  57. }
  58. },
  59. error: function() {
  60. index += 1;
  61. },
  62. complete: function() {
  63. if (content.length === 0 && index < endpoints.length - 1) {
  64. this.url = endpoints[index];
  65. this.data = query;
  66. $.ajax(this);
  67. }
  68. if (index === endpoints.length - 1) {
  69. content = $('<a>', {
  70. href: pastedData,
  71. text: pastedData
  72. }).prop('outerHTML');
  73. }
  74. if (content.length > 0) {
  75. index = 0;
  76. trumbowyg.execCmd('insertHTML', content);
  77. }
  78. }
  79. });
  80. }
  81. } catch (c) {}
  82. });
  83. }
  84. }
  85. }
  86. });
  87. })(jQuery);