summaryrefslogtreecommitdiffstats
path: root/browser/components/extensions/test/browser/browser_ext_urlbar.js
blob: 5a2c84e5e7242990d20229731bd3de66901e95bb (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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
"use strict";

ChromeUtils.defineESModuleGetters(this, {
  PlacesTestUtils: "resource://testing-common/PlacesTestUtils.sys.mjs",
  PlacesUtils: "resource://gre/modules/PlacesUtils.sys.mjs",
  UrlbarPrefs: "resource:///modules/UrlbarPrefs.sys.mjs",
  UrlbarProvidersManager: "resource:///modules/UrlbarProvidersManager.sys.mjs",
});

ChromeUtils.defineLazyGetter(this, "UrlbarTestUtils", () => {
  const { UrlbarTestUtils: module } = ChromeUtils.importESModule(
    "resource://testing-common/UrlbarTestUtils.sys.mjs"
  );
  module.init(this);
  return module;
});

async function loadTipExtension(options = {}) {
  let ext = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["urlbar"],
    },
    isPrivileged: true,
    background() {
      browser.test.onMessage.addListener(options => {
        browser.urlbar.onBehaviorRequested.addListener(query => {
          return "restricting";
        }, "test");
        browser.urlbar.onResultsRequested.addListener(query => {
          return [
            {
              type: "tip",
              source: "local",
              heuristic: true,
              payload: {
                text: "Test",
                buttonText: "OK",
                buttonUrl: options.buttonUrl,
                helpUrl: options.helpUrl,
              },
            },
          ];
        }, "test");
        browser.urlbar.onResultPicked.addListener((payload, details) => {
          browser.test.assertEq(payload.text, "Test", "payload.text");
          browser.test.assertEq(payload.buttonText, "OK", "payload.buttonText");
          browser.test.sendMessage("onResultPicked received", details);
        }, "test");
      });
    },
  });
  await ext.startup();
  ext.sendMessage(options);

  // Wait for the provider to be registered before continuing.  The provider
  // will be registered once the parent process receives the first addListener
  // call from the extension.  There's no better way to do this, unfortunately.
  // For example, if the extension sends a message to the test after it adds its
  // listeners and then we wait here for that message, there's no guarantee that
  // the addListener calls will have been received in the parent yet.
  await BrowserTestUtils.waitForCondition(
    () => UrlbarProvidersManager.getProvider("test"),
    "Waiting for provider to be registered"
  );

  Assert.ok(
    UrlbarProvidersManager.getProvider("test"),
    "Provider should have been registered"
  );
  return ext;
}

/**
 * Updates the Top Sites feed.
 *
 * @param {Function} condition
 *   A callback that returns true after Top Sites are successfully updated.
 * @param {boolean} searchShortcuts
 *   True if Top Sites search shortcuts should be enabled.
 */
async function updateTopSites(condition, searchShortcuts = false) {
  // Toggle the pref to clear the feed cache and force an update.
  await SpecialPowers.pushPrefEnv({
    set: [
      ["browser.newtabpage.activity-stream.feeds.system.topsites", false],
      ["browser.newtabpage.activity-stream.feeds.system.topsites", true],
      [
        "browser.newtabpage.activity-stream.improvesearch.topSiteSearchShortcuts",
        searchShortcuts,
      ],
    ],
  });

  // Wait for the feed to be updated.
  await TestUtils.waitForCondition(() => {
    let sites = AboutNewTab.getTopSites();
    return condition(sites);
  }, "Waiting for top sites to be updated");
}

add_setup(async function () {
  Services.prefs.setBoolPref("browser.urlbar.suggest.quickactions", false);
  registerCleanupFunction(async () => {
    Services.prefs.clearUserPref("browser.urlbar.suggest.quickactions");
  });
  // Set the notification timeout to a really high value to avoid intermittent
  // failures due to the mock extensions not responding in time.
  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.extension.timeout", 5000]],
  });
});

// Loads a tip extension without a main button URL and presses enter on the main
// button.
add_task(async function tip_onResultPicked_mainButton_noURL_enter() {
  let ext = await loadTipExtension();
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    waitForFocus,
    value: "test",
  });
  EventUtils.synthesizeKey("KEY_Enter");
  await ext.awaitMessage("onResultPicked received");
  await ext.unload();
});

// Loads a tip extension without a main button URL and clicks the main button.
add_task(async function tip_onResultPicked_mainButton_noURL_mouse() {
  let ext = await loadTipExtension();
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    waitForFocus,
    value: "test",
  });
  let mainButton = gURLBar.querySelector(".urlbarView-button-tip");
  Assert.ok(mainButton);
  EventUtils.synthesizeMouseAtCenter(mainButton, {});
  await ext.awaitMessage("onResultPicked received");
  await ext.unload();
});

