summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/xpcshell/test_ext_storage_tab.js
blob: 4ff080887f8d26bb5f73b47a3ad2bad3466e2881 (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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"use strict";

const { ExtensionStorageIDB } = ChromeUtils.importESModule(
  "resource://gre/modules/ExtensionStorageIDB.sys.mjs"
);

async function test_multiple_pages() {
  let extension = ExtensionTestUtils.loadExtension({
    async background() {
      function awaitMessage(expectedMsg, api = "test") {
        return new Promise(resolve => {
          browser[api].onMessage.addListener(function listener(msg) {
            if (msg === expectedMsg) {
              browser[api].onMessage.removeListener(listener);
              resolve();
            }
          });
        });
      }

      let tabReady = awaitMessage("tab-ready", "runtime");

      try {
        let storage = browser.storage.local;

        browser.test.sendMessage(
          "load-page",
          browser.runtime.getURL("tab.html")
        );
        await awaitMessage("page-loaded");
        await tabReady;

        let result = await storage.get("key");
        browser.test.assertEq(undefined, result.key, "Key should be undefined");

        await browser.runtime.sendMessage("tab-set-key");

        result = await storage.get("key");
        browser.test.assertEq(
          JSON.stringify({ foo: { bar: "baz" } }),
          JSON.stringify(result.key),
          "Key should be set to the value from the tab"
        );

        browser.test.sendMessage("remove-page");
        await awaitMessage("page-removed");

        result = await storage.get("key");
        browser.test.assertEq(
          JSON.stringify({ foo: { bar: "baz" } }),
          JSON.stringify(result.key),
          "Key should still be set to the value from the tab"
        );

        browser.test.notifyPass("storage-multiple");
      } catch (e) {
        browser.test.fail(`Error: ${e} :: ${e.stack}`);
        browser.test.notifyFail("storage-multiple");
      }
    },

    files: {
      "tab.html": `<!DOCTYPE html>
        <html>
          <head>
            <meta charset="utf-8">
            <script src="tab.js"></script>
          </head>
        </html>`,

      "tab.js"() {
        browser.test.log("tab");
        browser.runtime.onMessage.addListener(msg => {
          if (msg == "tab-set-key") {
            return browser.storage.local.set({ key: { foo: { bar: "baz" } } });
          }
        });

        browser.runtime.sendMessage("tab-ready");
      },
    },

    manifest: {
      permissions: ["storage"],
    },
  });

  let contentPage;
  extension.onMessage("load-page", async url => {
    contentPage = await ExtensionTestUtils.loadContentPage(url, { extension });
    extension.sendMessage("page-loaded");
  });
  extension.onMessage("remove-page", async () => {
    await contentPage.close();
    extension.sendMessage("page-removed");
  });

  await extension.startup();
  await extension.awaitFinish("storage-multiple");
  await extension.unload();
}

add_task(async function test_storage_local_file_backend_from_tab() {
  return runWithPrefs(
    [[ExtensionStorageIDB.BACKEND_ENABLED_PREF, false]],
    test_multiple_pages
  );
});

add_task(async function test_storage_local_idb_backend_from_tab() {
  return runWithPrefs(
    [[ExtensionStorageIDB.BACKEND_ENABLED_PREF, true]],
    test_multiple_pages
  );
});

async function test_storage_local_call_from_destroying_context() {
  let extension = ExtensionTestUtils.loadExtension({
    async background() {
      let numberOfChanges = 0;
      browser.storage.onChanged.addListener((changes, areaName) => {
        if (areaName !== "local") {
          browser.test.fail(
            `Received unexpected storage changes for "${areaName}"`
          );
        }

        numberOfChanges++;
      });

      browser.test.onMessage.addListener(async ({ msg, values }) => {
        switch (msg) {
          case "storage-set": {
            await browser.storage.local.set(values);
            browser.test.sendMessage("storage-set:done");
            break;
          }
          case "storage-get": {
            const res = await browser.storage.local.get();
            browser.test.sendMessage("storage-get:done", res);
            break;
          }
          case "storage-changes": {
            browser.test.sendMessage("storage-changes-count", numberOfChanges);
            break;
          }
          default:
            browser.test.fail(`Received unexpected message: ${msg}`);
        }
      });

      browser.test.sendMessage(
        "ext-page-url",
        browser.runtime.getURL("tab.html")
      );
    },
    files: {
      "tab.html": `<!DOCTYPE html>
        <html>
          <head>
            <meta charset="utf-8">
            <script src="tab.js"></script>
          </head>
        </html>`,

      "tab.js"() {
        browser.test.log("Extension tab - calling storage.local API method");
        // Call the storage.local API from a tab that is going to be quickly closed.
        browser.storage.local.set({
          "test-key-from-destroying-context": "testvalue2",
        });
        // Navigate away from the extension page, so that the storage.local API call will be unable
        // to send the call to the caller context (because it has been destroyed in the meantime).
        window.location = "about:blank";
      },
    },
    manifest: {
      permissions: ["storage"],
    },
  });

  await extension.startup();
  const url = await extension.awaitMessage("ext-page-url");

  let contentPage = await ExtensionTestUtils.loadContentPage(url, {
    extension,
  });
  let expectedBackgroundPageData = {
    "test-key-from-background-page": "test-value",
  };
  let expectedTabData = { "test-key-from-destroying-context": "testvalue2" };

  info(
    "Call storage.local.set from the background page and wait it to be completed"
  );
  extension.sendMessage({
    msg: "storage-set",
    values: expectedBackgroundPageData,
  });
  await extension.awaitMessage("storage-set:done");

  info(
    "Call storage.local.get from the background page and wait it to be completed"
  );
  extension.sendMessage({ msg: "storage-get" });
  let res = await extension.awaitMessage("storage-get:done");

  Assert.deepEqual(
    res,
    {
      ...expectedBackgroundPageData,
      ...expectedTabData,
    },
    "Got the expected data set in the storage.local backend"
  );

  extension.sendMessage({ msg: "storage-changes" });
  equal(
    await extension.awaitMessage("storage-changes-count"),
    2,
    "Got the expected number of storage.onChanged event received"
  );

  contentPage.close();

  await extension.unload();
}

add_task(
  async function test_storage_local_file_backend_destroyed_context_promise() {
    return runWithPrefs(
      [[ExtensionStorageIDB.BACKEND_ENABLED_PREF, false]],
      test_storage_local_call_from_destroying_context
    );
  }
);

add_task(
  async function test_storage_local_idb_backend_destroyed_context_promise() {
    return runWithPrefs(
      [[ExtensionStorageIDB.BACKEND_ENABLED_PREF, true]],
      test_storage_local_call_from_destroying_context
    );
  }
);