summaryrefslogtreecommitdiffstats
path: root/browser/components/extensions/test/browser/browser_ext_tabs_hide.js
blob: 89c50db692815b07ac8af934e07321eb6550278d (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
"use strict";

ChromeUtils.defineESModuleGetters(this, {
  ExtensionControlledPopup:
    "resource:///modules/ExtensionControlledPopup.sys.mjs",
  SessionStore: "resource:///modules/sessionstore/SessionStore.sys.mjs",
  TabStateFlusher: "resource:///modules/sessionstore/TabStateFlusher.sys.mjs",
});

const triggeringPrincipal_base64 = E10SUtils.SERIALIZED_SYSTEMPRINCIPAL;

async function doorhangerTest(testFn) {
  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["tabs", "tabHide"],
      icons: {
        48: "addon-icon.png",
      },
    },
    background() {
      browser.test.onMessage.addListener(async (msg, data) => {
        let tabs = await browser.tabs.query(data);
        await browser.tabs[msg](tabs.map(t => t.id));
        browser.test.sendMessage("done");
      });
    },
    useAddonManager: "temporary",
  });

  await extension.startup();

  // Open some tabs so we can hide them.
  let firstTab = gBrowser.selectedTab;
  let tabs = [
    await BrowserTestUtils.openNewForegroundTab(
      gBrowser,
      "http://example.com/?one",
      true,
      true
    ),
    await BrowserTestUtils.openNewForegroundTab(
      gBrowser,
      "http://example.com/?two",
      true,
      true
    ),
  ];
  gBrowser.selectedTab = firstTab;

  await testFn(extension);

  BrowserTestUtils.removeTab(tabs[0]);
  BrowserTestUtils.removeTab(tabs[1]);

  await extension.unload();
}

add_task(function test_doorhanger_keep() {
  return doorhangerTest(async function (extension) {
    is(gBrowser.visibleTabs.length, 3, "There are 3 visible tabs");

    // Hide the first tab, expect the doorhanger.
    let panel = ExtensionControlledPopup._getAndMaybeCreatePanel(document);
    let popupShown = promisePopupShown(panel);
    extension.sendMessage("hide", { url: "*://*/?one" });
    await extension.awaitMessage("done");
    await popupShown;

    is(gBrowser.visibleTabs.length, 2, "There are 2 visible tabs now");
    is(
      panel.anchorNode.closest("toolbarbutton").id,
      "alltabs-button",
      "The doorhanger is anchored to the all tabs button"
    );

    // Click the Keep Tabs Hidden button.
    let popupnotification = document.getElementById(
      "extension-tab-hide-notification"
    );
    let popupHidden = promisePopupHidden(panel);
    popupnotification.button.click();
    await popupHidden;

    // Hide another tab and ensure the popup didn't open.
    extension.sendMessage("hide", { url: "*://*/?two" });
    await extension.awaitMessage("done");
    is(panel.state, "closed", "The popup is still closed");
    is(gBrowser.visibleTabs.length, 1, "There's one visible tab now");

    extension.sendMessage("show", {});
    await extension.awaitMessage("done");
  });
});

add_task(function test_doorhanger_disable() {
  return doorhangerTest(async function (extension) {
    is(gBrowser.visibleTabs.length, 3, "There are 3 visible tabs");

    // Hide the first tab, expect the doorhanger.
    let panel = ExtensionControlledPopup._getAndMaybeCreatePanel(document);
    let popupShown = promisePopupShown(panel);
    extension.sendMessage("hide", { url: "*://*/?one" });
    await extension.awaitMessage("done");
    await popupShown;

    is(gBrowser.visibleTabs.length, 2, "There are 2 visible tabs now");
    is(
      panel.anchorNode.closest("toolbarbutton").id,
      "alltabs-button",
      "The doorhanger is anchored to the all tabs button"
    );

    // verify the contents of the description.
    let popupnotification = document.getElementById(
      "extension-tab-hide-notification"
    );
    let description = popupnotification.querySelector(
      "#extension-tab-hide-notification-description"
    );
    let addon = await AddonManager.getAddonByID(extension.id);
    ok(
      description.textContent.includes(addon.name),
      "The extension name is in the description"
    );
    let images = Array.from(description.querySelectorAll("image"));
    is(images.length, 2, "There are two images");
    ok(
      images.some(img => img.src.includes("addon-icon.png")),
      "There's an icon for the extension"
    );
    ok(
      images.some(img =>
        getComputedStyle(img).backgroundImage.includes("arrow-down.svg")
      ),
      "There's an icon for the all tabs menu"
    );

    // Click the Disable Extension button.
    let popupHidden = promisePopupHidden(panel);
    popupnotification.secondaryButton.click();
    await popupHidden;
    await new Promise(executeSoon);

    is(gBrowser.visibleTabs.length, 3, "There are 3 visible tabs again");
    is(addon.userDisabled, true, "The extension is now disabled");
  });
});

