summaryrefslogtreecommitdiffstats
path: root/dom/file/tests/test_ipc_messagemanager_blob.js
blob: dacdc9e7bb02c861966d87a00707b6d303e443b2 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
"use strict";

const { XPCShellContentUtils } = ChromeUtils.importESModule(
  "resource://testing-common/XPCShellContentUtils.sys.mjs"
);

XPCShellContentUtils.init(this);

function childFrameScript() {
  addMessageListener("test:ipcClonedMessage", function (message) {
    if (!Blob.isInstance(message.json)) {
      sendAsyncMessage(message.name, message.json);
      return;
    }

    let reader = new FileReader();
    reader.addEventListener("load", function () {
      let response =
        reader.result == "this is a great success!" ? message.json : "error";
      sendAsyncMessage(message.name, response);
    });
    reader.readAsText(message.json);
  });
}

add_task(async function test() {
  let page = await XPCShellContentUtils.loadContentPage("about:blank", {
    remote: true,
  });

  page.loadFrameScript(childFrameScript);

  const blobString = "this is a great success!";

  const messages = [
    "hi!",
    "",
    2,
    -0.04,
    34329873249872400000000000000,
    true,
    false,
    null,
    0,

    // Make sure this one is always last.
    new Blob(["this ", "is ", "a ", "great ", "success!"], {
      type: "text/plain",
    }),
  ];
  let receivedMessageIndex = 0;

  let mm = page.browser.messageManager;
  let done = new Promise(resolve => {
    mm.addMessageListener("test:ipcClonedMessage", async message => {
      let data = message.json;

      if (Blob.isInstance(data)) {
        equal(receivedMessageIndex, messages.length - 1, "Blob is last");
        equal(
          data.size,
          messages[receivedMessageIndex].size,
          "Correct blob size"
        );
        equal(
          data.type,
          messages[receivedMessageIndex].type,
          "Correct blob type"
        );

        let reader1 = new FileReader();
        reader1.readAsText(data);

        let reader2 = new FileReader();
        reader2.readAsText(messages[receivedMessageIndex]);

        await Promise.all([
          new Promise(res => (reader1.onload = res)),
          new Promise(res => (reader2.onload = res)),
        ]);

        equal(reader1.result, blobString, "Result 1");
        equal(reader2.result, blobString, "Result 2");

        resolve();
      } else {
        equal(
          data,
          messages[receivedMessageIndex++],
          "Got correct round-tripped response"
        );
      }
    });
  });

  for (let message of messages) {
    mm.sendAsyncMessage("test:ipcClonedMessage", message);
  }

  await done;
  await page.close();
});