postmessage.html 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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
  19. src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"
  20. integrity="sha384-xBuQ/xzmlsLoJpyjoggmTEz8OWUFM0/RC5BsqQBDX2v5cMvDHcMakNTNrHIW2I5f"
  21. crossorigin="anonymous"
  22. ></script>
  23. </head>
  24. <body>
  25. <script>
  26. 'use strict';
  27. var origin = /^https:\/\/example.org/,
  28. target = new RegExp('^(http(s)?:)?\\/\\/' + location.host + '\\/');
  29. $(window).on('message', function (e) {
  30. e = e.originalEvent;
  31. var s = e.data,
  32. xhr = $.ajaxSettings.xhr(),
  33. f;
  34. if (!origin.test(e.origin)) {
  35. throw new Error('Origin "' + e.origin + '" does not match ' + origin);
  36. }
  37. if (!target.test(e.data.url)) {
  38. throw new Error(
  39. 'Target "' + e.data.url + '" does not match ' + target
  40. );
  41. }
  42. $(xhr.upload).on('progress', function (ev) {
  43. ev = ev.originalEvent;
  44. e.source.postMessage(
  45. {
  46. id: s.id,
  47. type: ev.type,
  48. timeStamp: ev.timeStamp,
  49. lengthComputable: ev.lengthComputable,
  50. loaded: ev.loaded,
  51. total: ev.total
  52. },
  53. e.origin
  54. );
  55. });
  56. s.xhr = function () {
  57. return xhr;
  58. };
  59. if (!(s.data instanceof Blob)) {
  60. f = new FormData();
  61. $.each(s.data, function (i, v) {
  62. f.append(v.name, v.value);
  63. });
  64. s.data = f;
  65. }
  66. $.ajax(s).always(function (result, statusText, jqXHR) {
  67. if (!jqXHR.done) {
  68. jqXHR = result;
  69. result = null;
  70. }
  71. e.source.postMessage(
  72. {
  73. id: s.id,
  74. status: jqXHR.status,
  75. statusText: statusText,
  76. result: result,
  77. headers: jqXHR.getAllResponseHeaders()
  78. },
  79. e.origin
  80. );
  81. });
  82. });
  83. </script>
  84. </body>
  85. </html>