add_task(async function test_tabs_showhide() {
  async function background() {
    browser.test.onMessage.addListener(async (msg, data) => {
      switch (msg) {
        case "hideall": {
          let tabs = await browser.tabs.query({ hidden: false });
          browser.test.assertEq(tabs.length, 5, "got 5 tabs");
          let ids = tabs.map(tab => tab.id);
          browser.test.log(`working with ids ${JSON.stringify(ids)}`);

          let hidden = await browser.tabs.hide(ids);
          browser.test.assertEq(hidden.length, 3, "hid 3 tabs");
          tabs = await browser.tabs.query({ hidden: true });
          ids = tabs.map(tab => tab.id);
          browser.test.assertEq(
            JSON.stringify(hidden.sort()),
            JSON.stringify(ids.sort()),
            "hidden tabIds match"
          );

          browser.test.sendMessage("hidden", { hidden });
          break;
        }
        case "showall": {
          let tabs = await browser.tabs.query({ hidden: true });
          for (let tab of tabs) {
            browser.test.assertTrue(tab.hidden, "tab is hidden");
          }
          let ids = tabs.map(tab => tab.id);
          browser.tabs.show(ids);
          browser.test.sendMessage("shown");
          break;
        }
      }
    });
  }

  let extdata = {
    manifest: { permissions: ["tabs", "tabHide"] },
    background,
    useAddonManager: "temporary", // So the doorhanger can find the addon.
  };
  let extension = ExtensionTestUtils.loadExtension(extdata);
  await extension.startup();

  let sessData = {
    windows: [
      {
        tabs: [
          { entries: [{ url: "about:blank", triggeringPrincipal_base64 }] },
          {
            entries: [
              { url: "https://example.com/", triggeringPrincipal_base64 },
            ],
          },
          {
            entries: [
              { url: "https://mochi.test:8888/", triggeringPrincipal_base64 },
            ],
          },
        ],
      },
      {
        tabs: [
          { entries: [{ url: "about:blank", triggeringPrincipal_base64 }] },
          {
            entries: [
              { url: "http://test1.example.com/", triggeringPrincipal_base64 },
            ],
          },
        ],
      },
    ],
  };

  // Set up a test session with 2 windows and 5 tabs.
  let oldState = SessionStore.getBrowserState();
  let restored = TestUtils.topicObserved("sessionstore-browser-state-restored");
  SessionStore.setBrowserState(JSON.stringify(sessData));
  await restored;

  if (!Services.prefs.getBoolPref("browser.tabs.tabmanager.enabled")) {
    for (let win of BrowserWindowIterator()) {
      let allTabsButton = win.document.getElementById("alltabs-button");
      is(
        getComputedStyle(allTabsButton).display,
        "none",
        "The all tabs button is hidden"
      );
    }
  }

  // Attempt to hide all the tabs, however the active tab in each window cannot
  // be hidden, so the result will be 3 hidden tabs.
  extension.sendMessage("hideall");
  await extension.awaitMessage("hidden");

  // We have 2 windows in this session.  Otherwin is the non-current window.
  // In each window, the first tab will be the selected tab and should not be
  // hidden.  The rest of the tabs should be hidden at this point.  Hidden
  // status was already validated inside the extension, this double checks
  // from chrome code.
  let otherwin;
  for (let win of BrowserWindowIterator()) {
    if (win != window) {
      otherwin = win;
    }
    let tabs = Array.from(win.gBrowser.tabs);
    ok(!tabs[0].hidden, "first tab not hidden");
    for (let i = 1; i < tabs.length; i++) {
      ok(tabs[i].hidden, "tab hidden value is correct");
      let id = SessionStore.getCustomTabValue(tabs[i], "hiddenBy");
      is(id, extension.id, "tab hiddenBy value is correct");
      await TabStateFlusher.flush(tabs[i].linkedBrowser);
    }

    let allTabsButton = win.document.getElementById("alltabs-button");
    isnot(
      getComputedStyle(allTabsButton).display,
      "none",
      "The all tabs button is visible"
    );
  }

  // Close the other window then restore it to test that the tabs are
  // restored with proper hidden state, and the correct extension id.
  await BrowserTestUtils.closeWindow(otherwin);

  otherwin = SessionStore.undoCloseWindow(0);
  await BrowserTestUtils.waitForEvent(otherwin, "load");
  let tabs = Array.from(otherwin.gBrowser.tabs);
  ok(!tabs[0].hidden, "first tab not hidden");
  for (let i = 1; i < tabs.length; i++) {
    ok(tabs[i].hidden, "tab hidden value is correct");
    let id = SessionStore.getCustomTabValue(tabs[i], "hiddenBy");
    is(id, extension.id, "tab hiddenBy value is correct");
  }

  // Test closing the last visible tab, the next tab which is hidden should become
  // the selectedTab and will be visible.
  ok(!otherwin.gBrowser.selectedTab.hidden, "selected tab is not hidden");
  BrowserTestUtils.removeTab(otherwin.gBrowser.selectedTab);
  ok(!otherwin.gBrowser.selectedTab.hidden, "tab was unhidden");

  // Showall will unhide any remaining hidden tabs.
  extension.sendMessage("showall");
  await extension.awaitMessage("shown");

  // Check from chrome code that all tabs are visible again.
  for (let win of BrowserWindowIterator()) {
    let tabs = Array.from(win.gBrowser.tabs);
    for (let i = 0; i < tabs.length; i++) {
      ok(!tabs[i].hidden, "tab hidden value is correct");
    }
  }

  // Close second window.
  await BrowserTestUtils.closeWindow(otherwin);

  await extension.unload();

  // Restore pre-test state.
  restored = TestUtils.topicObserved("sessionstore-browser-state-restored");
  SessionStore.setBrowserState(oldState);
  await restored;
});

