encodePacket.browser.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { PACKET_TYPES } from "./commons.js";
  2. const withNativeBlob = typeof Blob === "function" ||
  3. (typeof Blob !== "undefined" &&
  4. Object.prototype.toString.call(Blob) === "[object BlobConstructor]");
  5. const withNativeArrayBuffer = typeof ArrayBuffer === "function";
  6. // ArrayBuffer.isView method is not defined in IE10
  7. const isView = obj => {
  8. return typeof ArrayBuffer.isView === "function"
  9. ? ArrayBuffer.isView(obj)
  10. : obj && obj.buffer instanceof ArrayBuffer;
  11. };
  12. const encodePacket = ({ type, data }, supportsBinary, callback) => {
  13. if (withNativeBlob && data instanceof Blob) {
  14. if (supportsBinary) {
  15. return callback(data);
  16. }
  17. else {
  18. return encodeBlobAsBase64(data, callback);
  19. }
  20. }
  21. else if (withNativeArrayBuffer &&
  22. (data instanceof ArrayBuffer || isView(data))) {
  23. if (supportsBinary) {
  24. return callback(data);
  25. }
  26. else {
  27. return encodeBlobAsBase64(new Blob([data]), callback);
  28. }
  29. }
  30. // plain string
  31. return callback(PACKET_TYPES[type] + (data || ""));
  32. };
  33. const encodeBlobAsBase64 = (data, callback) => {
  34. const fileReader = new FileReader();
  35. fileReader.onload = function () {
  36. const content = fileReader.result.split(",")[1];
  37. callback("b" + content);
  38. };
  39. return fileReader.readAsDataURL(data);
  40. };
  41. export default encodePacket;