// Loads a tip extension with a main button URL and presses enter on the main
// button.
add_task(async function tip_onResultPicked_mainButton_url_enter() {
  let ext = await loadTipExtension({ buttonUrl: "http://example.com/" });
  await BrowserTestUtils.withNewTab("about:blank", async () => {
    await UrlbarTestUtils.promiseAutocompleteResultPopup({
      window,
      waitForFocus,
      value: "test",
    });
    let loadedPromise = BrowserTestUtils.browserLoaded(
      gBrowser.selectedBrowser
    );
    ext.onMessage("onResultPicked received", () => {
      Assert.ok(false, "onResultPicked should not be called");
    });
    EventUtils.synthesizeKey("KEY_Enter");
    await loadedPromise;
    Assert.equal(gBrowser.currentURI.spec, "http://example.com/");
  });
  await ext.unload();
});

// Loads a tip extension with a main button URL and clicks the main button.
add_task(async function tip_onResultPicked_mainButton_url_mouse() {
  let ext = await loadTipExtension({ buttonUrl: "http://example.com/" });
  await BrowserTestUtils.withNewTab("about:blank", async () => {
    await UrlbarTestUtils.promiseAutocompleteResultPopup({
      window,
      waitForFocus,
      value: "test",
    });
    let mainButton = gURLBar.querySelector(".urlbarView-button-tip");
    Assert.ok(mainButton);
    let loadedPromise = BrowserTestUtils.browserLoaded(
      gBrowser.selectedBrowser
    );
    ext.onMessage("onResultPicked received", () => {
      Assert.ok(false, "onResultPicked should not be called");
    });
    EventUtils.synthesizeMouseAtCenter(mainButton, {});
    await loadedPromise;
    Assert.equal(gBrowser.currentURI.spec, "http://example.com/");
  });
  await ext.unload();
});

// Loads a tip extension with a help button URL and presses enter on the help
// button.
add_task(async function tip_onResultPicked_helpButton_url_enter() {
  let ext = await loadTipExtension({ helpUrl: "http://example.com/" });
  await BrowserTestUtils.withNewTab("about:blank", async () => {
    await UrlbarTestUtils.promiseAutocompleteResultPopup({
      window,
      waitForFocus,
      value: "test",
    });
    ext.onMessage("onResultPicked received", () => {
      Assert.ok(false, "onResultPicked should not be called");
    });
    let loadedPromise = BrowserTestUtils.browserLoaded(
      gBrowser.selectedBrowser
    );
    if (UrlbarPrefs.get("resultMenu")) {
      await UrlbarTestUtils.openResultMenuAndPressAccesskey(window, "h");
    } else {
      EventUtils.synthesizeKey("KEY_Tab");
      EventUtils.synthesizeKey("KEY_Enter");
    }
    info("Waiting for help URL to load");
    await loadedPromise;
    Assert.equal(gBrowser.currentURI.spec, "http://example.com/");
  });
  await ext.unload();
});

// Loads a tip extension with a help button URL and clicks the help button.
add_task(async function tip_onResultPicked_helpButton_url_mouse() {
  let ext = await loadTipExtension({ helpUrl: "http://example.com/" });
  await BrowserTestUtils.withNewTab("about:blank", async () => {
    await UrlbarTestUtils.promiseAutocompleteResultPopup({
      window,
      waitForFocus,
      value: "test",
    });
    ext.onMessage("onResultPicked received", () => {
      Assert.ok(false, "onResultPicked should not be called");
    });
    let loadedPromise = BrowserTestUtils.browserLoaded(
      gBrowser.selectedBrowser
    );
    if (UrlbarPrefs.get("resultMenu")) {
      await UrlbarTestUtils.openResultMenuAndPressAccesskey(window, "h", {
        openByMouse: true,
      });
    } else {
      let helpButton = gURLBar.querySelector(".urlbarView-button-help");
      Assert.ok(helpButton);
      EventUtils.synthesizeMouseAtCenter(helpButton, {});
    }
    info("Waiting for help URL to load");
    await loadedPromise;
    Assert.equal(gBrowser.currentURI.spec, "http://example.com/");
  });
  await ext.unload();
});

// Tests the search function with a non-empty string.
add_task(async function search() {
  gURLBar.blur();

  let ext = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["urlbar"],
    },
    isPrivileged: true,
    background: () => {
      browser.urlbar.search("test");
    },
  });
  await ext.startup();

  let context = await UrlbarTestUtils.promiseSearchComplete(window);
  Assert.equal(gURLBar.value, "test");
  Assert.equal(context.searchString, "test");
  Assert.ok(gURLBar.focused);
  Assert.equal(gURLBar.getAttribute("focused"), "true");

  await UrlbarTestUtils.promisePopupClose(window);
  await ext.unload();
});