// Test our shutdown handling.  Currently this means any hidden tabs will be
// shown when a tabHide extension is shutdown.  We additionally test the
// tabs.onUpdated listener gets called with hidden state changes.
add_task(async function test_tabs_shutdown() {
  let tabs = [
    await BrowserTestUtils.openNewForegroundTab(
      gBrowser,
      "http://example.com/",
      true,
      true
    ),
    await BrowserTestUtils.openNewForegroundTab(
      gBrowser,
      "http://mochi.test:8888/",
      true,
      true
    ),
  ];

  async function background() {
    let tabs = await browser.tabs.query({ url: "http://example.com/" });
    let testTab = tabs[0];

    browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
      if ("hidden" in changeInfo) {
        browser.test.assertEq(tabId, testTab.id, "correct tab was hidden");
        browser.test.assertTrue(changeInfo.hidden, "tab is hidden");
        browser.test.assertEq(tab.url, testTab.url, "tab has correct URL");
        browser.test.sendMessage("changeInfo");
      }
    });

    let hidden = await browser.tabs.hide(testTab.id);
    browser.test.assertEq(hidden[0], testTab.id, "tab was hidden");
    tabs = await browser.tabs.query({ hidden: true });
    browser.test.assertEq(tabs[0].id, testTab.id, "tab was hidden");
    browser.test.sendMessage("ready");
  }

  let extdata = {
    manifest: { permissions: ["tabs", "tabHide"] },
    useAddonManager: "temporary", // For testing onShutdown.
    background,
  };
  let extension = ExtensionTestUtils.loadExtension(extdata);
  await extension.startup();

  // test onUpdated
  await Promise.all([
    extension.awaitMessage("ready"),
    extension.awaitMessage("changeInfo"),
  ]);
  Assert.ok(tabs[0].hidden, "Tab is hidden by extension");

  await extension.unload();

  Assert.ok(!tabs[0].hidden, "Tab is not hidden after unloading extension");
  BrowserTestUtils.removeTab(tabs[0]);
  BrowserTestUtils.removeTab(tabs[1]);
});