summaryrefslogtreecommitdiffstats
path: root/browser/components/extensions/test/browser/browser_ext_tabs_discarded.js
blob: 48c57b5a05f476a1fe1b5982fb22f1799df698c0 (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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
/* global gBrowser SessionStore */
"use strict";

const triggeringPrincipal_base64 = E10SUtils.SERIALIZED_SYSTEMPRINCIPAL;

let lazyTabState = {
  entries: [
    {
      url: "http://example.com/",
      triggeringPrincipal_base64,
      title: "Example Domain",
    },
  ],
};

add_task(async function test_discarded() {
  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["tabs", "webNavigation"],
    },

    background() {
      browser.webNavigation.onCompleted.addListener(
        async details => {
          browser.test.log(`webNav onCompleted received for ${details.tabId}`);
          let updatedTab = await browser.tabs.get(details.tabId);
          browser.test.assertEq(
            false,
            updatedTab.discarded,
            "lazy to non-lazy update discard property"
          );
          browser.test.notifyPass("test-finished");
        },
        { url: [{ hostContains: "example.com" }] }
      );

      browser.tabs.onCreated.addListener(function (tab) {
        browser.test.assertEq(
          true,
          tab.discarded,
          "non-lazy tab onCreated discard property"
        );
        browser.tabs.update(tab.id, { active: true });
      });
    },
  });

  await extension.startup();

  let testTab = BrowserTestUtils.addTab(gBrowser, "about:blank", {
    createLazyBrowser: true,
  });
  SessionStore.setTabState(testTab, lazyTabState);

  await extension.awaitFinish("test-finished");
  await extension.unload();

  BrowserTestUtils.removeTab(testTab);
});

// Regression test for Bug 1819794.
add_task(async function test_create_discarded_with_cookieStoreId() {
  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["contextualIdentities", "cookies"],
    },
    async background() {
      const [{ cookieStoreId }] = await browser.contextualIdentities.query({});
      browser.test.assertEq(
        "firefox-container-1",
        cookieStoreId,
        "Got expected cookieStoreId"
      );
      await browser.tabs.create({
        url: `http://example.com/#${cookieStoreId}`,
        cookieStoreId,
        discarded: true,
      });
      await browser.tabs.create({
        url: `http://example.com/#no-container`,
        discarded: true,
      });
    },
    // Needed by ExtensionSettingsStore (as a side-effect of contextualIdentities permission).
    useAddonManager: "temporary",
  });

  const tabContainerPromise = BrowserTestUtils.waitForEvent(
    window,
    "TabOpen",
    false,
    evt => {
      return evt.target.getAttribute("usercontextid", "1");
    }
  ).then(evt => evt.target);
  const tabDefaultPromise = BrowserTestUtils.waitForEvent(
    window,
    "TabOpen",
    false,
    evt => {
      return !evt.target.hasAttribute("usercontextid");
    }
  ).then(evt => evt.target);

  await extension.startup();

  const tabContainer = await tabContainerPromise;
  ok(
    tabContainer.hasAttribute("pending"),
    "new container tab should be discarded"
  );
  const tabContainerState = SessionStore.getTabState(tabContainer);
  is(
    JSON.parse(tabContainerState).userContextId,
    1,
    `Expect a userContextId associated to the new discarded container tab: ${tabContainerState}`
  );

  const tabDefault = await tabDefaultPromise;
  ok(
    tabDefault.hasAttribute("pending"),
    "new non-container tab should be discarded"
  );
  const tabDefaultState = SessionStore.getTabState(tabDefault);
  is(
    JSON.parse(tabDefaultState).userContextId,
    0,
    `Expect userContextId 0 associated to the new discarded non-container tab: ${tabDefaultState}`
  );

  BrowserTestUtils.removeTab(tabContainer);
  BrowserTestUtils.removeTab(tabDefault);
  await extension.unload();
});

// If discard is called immediately after creating a new tab, the new tab may not have loaded,
// and the sessionstore for that tab is not ready for discarding.  The result was a corrupted
// sessionstore for the tab, which when the tab was activated, resulted in a tab with partial
// state.
add_task(async function test_create_then_discard() {
  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["tabs", "webNavigation"],
    },

    background: async function () {
      let createdTab;

      browser.tabs.onUpdated.addListener((tabId, updatedInfo) => {
        if (!updatedInfo.discarded) {
          return;
        }

        browser.webNavigation.onCompleted.addListener(
          async details => {
            browser.test.assertEq(
              createdTab.id,
              details.tabId,
              "created tab navigation is completed"
            );
            let activeTab = await browser.tabs.get(details.tabId);
            browser.test.assertEq(
              "http://example.com/",
              details.url,
              "created tab url is correct"
            );
            browser.test.assertEq(
              "http://example.com/",
              activeTab.url,
              "created tab url is correct"
            );
            browser.tabs.remove(details.tabId);
            browser.test.notifyPass("test-finished");
          },
          { url: [{ hostContains: "example.com" }] }
        );

        browser.tabs.update(tabId, { active: true });
      });

      createdTab = await browser.tabs.create({
        url: "http://example.com/",
        active: false,
      });
      browser.tabs.discard(createdTab.id);
    },
  });
  await extension.startup();
  await extension.awaitFinish("test-finished");
  await extension.unload();
});

