summaryrefslogtreecommitdiffstats
path: root/browser/components/originattributes/test/browser/worker_blobify.js
blob: 20a1d8f2a07b225b85d0ce19c11ebae31f4b1ff8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Wait for a string to be posted to this worker.
// Create a blob containing this string, and then
// post back a blob URL pointing to the blob.

/* eslint-env worker */

var postStringInBlob = function (blobObject) {
  var fileReader = new FileReaderSync();
  var result = fileReader.readAsText(blobObject);
  postMessage(result);
};

self.addEventListener("message", e => {
  if (e.data.what === "blobify") {
    try {
      let blobURL = URL.createObjectURL(new Blob([e.data.message]));
      postMessage({ blobURL });
    } catch (ex) {
      postMessage({ error: ex.message });
    }
    return;
  }

  if (e.data.what === "deblobify") {
    if ("error" in e.data.message) {
      postMessage(e.data.message);
      return;
    }
    let blobURL = e.data.message.blobURL,
      xhr = new XMLHttpRequest();
    try {
      xhr.open("GET", blobURL, true);
      xhr.onload = function () {
        postStringInBlob(xhr.response);
      };
      xhr.onerror = function () {
        postMessage({ error: "xhr error" });
      };
      xhr.responseType = "blob";
      xhr.send();
    } catch (ex) {
      postMessage({ error: ex.message });
    }

    return;
  }

  postMessage("Invalid operation!");
});