summaryrefslogtreecommitdiffstats
path: root/dom/tests/browser/browser_hasbeforeunload.js
blob: de86a1ea7a1cc8d479eed853d54aef1e9205621a (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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
"use strict";

const PAGE_URL =
  "http://example.com/browser/dom/tests/browser/beforeunload_test_page.html";

/**
 * Adds 1 or more inert beforeunload event listeners in this browser.
 * By default, will target the top-level content window, but callers
 * can specify the index of a subframe to target. See prepareSubframes
 * for an idea of how the subframes are structured.
 *
 * @param {<xul:browser>} browser
 *        The browser to add the beforeunload event listener in.
 * @param {int} howMany
 *        How many beforeunload event listeners to add. Note that these
 *        beforeunload event listeners are inert and will not actually
 *        prevent the host window from navigating.
 * @param {optional int} frameDepth
 *        The depth of the frame to add the event listener to. Defaults
 *        to 0, which is the top-level content window.
 * @return {Promise}
 */
function addBeforeUnloadListeners(browser, howMany = 1, frameDepth = 0) {
  return controlFrameAt(browser, frameDepth, {
    name: "AddBeforeUnload",
    howMany,
  });
}

/**
 * Adds 1 or more inert beforeunload event listeners in this browser on
 * a particular subframe. By default, this will target the first subframe
 * under the top-level content window, but callers can specify the index
 * of a subframe to target. See prepareSubframes for an idea of how the
 * subframes are structured.
 *
 * Note that this adds the beforeunload event listener on the "outer" window,
 * by doing:
 *
 * iframe.addEventListener("beforeunload", ...);
 *
 * @param {<xul:browser>} browser
 *        The browser to add the beforeunload event listener in.
 * @param {int} howMany
 *        How many beforeunload event listeners to add. Note that these
 *        beforeunload event listeners are inert and will not actually
 *        prevent the host window from navigating.
 * @param {optional int} frameDepth
 *        The depth of the frame to add the event listener to. Defaults
 *        to 1, which is the first subframe inside the top-level content
 *        window. Setting this to 0 will throw.
 * @return {Promise}
 */
function addOuterBeforeUnloadListeners(browser, howMany = 1, frameDepth = 1) {
  if (frameDepth == 0) {
    throw new Error(
      "When adding a beforeunload listener on an outer " +
        "window, the frame you're targeting needs to be at " +
        "depth > 0."
    );
  }

  return controlFrameAt(browser, frameDepth, {
    name: "AddOuterBeforeUnload",
    howMany,
  });
}

/**
 * Removes 1 or more inert beforeunload event listeners in this browser.
 * This assumes that addBeforeUnloadListeners has been called previously
 * for the target frame.
 *
 * By default, will target the top-level content window, but callers
 * can specify the index of a subframe to target. See prepareSubframes
 * for an idea of how the subframes are structured.
 *
 * @param {<xul:browser>} browser
 *        The browser to remove the beforeunload event listener from.
 * @param {int} howMany
 *        How many beforeunload event listeners to remove.
 * @param {optional int} frameDepth
 *        The depth of the frame to remove the event listener from. Defaults
 *        to 0, which is the top-level content window.
 * @return {Promise}
 */
function removeBeforeUnloadListeners(browser, howMany = 1, frameDepth = 0) {
  return controlFrameAt(browser, frameDepth, {
    name: "RemoveBeforeUnload",
    howMany,
  });
}

/**
 * Removes 1 or more inert beforeunload event listeners in this browser on
 * a particular subframe. By default, this will target the first subframe
 * under the top-level content window, but callers can specify the index
 * of a subframe to target. See prepareSubframes for an idea of how the
 * subframes are structured.
 *
 * Note that this removes the beforeunload event listener on the "outer" window,
 * by doing:
 *
 * iframe.removeEventListener("beforeunload", ...);
 *
 * @param {<xul:browser>} browser
 *        The browser to remove the beforeunload event listener from.
 * @param {int} howMany
 *        How many beforeunload event listeners to remove.
 * @param {optional int} frameDepth
 *        The depth of the frame to remove the event listener from. Defaults
 *        to 1, which is the first subframe inside the top-level content
 *        window. Setting this to 0 will throw.
 * @return {Promise}
 */
function removeOuterBeforeUnloadListeners(
  browser,
  howMany = 1,
  frameDepth = 1
) {
  if (frameDepth == 0) {
    throw new Error(
      "When removing a beforeunload listener from an outer " +
        "window, the frame you're targeting needs to be at " +
        "depth > 0."
    );
  }

  return controlFrameAt(browser, frameDepth, {
    name: "RemoveOuterBeforeUnload",
    howMany,
  });
}

/**
 * Navigates a content window to a particular URL and waits for it to
 * finish loading that URL.
 *
 * By default, will target the top-level content window, but callers
 * can specify the index of a subframe to target. See prepareSubframes
 * for an idea of how the subframes are structured.
 *
 * @param {<xul:browser>} browser
 *        The browser that will have the navigation occur within it.
 * @param {string} url
 *        The URL to send the content window to.
 * @param {optional int} frameDepth
 *        The depth of the frame to navigate. Defaults to 0, which is
 *        the top-level content window.
 * @return {Promise}
 */
function navigateSubframe(browser, url, frameDepth = 0) {
  let navigatePromise = controlFrameAt(browser, frameDepth, {
    name: "Navigate",
    url,
  });
  let subframeLoad = BrowserTestUtils.browserLoaded(browser, true);
  return Promise.all([navigatePromise, subframeLoad]);
}

/**
 * Removes the <iframe> from a content window pointed at PAGE_URL.
 *
 * By default, will target the top-level content window, but callers
 * can specify the index of a subframe to target. See prepareSubframes
 * for an idea of how the subframes are structured.
 *
 * @param {<xul:browser>} browser
 *        The browser that will have removal occur within it.
 * @param {optional int} frameDepth
 *        The depth of the frame that will have the removal occur within
 *        it. Defaults to 0, which is the top-level content window, meaning
 *        that the first subframe will be removed.
 * @return {Promise}
 */
function removeSubframeFrom(browser, frameDepth = 0) {
  return controlFrameAt(browser, frameDepth, {
    name: "RemoveSubframe",
  });
}

/**
 * Sends a command to a frame pointed at PAGE_URL. There are utility
 * functions defined in this file that call this function. You should
 * use those instead.
 *
 * @param {<xul:browser>} browser
 *        The browser to send the command to.
 * @param {int} frameDepth
 *        The depth of the frame that we'll send the command to. 0 means
 *        sending it to the top-level content window.
 * @param {object} command
 *        An object with the following structure:
 *
 *        {
 *          name: (string),
 *          <arbitrary arguments to send with the command>
 *        }
 *
 *        Here are the commands that can be sent:
 *
 *        AddBeforeUnload
 *          {int} howMany
 *          How many beforeunload event listeners to add.
 *
 *        AddOuterBeforeUnload
 *          {int} howMany
 *          How many beforeunload event listeners to add to
 *          the iframe in the document at this depth.
 *
 *        RemoveBeforeUnload
 *          {int} howMany
 *          How many beforeunload event listeners to remove.
 *
 *        RemoveOuterBeforeUnload
 *          {int} howMany
 *          How many beforeunload event listeners to remove from
 *          the iframe in the document at this depth.
 *
 *        Navigate
 *          {string} url
 *          The URL to send the frame to.
 *
 *        RemoveSubframe
 *
 * @return {Promise}
 */
function controlFrameAt(browser, frameDepth, command) {
  return SpecialPowers.spawn(
    browser,
    [{ frameDepth, command }],
    async function (args) {
      const { TestUtils } = ChromeUtils.importESModule(
        "resource://testing-common/TestUtils.sys.mjs"
      );

      let { command: contentCommand, frameDepth: contentFrameDepth } = args;

      let targetContent = content;
      let targetSubframe = content.document.getElementById("subframe");

      // We want to not only find the frame that maps to the
      // target frame depth that we've been given, but we also want
      // to count the total depth so that if a middle frame is removed
      // or navigated, then we know how many outer-window-destroyed
      // observer notifications to expect.
      let currentContent = targetContent;
      let currentSubframe = targetSubframe;

      let depth = 0;

      do {
        currentContent = currentSubframe.contentWindow;
        currentSubframe = currentContent.document.getElementById("subframe");
        depth++;
        if (depth == contentFrameDepth) {
          targetContent = currentContent;
          targetSubframe = currentSubframe;
        }
      } while (currentSubframe);

      switch (contentCommand.name) {
        case "AddBeforeUnload": {
          let BeforeUnloader = targetContent.wrappedJSObject.BeforeUnloader;
          Assert.ok(BeforeUnloader, "Found BeforeUnloader in the test page.");
          BeforeUnloader.pushInner(contentCommand.howMany);
          break;
        }
        case "AddOuterBeforeUnload": {
          let BeforeUnloader = targetContent.wrappedJSObject.BeforeUnloader;
          Assert.ok(BeforeUnloader, "Found BeforeUnloader in the test page.");
          BeforeUnloader.pushOuter(contentCommand.howMany);
          break;
        }
        case "RemoveBeforeUnload": {
          let BeforeUnloader = targetContent.wrappedJSObject.BeforeUnloader;
          Assert.ok(BeforeUnloader, "Found BeforeUnloader in the test page.");
          BeforeUnloader.popInner(contentCommand.howMany);
          break;
        }
        case "RemoveOuterBeforeUnload": {
          let BeforeUnloader = targetContent.wrappedJSObject.BeforeUnloader;
          Assert.ok(BeforeUnloader, "Found BeforeUnloader in the test page.");
          BeforeUnloader.popOuter(contentCommand.howMany);
          break;
        }
        case "Navigate": {
          // How many frames are going to be destroyed when we do this? We
          // need to wait for that many window destroyed notifications.
          targetContent.location = contentCommand.url;

          let destroyedOuterWindows = depth - contentFrameDepth;
          if (destroyedOuterWindows) {
            await TestUtils.topicObserved("outer-window-destroyed", () => {
              destroyedOuterWindows--;
              return !destroyedOuterWindows;
            });
          }
          break;
        }
        case "RemoveSubframe": {
          let subframe = targetContent.document.getElementById("subframe");
          Assert.ok(
            subframe,
            "Found subframe at frame depth of " + contentFrameDepth
          );
          subframe.remove();

          let destroyedOuterWindows = depth - contentFrameDepth;
          if (destroyedOuterWindows) {
            await TestUtils.topicObserved("outer-window-destroyed", () => {
              destroyedOuterWindows--;
              return !destroyedOuterWindows;
            });
          }
          break;
        }
      }
    }
  ).catch(console.error);
}

/**
 * Sets up a structure where a page at PAGE_URL will host an
 * <iframe> also pointed at PAGE_URL, and does this repeatedly
 * until we've achieved the desired frame depth. Note that this
 * will cause the top-level browser to reload, and wipe out any
 * previous changes to the DOM under it.
 *
 * @param {<xul:browser>} browser
 *        The browser in which we'll load our structure at the
 *        top level.
 * @param {Array<object>} options
 *        Set-up options for each subframe. The following properties
 *        are accepted:
 *
 *        {string} sandboxAttributes
 *          The value to set the sandbox attribute to. If null, no sandbox
 *          attribute will be set (and any pre-existing sandbox attributes)
 *          on the <iframe> will be removed.
 *
 *        The number of entries on the options Array corresponds to how many
 *        subframes are under the top-level content window.
 *
 *        Example:
 *
 *        yield prepareSubframes(browser, [
 *          { sandboxAttributes: null },
 *          { sandboxAttributes: "allow-modals" },
 *        ]);
 *
 *        This would create the following structure:
 *
 *        <top-level content window at PAGE_URL>
 *        |
 *        |--> <iframe at PAGE_URL, no sandbox attributes>
 *             |
 *             |--> <iframe at PAGE_URL, sandbox="allow-modals">
 *
 * @return {Promise}
 */
async function prepareSubframes(browser, options) {
  browser.reload();
  await BrowserTestUtils.browserLoaded(browser);

  await SpecialPowers.spawn(
    browser,
    [{ options, PAGE_URL }],
    async function (args) {
      let { options: allSubframeOptions, PAGE_URL: contentPageURL } = args;
      function loadBeforeUnloadHelper(doc, subframeOptions) {
        let subframe = doc.getElementById("subframe");
        subframe.remove();
        if (subframeOptions.sandboxAttributes === null) {
          subframe.removeAttribute("sandbox");
        } else {
          subframe.setAttribute("sandbox", subframeOptions.sandboxAttributes);
        }
        doc.body.appendChild(subframe);
        subframe.contentWindow.location = contentPageURL;
        return ContentTaskUtils.waitForEvent(subframe, "load").then(() => {
          return subframe.contentDocument;
        });
      }

      let currentDoc = content.document;
      for (let subframeOptions of allSubframeOptions) {
        currentDoc = await loadBeforeUnloadHelper(currentDoc, subframeOptions);
      }
    }
  );
}

/**
 * Ensures that a browser's nsIRemoteTab hasBeforeUnload attribute
 * is set to the expected value.
 *
 * @param {<xul:browser>} browser
 *        The browser whose nsIRemoteTab we will check.
 * @param {bool} expected
 *        True if hasBeforeUnload is expected to be true.
 */
function assertHasBeforeUnload(browser, expected) {
  Assert.equal(browser.hasBeforeUnload, expected);
}

/**
 * Tests that the MozBrowser hasBeforeUnload property works under
 * a number of different scenarios on inner windows. At a high-level,
 * we test that hasBeforeUnload works properly during page / iframe
 * navigation, or when an <iframe> with a beforeunload listener on its
 * inner window is removed from the DOM.
 */
add_task(async function test_inner_window_scenarios() {
  // Turn this off because the test expects the page to be not bfcached.
  await SpecialPowers.pushPrefEnv({
    set: [
      ["docshell.shistory.bfcache.ship_allow_beforeunload_listeners", false],
    ],
  });
  await BrowserTestUtils.withNewTab(
    {
      gBrowser,
      url: PAGE_URL,
    },
    async function (browser) {
      Assert.ok(
        browser.isRemoteBrowser,
        "This test only makes sense with out of process browsers."
      );
      assertHasBeforeUnload(browser, false);

      // Test the simple case on the top-level window by adding a single
      // beforeunload event listener on the inner window and then removing
      // it.
      await addBeforeUnloadListeners(browser);
      assertHasBeforeUnload(browser, true);
      await removeBeforeUnloadListeners(browser);
      assertHasBeforeUnload(browser, false);

      // Now let's add several beforeunload listeners, and
      // ensure that we only set hasBeforeUnload to false once
      // the last listener is removed.
      await addBeforeUnloadListeners(browser, 3);
      assertHasBeforeUnload(browser, true);
      await removeBeforeUnloadListeners(browser); // 2 left...
      assertHasBeforeUnload(browser, true);
      await removeBeforeUnloadListeners(browser); // 1 left...
      assertHasBeforeUnload(browser, true);
      await removeBeforeUnloadListeners(browser); // None left!

      assertHasBeforeUnload(browser, false);

      // Now let's have the top-level content window navigate
      // away with a beforeunload listener set, and ensure
      // that we clear the hasBeforeUnload value.
      await addBeforeUnloadListeners(browser, 5);
      await navigateSubframe(browser, "http://example.com");
      assertHasBeforeUnload(browser, false);

      // Now send the page back to the test page for
      // the next few tests.
      BrowserTestUtils.startLoadingURIString(browser, PAGE_URL);
      await BrowserTestUtils.browserLoaded(browser);

      // We want to test hasBeforeUnload works properly with
      // beforeunload event listeners in <iframe> elements too.
      // We prepare a structure like this with 3 content windows
      // to exercise:
      //
      // <top-level content window at PAGE_URL> (TOP)
      // |
      // |--> <iframe at PAGE_URL> (MIDDLE)
      //      |
      //      |--> <iframe at PAGE_URL> (BOTTOM)
      //
      await prepareSubframes(browser, [
        { sandboxAttributes: null },
        { sandboxAttributes: null },
      ]);
      // These constants are just to make it easier to know which
      // frame we're referring to without having to remember the
      // exact indices.
      const TOP = 0;
      const MIDDLE = 1;
      const BOTTOM = 2;

      // We should initially start with hasBeforeUnload set to false.
      assertHasBeforeUnload(browser, false);

      // Tests that if there are beforeunload event listeners on
      // all levels of our window structure, that we only set
      // hasBeforeUnload to false once the last beforeunload
      // listener has been unset.
      await addBeforeUnloadListeners(browser, 2, MIDDLE);
      assertHasBeforeUnload(browser, true);
      await addBeforeUnloadListeners(browser, 1, TOP);
      assertHasBeforeUnload(browser, true);
      await addBeforeUnloadListeners(browser, 5, BOTTOM);
      assertHasBeforeUnload(browser, true);

      await removeBeforeUnloadListeners(browser, 1, TOP);
      assertHasBeforeUnload(browser, true);
      await removeBeforeUnloadListeners(browser, 5, BOTTOM);
      assertHasBeforeUnload(browser, true);
      await removeBeforeUnloadListeners(browser, 2, MIDDLE);
      assertHasBeforeUnload(browser, false);

      // Tests that if a beforeunload event listener is set on
      // an iframe that navigates away to a page without a
      // beforeunload listener, that hasBeforeUnload is set
      // to false.
      await addBeforeUnloadListeners(browser, 5, BOTTOM);
      assertHasBeforeUnload(browser, true);

      await navigateSubframe(browser, "http://example.com", BOTTOM);
      assertHasBeforeUnload(browser, false);

      // Reset our window structure now.
      await prepareSubframes(browser, [
        { sandboxAttributes: null },
        { sandboxAttributes: null },
      ]);

      // This time, add beforeunload event listeners to both the
      // MIDDLE and BOTTOM frame, and then navigate the MIDDLE
      // away. This should set hasBeforeUnload to false.
      await addBeforeUnloadListeners(browser, 3, MIDDLE);
      await addBeforeUnloadListeners(browser, 1, BOTTOM);
      assertHasBeforeUnload(browser, true);
      await navigateSubframe(browser, "http://example.com", MIDDLE);
      assertHasBeforeUnload(browser, false);

      // Tests that if the MIDDLE and BOTTOM frames have beforeunload
      // event listeners, and if we remove the BOTTOM <iframe> and the
      // MIDDLE <iframe>, that hasBeforeUnload is set to false.
      await prepareSubframes(browser, [
        { sandboxAttributes: null },
        { sandboxAttributes: null },
      ]);
      await addBeforeUnloadListeners(browser, 3, MIDDLE);
      await addBeforeUnloadListeners(browser, 1, BOTTOM);
      assertHasBeforeUnload(browser, true);
      await removeSubframeFrom(browser, MIDDLE);
      assertHasBeforeUnload(browser, true);
      await removeSubframeFrom(browser, TOP);
      assertHasBeforeUnload(browser, false);

      // Tests that if the MIDDLE and BOTTOM frames have beforeunload
      // event listeners, and if we remove just the MIDDLE <iframe>, that
      // hasBeforeUnload is set to false.
      await prepareSubframes(browser, [
        { sandboxAttributes: null },
        { sandboxAttributes: null },
      ]);
      await addBeforeUnloadListeners(browser, 3, MIDDLE);
      await addBeforeUnloadListeners(browser, 1, BOTTOM);
      assertHasBeforeUnload(browser, true);
      await removeSubframeFrom(browser, TOP);
      assertHasBeforeUnload(browser, false);

      // Test that two sandboxed iframes, _without_ the allow-modals
      // permission, do not result in the hasBeforeUnload attribute
      // being set to true when beforeunload event listeners are added.
      await prepareSubframes(browser, [
        { sandboxAttributes: "allow-scripts" },
        { sandboxAttributes: "allow-scripts" },
      ]);

      await addBeforeUnloadListeners(browser, 3, MIDDLE);
      await addBeforeUnloadListeners(browser, 1, BOTTOM);
      assertHasBeforeUnload(browser, false);

      await removeBeforeUnloadListeners(browser, 3, MIDDLE);
      await removeBeforeUnloadListeners(browser, 1, BOTTOM);
      assertHasBeforeUnload(browser, false);

      // Test that two sandboxed iframes, both with the allow-modals
      // permission, cause the hasBeforeUnload attribute to be set
      // to true when beforeunload event listeners are added.
      await prepareSubframes(browser, [
        { sandboxAttributes: "allow-scripts allow-modals" },
        { sandboxAttributes: "allow-scripts allow-modals" },
      ]);

      await addBeforeUnloadListeners(browser, 3, MIDDLE);
      await addBeforeUnloadListeners(browser, 1, BOTTOM);
      assertHasBeforeUnload(browser, true);

      await removeBeforeUnloadListeners(browser, 1, BOTTOM);
      assertHasBeforeUnload(browser, true);
      await removeBeforeUnloadListeners(browser, 3, MIDDLE);
      assertHasBeforeUnload(browser, false);
    }
  );
});

/**
 * Tests that the nsIRemoteTab hasBeforeUnload attribute works under
 * a number of different scenarios on outer windows. Very similar to
 * the above set of tests, except that we add the beforeunload listeners
 * to the iframe DOM nodes instead of the inner windows.
 */
add_task(async function test_outer_window_scenarios() {
  // Turn this off because the test expects the page to be not bfcached.
  await SpecialPowers.pushPrefEnv({
    set: [
      ["docshell.shistory.bfcache.ship_allow_beforeunload_listeners", false],
    ],
  });
  await BrowserTestUtils.withNewTab(
    {
      gBrowser,
      url: PAGE_URL,
    },
    async function (browser) {
      Assert.ok(
        browser.isRemoteBrowser,
        "This test only makes sense with out of process browsers."
      );
      assertHasBeforeUnload(browser, false);

      // We want to test hasBeforeUnload works properly with
      // beforeunload event listeners in <iframe> elements.
      // We prepare a structure like this with 3 content windows
      // to exercise:
      //
      // <top-level content window at PAGE_URL> (TOP)
      // |
      // |--> <iframe at PAGE_URL> (MIDDLE)
      //      |
      //      |--> <iframe at PAGE_URL> (BOTTOM)
      //
      await prepareSubframes(browser, [
        { sandboxAttributes: null },
        { sandboxAttributes: null },
      ]);

      // These constants are just to make it easier to know which
      // frame we're referring to without having to remember the
      // exact indices.
      const TOP = 0;
      const MIDDLE = 1;
      const BOTTOM = 2;

      // Test the simple case on the top-level window by adding a single
      // beforeunload event listener on the outer window of the iframe
      // in the TOP document.
      await addOuterBeforeUnloadListeners(browser);
      assertHasBeforeUnload(browser, true);

      await removeOuterBeforeUnloadListeners(browser);
      assertHasBeforeUnload(browser, false);

      // Now let's add several beforeunload listeners, and
      // ensure that we only set hasBeforeUnload to false once
      // the last listener is removed.
      await addOuterBeforeUnloadListeners(browser, 3);
      assertHasBeforeUnload(browser, true);
      await removeOuterBeforeUnloadListeners(browser); // 2 left...
      assertHasBeforeUnload(browser, true);
      await removeOuterBeforeUnloadListeners(browser); // 1 left...
      assertHasBeforeUnload(browser, true);
      await removeOuterBeforeUnloadListeners(browser); // None left!

      assertHasBeforeUnload(browser, false);

      // Now let's have the top-level content window navigate away
      // with a beforeunload listener set on the outer window of the
      // iframe inside it, and ensure that we clear the hasBeforeUnload
      // value.
      await addOuterBeforeUnloadListeners(browser, 5);
      await navigateSubframe(browser, "http://example.com", TOP);
      assertHasBeforeUnload(browser, false);

      // Now send the page back to the test page for
      // the next few tests.
      BrowserTestUtils.startLoadingURIString(browser, PAGE_URL);
      await BrowserTestUtils.browserLoaded(browser);

      // We should initially start with hasBeforeUnload set to false.
      assertHasBeforeUnload(browser, false);

      await prepareSubframes(browser, [
        { sandboxAttributes: null },
        { sandboxAttributes: null },
      ]);

      // Tests that if there are beforeunload event listeners on
      // all levels of our window structure, that we only set
      // hasBeforeUnload to false once the last beforeunload
      // listener has been unset.
      await addOuterBeforeUnloadListeners(browser, 3, MIDDLE);
      assertHasBeforeUnload(browser, true);
      await addOuterBeforeUnloadListeners(browser, 7, BOTTOM);
      assertHasBeforeUnload(browser, true);

      await removeOuterBeforeUnloadListeners(browser, 7, BOTTOM);
      assertHasBeforeUnload(browser, true);
      await removeOuterBeforeUnloadListeners(browser, 3, MIDDLE);
      assertHasBeforeUnload(browser, false);

      // Tests that if a beforeunload event listener is set on
      // an iframe that navigates away to a page without a
      // beforeunload listener, that hasBeforeUnload is set
      // to false. We're setting the event listener on the
      // outer window on the <iframe> in the MIDDLE, which
      // itself contains the BOTTOM frame it our structure.
      await addOuterBeforeUnloadListeners(browser, 5, BOTTOM);
      assertHasBeforeUnload(browser, true);

      // Now navigate that BOTTOM frame.
      await navigateSubframe(browser, "http://example.com", BOTTOM);
      assertHasBeforeUnload(browser, false);

      // Reset our window structure now.
      await prepareSubframes(browser, [
        { sandboxAttributes: null },
        { sandboxAttributes: null },
      ]);

      // This time, add beforeunload event listeners to the outer
      // windows for MIDDLE and BOTTOM. Then navigate the MIDDLE
      // frame. This should set hasBeforeUnload to false.
      await addOuterBeforeUnloadListeners(browser, 3, MIDDLE);
      await addOuterBeforeUnloadListeners(browser, 1, BOTTOM);
      assertHasBeforeUnload(browser, true);
      await navigateSubframe(browser, "http://example.com", MIDDLE);
      assertHasBeforeUnload(browser, false);

      // Adds beforeunload event listeners to the outer windows of
      // MIDDLE and BOTOTM, and then removes those iframes. Removing
      // both iframes should set hasBeforeUnload to false.
      await prepareSubframes(browser, [
        { sandboxAttributes: null },
        { sandboxAttributes: null },
      ]);
      await addOuterBeforeUnloadListeners(browser, 3, MIDDLE);
      await addOuterBeforeUnloadListeners(browser, 1, BOTTOM);
      assertHasBeforeUnload(browser, true);
      await removeSubframeFrom(browser, BOTTOM);
      assertHasBeforeUnload(browser, true);
      await removeSubframeFrom(browser, MIDDLE);
      assertHasBeforeUnload(browser, false);

      // Adds beforeunload event listeners to the outer windows of MIDDLE
      // and BOTTOM, and then removes just the MIDDLE iframe (which will
      // take the bottom one with it). This should set hasBeforeUnload to
      // false.
      await prepareSubframes(browser, [
        { sandboxAttributes: null },
        { sandboxAttributes: null },
      ]);
      await addOuterBeforeUnloadListeners(browser, 3, MIDDLE);
      await addOuterBeforeUnloadListeners(browser, 1, BOTTOM);
      assertHasBeforeUnload(browser, true);
      await removeSubframeFrom(browser, TOP);
      assertHasBeforeUnload(browser, false);

      // Test that two sandboxed iframes, _without_ the allow-modals
      // permission, do not result in the hasBeforeUnload attribute
      // being set to true when beforeunload event listeners are added
      // to the outer windows. Note that this requires the
      // allow-same-origin permission, otherwise a cross-origin
      // security exception is thrown.
      await prepareSubframes(browser, [
        { sandboxAttributes: "allow-same-origin allow-scripts" },
        { sandboxAttributes: "allow-same-origin allow-scripts" },
      ]);

      await addOuterBeforeUnloadListeners(browser, 3, MIDDLE);
      await addOuterBeforeUnloadListeners(browser, 1, BOTTOM);
      assertHasBeforeUnload(browser, false);

      await removeOuterBeforeUnloadListeners(browser, 3, MIDDLE);
      await removeOuterBeforeUnloadListeners(browser, 1, BOTTOM);
      assertHasBeforeUnload(browser, false);

      // Test that two sandboxed iframes, both with the allow-modals
      // permission, cause the hasBeforeUnload attribute to be set
      // to true when beforeunload event listeners are added. Note
      // that this requires the allow-same-origin permission,
      // otherwise a cross-origin security exception is thrown.
      await prepareSubframes(browser, [
        { sandboxAttributes: "allow-same-origin allow-scripts allow-modals" },
        { sandboxAttributes: "allow-same-origin allow-scripts allow-modals" },
      ]);

      await addOuterBeforeUnloadListeners(browser, 3, MIDDLE);
      await addOuterBeforeUnloadListeners(browser, 1, BOTTOM);
      assertHasBeforeUnload(browser, true);

      await removeOuterBeforeUnloadListeners(browser, 1, BOTTOM);
      assertHasBeforeUnload(browser, true);
      await removeOuterBeforeUnloadListeners(browser, 3, MIDDLE);
      assertHasBeforeUnload(browser, false);
    }
  );
});

/**
 * Tests hasBeforeUnload behaviour when beforeunload event listeners
 * are added on both inner and outer windows.
 */
add_task(async function test_mixed_inner_and_outer_window_scenarios() {
  // Turn this off because the test expects the page to be not bfcached.
  await SpecialPowers.pushPrefEnv({
    set: [
      ["docshell.shistory.bfcache.ship_allow_beforeunload_listeners", false],
    ],
  });
  await BrowserTestUtils.withNewTab(
    {
      gBrowser,
      url: PAGE_URL,
    },
    async function (browser) {
      Assert.ok(
        browser.isRemoteBrowser,
        "This test only makes sense with out of process browsers."
      );
      assertHasBeforeUnload(browser, false);

      // We want to test hasBeforeUnload works properly with
      // beforeunload event listeners in <iframe> elements.
      // We prepare a structure like this with 3 content windows
      // to exercise:
      //
      // <top-level content window at PAGE_URL> (TOP)
      // |
      // |--> <iframe at PAGE_URL> (MIDDLE)
      //      |
      //      |--> <iframe at PAGE_URL> (BOTTOM)
      //
      await prepareSubframes(browser, [
        { sandboxAttributes: null },
        { sandboxAttributes: null },
      ]);

      // These constants are just to make it easier to know which
      // frame we're referring to without having to remember the
      // exact indices.
      const TOP = 0;
      const MIDDLE = 1;
      const BOTTOM = 2;

      await addBeforeUnloadListeners(browser, 1, TOP);
      assertHasBeforeUnload(browser, true);
      await addBeforeUnloadListeners(browser, 2, MIDDLE);
      assertHasBeforeUnload(browser, true);
      await addBeforeUnloadListeners(browser, 5, BOTTOM);
      assertHasBeforeUnload(browser, true);

      await addOuterBeforeUnloadListeners(browser, 3, MIDDLE);
      assertHasBeforeUnload(browser, true);
      await addOuterBeforeUnloadListeners(browser, 7, BOTTOM);
      assertHasBeforeUnload(browser, true);

      await removeBeforeUnloadListeners(browser, 5, BOTTOM);
      assertHasBeforeUnload(browser, true);

      await removeBeforeUnloadListeners(browser, 2, MIDDLE);
      assertHasBeforeUnload(browser, true);

      await removeOuterBeforeUnloadListeners(browser, 3, MIDDLE);
      assertHasBeforeUnload(browser, true);

      await removeBeforeUnloadListeners(browser, 1, TOP);
      assertHasBeforeUnload(browser, true);

      await removeOuterBeforeUnloadListeners(browser, 7, BOTTOM);
      assertHasBeforeUnload(browser, false);
    }
  );
});