add_task(async function test_create_discarded() {
  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["tabs", "webNavigation"],
    },

    background() {
      let tabOpts = {
        url: "http://example.com/",
        active: false,
        discarded: true,
        title: "discarded tab",
      };

      browser.webNavigation.onCompleted.addListener(
        async details => {
          let activeTab = await browser.tabs.get(details.tabId);
          browser.test.assertEq(
            tabOpts.url,
            activeTab.url,
            "restored tab url matches active tab url"
          );
          browser.test.assertEq(
            "mochitest index /",
            activeTab.title,
            "restored tab title is correct"
          );
          browser.tabs.remove(details.tabId);
          browser.test.notifyPass("test-finished");
        },
        { url: [{ hostContains: "example.com" }] }
      );

      browser.tabs.onCreated.addListener(tab => {
        browser.test.assertEq(
          tabOpts.active,
          tab.active,
          "lazy tab is not active"
        );
        browser.test.assertEq(
          tabOpts.discarded,
          tab.discarded,
          "lazy tab is discarded"
        );
        browser.test.assertEq(tabOpts.url, tab.url, "lazy tab url is correct");
        browser.test.assertEq(
          tabOpts.title,
          tab.title,
          "lazy tab title is correct"
        );
        browser.tabs.update(tab.id, { active: true });
      });

      browser.tabs.create(tabOpts);
    },
  });
  await extension.startup();
  await extension.awaitFinish("test-finished");
  await extension.unload();
});

add_task(async function test_discarded_private_tab_restored() {
  let extension = ExtensionTestUtils.loadExtension({
    incognitoOverride: "spanning",

    background() {
      let isDiscarding = false;
      browser.tabs.onUpdated.addListener(
        async function listener(tabId, changeInfo, tab) {
          const { active, discarded, incognito } = tab;
          if (!incognito || active || discarded || isDiscarding) {
            return;
          }
          // Remove the onUpdated listener to prevent intermittent failure
          // to be hit if the listener gets called again for unrelated
          // tabs.onUpdated events that may get fired after the test case got
          // the tab-discarded test message that was expecting.
          isDiscarding = true;
          browser.tabs.onUpdated.removeListener(listener);
          browser.test.log(
            `Test extension discarding ${tabId}: ${JSON.stringify(changeInfo)}`
          );
          await browser.tabs.discard(tabId);
          browser.test.sendMessage("tab-discarded");
        },
        { properties: ["status"] }
      );
    },
  });

  // Open a private browsing window.
  const privateWin = await BrowserTestUtils.openNewBrowserWindow({
    private: true,
  });

  await extension.startup();

  const newTab = await BrowserTestUtils.addTab(
    privateWin.gBrowser,
    "https://example.com/"
  );
  await extension.awaitMessage("tab-discarded");
  is(newTab.getAttribute("pending"), "true", "private tab should be discarded");

  const promiseTabLoaded = BrowserTestUtils.browserLoaded(newTab.linkedBrowser);

  info("Switching to the discarded background tab");
  await BrowserTestUtils.switchTab(privateWin.gBrowser, newTab);

  info("Wait for the restored tab to complete loading");
  await promiseTabLoaded;
  is(
    newTab.hasAttribute("pending"),
    false,
    "discarded private tab should have been restored"
  );

  is(
    newTab.linkedBrowser.currentURI.spec,
    "https://example.com/",
    "Got the expected url on the restored tab"
  );

  await extension.unload();
  await BrowserTestUtils.closeWindow(privateWin);
});

add_task(async function test_update_discarded() {
  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["tabs", "<all_urls>"],
    },

    background() {
      browser.test.onMessage.addListener(async msg => {
        let [tab] = await browser.tabs.query({ url: "http://example.com/" });
        if (msg == "update") {
          await browser.tabs.update(tab.id, { url: "https://example.com/" });
        } else {
          browser.test.fail(`Unexpected message received: ${msg}`);
        }
      });
      browser.test.sendMessage("ready");
    },
  });

  await extension.startup();
  await extension.awaitMessage("ready");

  let lazyTab = BrowserTestUtils.addTab(gBrowser, "http://example.com/", {
    createLazyBrowser: true,
    lazyTabTitle: "Example Domain",
  });

  let tabBrowserInsertedPromise = BrowserTestUtils.waitForEvent(
    lazyTab,
    "TabBrowserInserted"
  );

  SimpleTest.waitForExplicitFinish();
  let waitForConsole = new Promise(resolve => {
    SimpleTest.monitorConsole(resolve, [
      {
        message:
          /Lazy browser prematurely inserted via 'loadURI' property access:/,
        forbid: true,
      },
    ]);
  });

  extension.sendMessage("update");
  await tabBrowserInsertedPromise;

  await BrowserTestUtils.waitForBrowserStateChange(
    lazyTab.linkedBrowser,
    "https://example.com/",
    stateFlags => {
      return (
        stateFlags & Ci.nsIWebProgressListener.STATE_IS_WINDOW &&
        stateFlags & Ci.nsIWebProgressListener.STATE_STOP
      );
    }
  );

  await TestUtils.waitForTick();
  BrowserTestUtils.removeTab(lazyTab);

  await extension.unload();

  SimpleTest.endMonitorConsole();
  await waitForConsole;
});