postmessage.html 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <!DOCTYPE HTML>
  2. <!--
  3. /*
  4. * jQuery File Upload Plugin postMessage API
  5. * https://github.com/blueimp/jQuery-File-Upload
  6. *
  7. * Copyright 2011, Sebastian Tschan
  8. * https://blueimp.net
  9. *
  10. * Licensed under the MIT license:
  11. * https://opensource.org/licenses/MIT
  12. */
  13. -->
  14. <html lang="en">
  15. <head>
  16. <meta charset="utf-8">
  17. <title>jQuery File Upload Plugin postMessage API</title>
  18. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
  19. </head>
  20. <body>
  21. <script>
  22. /*jslint unparam: true, regexp: true */
  23. /*global $, Blob, FormData, location */
  24. 'use strict';
  25. var origin = /^http:\/\/example.org/,
  26. target = new RegExp('^(http(s)?:)?\\/\\/' + location.host + '\\/');
  27. $(window).on('message', function (e) {
  28. e = e.originalEvent;
  29. var s = e.data,
  30. xhr = $.ajaxSettings.xhr(),
  31. f;
  32. if (!origin.test(e.origin)) {
  33. throw new Error('Origin "' + e.origin + '" does not match ' + origin);
  34. }
  35. if (!target.test(e.data.url)) {
  36. throw new Error('Target "' + e.data.url + '" does not match ' + target);
  37. }
  38. $(xhr.upload).on('progress', function (ev) {
  39. ev = ev.originalEvent;
  40. e.source.postMessage({
  41. id: s.id,
  42. type: ev.type,
  43. timeStamp: ev.timeStamp,
  44. lengthComputable: ev.lengthComputable,
  45. loaded: ev.loaded,
  46. total: ev.total
  47. }, e.origin);
  48. });
  49. s.xhr = function () {
  50. return xhr;
  51. };
  52. if (!(s.data instanceof Blob)) {
  53. f = new FormData();
  54. $.each(s.data, function (i, v) {
  55. f.append(v.name, v.value);
  56. });
  57. s.data = f;
  58. }
  59. $.ajax(s).always(function (result, statusText, jqXHR) {
  60. if (!jqXHR.done) {
  61. jqXHR = result;
  62. result = null;
  63. }
  64. e.source.postMessage({
  65. id: s.id,
  66. status: jqXHR.status,
  67. statusText: statusText,
  68. result: result,
  69. headers: jqXHR.getAllResponseHeaders()
  70. }, e.origin);
  71. });
  72. });
  73. </script>
  74. </body>
  75. </html>