// Tests the search function with an empty string.
add_task(async function searchEmpty() {
  gURLBar.blur();

  // Searching for an empty string shows the history view, but there may be no
  // history here since other tests may have cleared it or since this test is
  // running in isolation.  We want to make sure providers are called and their
  // results are shown, so add a provider that returns a tip.
  let ext = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["urlbar"],
    },
    isPrivileged: true,
    background() {
      browser.urlbar.onBehaviorRequested.addListener(query => {
        return "restricting";
      }, "test");
      browser.urlbar.onResultsRequested.addListener(query => {
        return [
          {
            type: "tip",
            source: "local",
            heuristic: true,
            payload: {
              text: "Test",
              buttonText: "OK",
            },
          },
        ];
      }, "test");
      browser.urlbar.search("");
    },
  });
  await ext.startup();

  await BrowserTestUtils.waitForCondition(
    () => UrlbarProvidersManager.getProvider("test"),
    "Waiting for provider to be registered"
  );

  let context = await UrlbarTestUtils.promiseSearchComplete(window);
  Assert.equal(gURLBar.value, "");
  Assert.equal(context.searchString, "");
  Assert.equal(context.results.length, 1);
  Assert.equal(context.results[0].type, UrlbarUtils.RESULT_TYPE.TIP);
  Assert.ok(gURLBar.focused);
  Assert.equal(gURLBar.getAttribute("focused"), "true");

  await UrlbarTestUtils.promisePopupClose(window);
  await ext.unload();
  await SpecialPowers.popPrefEnv();
});

// Tests the search function with `focus: false`.
add_task(async function searchFocusFalse() {
  await PlacesUtils.history.clear();
  await PlacesUtils.bookmarks.eraseEverything();
  await PlacesTestUtils.addVisits([
    "http://example.com/test1",
    "http://example.com/test2",
  ]);

  gURLBar.blur();

  let ext = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["urlbar"],
    },
    isPrivileged: true,
    background: () => {
      browser.urlbar.search("test", { focus: false });
    },
  });
  await ext.startup();

  let context = await UrlbarTestUtils.promiseSearchComplete(window);
  Assert.equal(gURLBar.value, "test");
  Assert.equal(context.searchString, "test");
  Assert.ok(!gURLBar.focused);
  Assert.ok(!gURLBar.hasAttribute("focused"));

  let resultCount = UrlbarTestUtils.getResultCount(window);
  Assert.equal(resultCount, 3);

  let result = await UrlbarTestUtils.getDetailsOfResultAt(window, 0);
  Assert.equal(result.type, UrlbarUtils.RESULT_TYPE.SEARCH);
  Assert.equal(result.title, "test");

  result = await UrlbarTestUtils.getDetailsOfResultAt(window, 1);
  Assert.equal(result.type, UrlbarUtils.RESULT_TYPE.URL);
  Assert.equal(result.url, "http://example.com/test2");

  result = await UrlbarTestUtils.getDetailsOfResultAt(window, 2);
  Assert.equal(result.type, UrlbarUtils.RESULT_TYPE.URL);
  Assert.equal(result.url, "http://example.com/test1");

  await UrlbarTestUtils.promisePopupClose(window);
  await ext.unload();
  await SpecialPowers.popPrefEnv();
});

// Tests the search function with `focus: false` and an empty string.
add_task(async function searchFocusFalseEmpty() {
  await PlacesUtils.history.clear();
  await PlacesUtils.bookmarks.eraseEverything();
  for (let i = 0; i < 5; i++) {
    await PlacesTestUtils.addVisits(["http://example.com/test1"]);
  }
  await updateTopSites(sites => sites.length == 1);
  gURLBar.blur();

  let ext = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["urlbar"],
    },
    isPrivileged: true,
    background: () => {
      browser.urlbar.search("", { focus: false });
    },
  });
  await ext.startup();

  let context = await UrlbarTestUtils.promiseSearchComplete(window);
  Assert.equal(gURLBar.value, "");
  Assert.equal(context.searchString, "");
  Assert.ok(!gURLBar.focused);
  Assert.ok(!gURLBar.hasAttribute("focused"));

  let resultCount = UrlbarTestUtils.getResultCount(window);
  Assert.equal(resultCount, 1);

  let result = await UrlbarTestUtils.getDetailsOfResultAt(window, 0);
  Assert.equal(result.type, UrlbarUtils.RESULT_TYPE.URL);
  Assert.equal(result.url, "http://example.com/test1");

  await UrlbarTestUtils.promisePopupClose(window);
  await ext.unload();
  await SpecialPowers.popPrefEnv();
});

