jquery.iframe-transport.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. /*
  2. * jQuery Iframe Transport Plugin
  3. * https://github.com/blueimp/jQuery-File-Upload
  4. *
  5. * Copyright 2011, Sebastian Tschan
  6. * https://blueimp.net
  7. *
  8. * Licensed under the MIT license:
  9. * https://opensource.org/licenses/MIT
  10. */
  11. /* global define, require, window, document, JSON */
  12. ;(function (factory) {
  13. 'use strict';
  14. if (typeof define === 'function' && define.amd) {
  15. // Register as an anonymous AMD module:
  16. define(['jquery'], factory);
  17. } else if (typeof exports === 'object') {
  18. // Node/CommonJS:
  19. factory(require('jquery'));
  20. } else {
  21. // Browser globals:
  22. factory(window.jQuery);
  23. }
  24. }(function ($) {
  25. 'use strict';
  26. // Helper variable to create unique names for the transport iframes:
  27. var counter = 0,
  28. jsonAPI = $,
  29. jsonParse = 'parseJSON';
  30. if ('JSON' in window && 'parse' in JSON) {
  31. jsonAPI = JSON;
  32. jsonParse = 'parse';
  33. }
  34. // The iframe transport accepts four additional options:
  35. // options.fileInput: a jQuery collection of file input fields
  36. // options.paramName: the parameter name for the file form data,
  37. // overrides the name property of the file input field(s),
  38. // can be a string or an array of strings.
  39. // options.formData: an array of objects with name and value properties,
  40. // equivalent to the return data of .serializeArray(), e.g.:
  41. // [{name: 'a', value: 1}, {name: 'b', value: 2}]
  42. // options.initialIframeSrc: the URL of the initial iframe src,
  43. // by default set to "javascript:false;"
  44. $.ajaxTransport('iframe', function (options) {
  45. if (options.async) {
  46. // javascript:false as initial iframe src
  47. // prevents warning popups on HTTPS in IE6:
  48. /*jshint scripturl: true */
  49. var initialIframeSrc = options.initialIframeSrc || 'javascript:false;',
  50. /*jshint scripturl: false */
  51. form,
  52. iframe,
  53. addParamChar;
  54. return {
  55. send: function (_, completeCallback) {
  56. form = $('<form style="display:none;"></form>');
  57. form.attr('accept-charset', options.formAcceptCharset);
  58. addParamChar = /\?/.test(options.url) ? '&' : '?';
  59. // XDomainRequest only supports GET and POST:
  60. if (options.type === 'DELETE') {
  61. options.url = options.url + addParamChar + '_method=DELETE';
  62. options.type = 'POST';
  63. } else if (options.type === 'PUT') {
  64. options.url = options.url + addParamChar + '_method=PUT';
  65. options.type = 'POST';
  66. } else if (options.type === 'PATCH') {
  67. options.url = options.url + addParamChar + '_method=PATCH';
  68. options.type = 'POST';
  69. }
  70. // IE versions below IE8 cannot set the name property of
  71. // elements that have already been added to the DOM,
  72. // so we set the name along with the iframe HTML markup:
  73. counter += 1;
  74. iframe = $(
  75. '<iframe src="' + initialIframeSrc +
  76. '" name="iframe-transport-' + counter + '"></iframe>'
  77. ).bind('load', function () {
  78. var fileInputClones,
  79. paramNames = $.isArray(options.paramName) ?
  80. options.paramName : [options.paramName];
  81. iframe
  82. .unbind('load')
  83. .bind('load', function () {
  84. var response;
  85. // Wrap in a try/catch block to catch exceptions thrown
  86. // when trying to access cross-domain iframe contents:
  87. try {
  88. response = iframe.contents();
  89. // Google Chrome and Firefox do not throw an
  90. // exception when calling iframe.contents() on
  91. // cross-domain requests, so we unify the response:
  92. if (!response.length || !response[0].firstChild) {
  93. throw new Error();
  94. }
  95. } catch (e) {
  96. response = undefined;
  97. }
  98. // The complete callback returns the
  99. // iframe content document as response object:
  100. completeCallback(
  101. 200,
  102. 'success',
  103. {'iframe': response}
  104. );
  105. // Fix for IE endless progress bar activity bug
  106. // (happens on form submits to iframe targets):
  107. $('<iframe src="' + initialIframeSrc + '"></iframe>')
  108. .appendTo(form);
  109. window.setTimeout(function () {
  110. // Removing the form in a setTimeout call
  111. // allows Chrome's developer tools to display
  112. // the response result
  113. form.remove();
  114. }, 0);
  115. });
  116. form
  117. .prop('target', iframe.prop('name'))
  118. .prop('action', options.url)
  119. .prop('method', options.type);
  120. if (options.formData) {
  121. $.each(options.formData, function (index, field) {
  122. $('<input type="hidden"/>')
  123. .prop('name', field.name)
  124. .val(field.value)
  125. .appendTo(form);
  126. });
  127. }
  128. if (options.fileInput && options.fileInput.length &&
  129. options.type === 'POST') {
  130. fileInputClones = options.fileInput.clone();
  131. // Insert a clone for each file input field:
  132. options.fileInput.after(function (index) {
  133. return fileInputClones[index];
  134. });
  135. if (options.paramName) {
  136. options.fileInput.each(function (index) {
  137. $(this).prop(
  138. 'name',
  139. paramNames[index] || options.paramName
  140. );
  141. });
  142. }
  143. // Appending the file input fields to the hidden form
  144. // removes them from their original location:
  145. form
  146. .append(options.fileInput)
  147. .prop('enctype', 'multipart/form-data')
  148. // enctype must be set as encoding for IE:
  149. .prop('encoding', 'multipart/form-data');
  150. // Remove the HTML5 form attribute from the input(s):
  151. options.fileInput.removeAttr('form');
  152. }
  153. form.submit();
  154. // Insert the file input fields at their original location
  155. // by replacing the clones with the originals:
  156. if (fileInputClones && fileInputClones.length) {
  157. options.fileInput.each(function (index, input) {
  158. var clone = $(fileInputClones[index]);
  159. // Restore the original name and form properties:
  160. $(input)
  161. .prop('name', clone.prop('name'))
  162. .attr('form', clone.attr('form'));
  163. clone.replaceWith(input);
  164. });
  165. }
  166. });
  167. form.append(iframe).appendTo(document.body);
  168. },
  169. abort: function () {
  170. if (iframe) {
  171. // javascript:false as iframe src aborts the request
  172. // and prevents warning popups on HTTPS in IE6.
  173. // concat is used to avoid the "Script URL" JSLint error:
  174. iframe
  175. .unbind('load')
  176. .prop('src', initialIframeSrc);
  177. }
  178. if (form) {
  179. form.remove();
  180. }
  181. }
  182. };
  183. }
  184. });
  185. // The iframe transport returns the iframe content document as response.
  186. // The following adds converters from iframe to text, json, html, xml
  187. // and script.
  188. // Please note that the Content-Type for JSON responses has to be text/plain
  189. // or text/html, if the browser doesn't include application/json in the
  190. // Accept header, else IE will show a download dialog.
  191. // The Content-Type for XML responses on the other hand has to be always
  192. // application/xml or text/xml, so IE properly parses the XML response.
  193. // See also
  194. // https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#content-type-negotiation
  195. $.ajaxSetup({
  196. converters: {
  197. 'iframe text': function (iframe) {
  198. return iframe && $(iframe[0].body).text();
  199. },
  200. 'iframe json': function (iframe) {
  201. return iframe && jsonAPI[jsonParse]($(iframe[0].body).text());
  202. },
  203. 'iframe html': function (iframe) {
  204. return iframe && $(iframe[0].body).html();
  205. },
  206. 'iframe xml': function (iframe) {
  207. var xmlDoc = iframe && iframe[0];
  208. return xmlDoc && $.isXMLDoc(xmlDoc) ? xmlDoc :
  209. $.parseXML((xmlDoc.XMLDocument && xmlDoc.XMLDocument.xml) ||
  210. $(xmlDoc.body).html());
  211. },
  212. 'iframe script': function (iframe) {
  213. return iframe && $.globalEval($(iframe[0].body).text());
  214. }
  215. }
  216. });
  217. }));