// Tests the focus function with select = false.
add_task(async function focusSelectFalse() {
  gURLBar.blur();
  gURLBar.value = "test";
  Assert.ok(!gURLBar.focused);
  Assert.ok(!gURLBar.hasAttribute("focused"));

  let ext = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["urlbar"],
    },
    isPrivileged: true,
    background: () => {
      browser.urlbar.focus();
    },
  });
  await ext.startup();

  await TestUtils.waitForCondition(() => gURLBar.focused);
  Assert.ok(gURLBar.focused);
  Assert.ok(gURLBar.hasAttribute("focused"));
  Assert.equal(gURLBar.selectionStart, gURLBar.selectionEnd);

  await ext.unload();
});

// Tests the focus function with select = true.
add_task(async function focusSelectTrue() {
  gURLBar.blur();
  gURLBar.value = "test";
  Assert.ok(!gURLBar.focused);
  Assert.ok(!gURLBar.hasAttribute("focused"));

  let ext = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["urlbar"],
    },
    isPrivileged: true,
    background: () => {
      browser.urlbar.focus(true);
    },
  });
  await ext.startup();

  await TestUtils.waitForCondition(() => gURLBar.focused);
  Assert.ok(gURLBar.focused);
  Assert.ok(gURLBar.hasAttribute("focused"));
  Assert.equal(gURLBar.selectionStart, 0);
  Assert.equal(gURLBar.selectionEnd, "test".length);

  await ext.unload();
});

// Tests the closeView function.
add_task(async function closeView() {
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    waitForFocus,
    value: "test",
  });

  let ext = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["urlbar"],
    },
    isPrivileged: true,
    background: () => {
      browser.urlbar.closeView();
    },
  });
  await UrlbarTestUtils.promisePopupClose(window, () => ext.startup());
  await ext.unload();
});

// Tests the onEngagement events.
add_task(async function onEngagement() {
  gURLBar.blur();

  // Enable engagement telemetry.
  Services.prefs.setBoolPref("browser.urlbar.eventTelemetry.enabled", true);

  let ext = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["urlbar"],
    },
    isPrivileged: true,
    background() {
      browser.urlbar.onEngagement.addListener(state => {
        browser.test.sendMessage("onEngagement", state);
      }, "test");
      browser.urlbar.onBehaviorRequested.addListener(query => {
        return "restricting";
      }, "test");
      browser.urlbar.onResultsRequested.addListener(query => {
        return [
          {
            type: "tip",
            source: "local",
            heuristic: true,
            payload: {
              text: "Test",
              buttonText: "OK",
            },
          },
        ];
      }, "test");
      browser.urlbar.search("");
    },
  });
  await ext.startup();

  // Start an engagement.
  let messagePromise = ext.awaitMessage("onEngagement");
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    waitForFocus,
    value: "test",
    fireInputEvent: true,
  });
  let state = await messagePromise;
  Assert.equal(state, "start");

  // Abandon the engagement.
  messagePromise = ext.awaitMessage("onEngagement");
  gURLBar.blur();
  state = await messagePromise;
  Assert.equal(state, "abandonment");

  // Start an engagement.
  messagePromise = ext.awaitMessage("onEngagement");
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    waitForFocus,
    value: "test",
    fireInputEvent: true,
  });
  state = await messagePromise;
  Assert.equal(state, "start");

  // End the engagement by pressing enter on the extension's tip result.
  messagePromise = ext.awaitMessage("onEngagement");
  EventUtils.synthesizeKey("KEY_Enter");
  state = await messagePromise;
  Assert.equal(state, "engagement");

  // We'll open about:preferences next.  Since it won't open in a new tab if the
  // current tab is blank, open a new tab now.
  await BrowserTestUtils.withNewTab("about:blank", async () => {
    // Start an engagement.
    messagePromise = ext.awaitMessage("onEngagement");
    await UrlbarTestUtils.promiseAutocompleteResultPopup({
      window,
      waitForFocus,
      value: "test",
      fireInputEvent: true,
    });
    state = await messagePromise;
    Assert.equal(state, "start");

    // Press up and enter to pick the search settings button.
    messagePromise = ext.awaitMessage("onEngagement");
    EventUtils.synthesizeKey("KEY_ArrowUp");
    EventUtils.synthesizeKey("KEY_Enter");
    await BrowserTestUtils.browserLoaded(
      gBrowser.selectedBrowser,
      false,
      "about:preferences#search"
    );
    state = await messagePromise;
    Assert.equal(state, "discard");
  });

  // Start a final engagement to make sure the previous discard didn't mess
  // anything up.
  messagePromise = ext.awaitMessage("onEngagement");
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    waitForFocus,
    value: "test",
    fireInputEvent: true,
  });
  state = await messagePromise;
  Assert.equal(state, "start");

  // End the engagement by pressing enter on the extension's tip result.
  messagePromise = ext.awaitMessage("onEngagement");
  EventUtils.synthesizeKey("KEY_Enter");
  state = await messagePromise;
  Assert.equal(state, "engagement");

  await ext.unload();
  Services.prefs.clearUserPref("browser.urlbar.eventTelemetry.enabled");
});