File: InfoBar.sys.mjs

package info (click to toggle)
firefox 147.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,683,320 kB
  • sloc: cpp: 7,607,359; javascript: 6,533,295; ansic: 3,775,223; python: 1,415,500; xml: 634,561; asm: 438,949; java: 186,241; sh: 62,752; makefile: 18,079; objc: 13,092; perl: 12,808; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (719 lines) | stat: -rw-r--r-- 23,349 bytes parent folder | download
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/* eslint-disable no-use-before-define */
const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  ASRouter: "resource:///modules/asrouter/ASRouter.sys.mjs",
  PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
  RemoteL10n: "resource:///modules/asrouter/RemoteL10n.sys.mjs",
  SpecialMessageActions:
    "resource://messaging-system/lib/SpecialMessageActions.sys.mjs",
});

const TYPES = {
  UNIVERSAL: "universal",
  GLOBAL: "global",
};

const FTL_FILES = [
  "browser/newtab/asrouter.ftl",
  "browser/defaultBrowserNotification.ftl",
  "browser/profiles.ftl",
  "browser/termsofuse.ftl",
];

class InfoBarNotification {
  constructor(message, dispatch) {
    this._dispatch = dispatch;
    this.dispatchUserAction = this.dispatchUserAction.bind(this);
    this.buttonCallback = this.buttonCallback.bind(this);
    this.infobarCallback = this.infobarCallback.bind(this);
    this.message = message;
    this.notification = null;
    const dismissPrefConfig = message?.content?.dismissOnPrefChange;
    // If set, these are the prefs to watch for changes to auto-dismiss the infobar.
    if (Array.isArray(dismissPrefConfig)) {
      this._dismissPrefs = dismissPrefConfig;
    } else if (dismissPrefConfig) {
      this._dismissPrefs = [dismissPrefConfig];
    } else {
      this._dismissPrefs = [];
    }
    this._prefObserver = null;
  }

  /**
   * Ensure a hidden container of <a data-l10n-name> templates exists, and
   * inject the request links using hrefs from message.content.linkUrls.
   */
  _ensureLinkTemplatesFor(doc, names) {
    let container = doc.getElementById("infobar-link-templates");
    // We inject a hidden <div> of <a data-l10n-name> templates into the
    // document because Fluent’s DOM-overlay scans the page for those
    // placeholders.
    if (!container) {
      container = doc.createElement("div");
      container.id = "infobar-link-templates";
      container.hidden = true;
      doc.body.appendChild(container);
    }

    const linkUrls = this.message.content.linkUrls || {};
    for (let name of names) {
      if (!container.querySelector(`a[data-l10n-name="${name}"]`)) {
        const a = doc.createElement("a");
        a.dataset.l10nName = name;
        a.href = linkUrls[name];
        container.appendChild(a);
      }
    }
  }

  /**
   * Async helper to render a Fluent string. If the translation contains `<a
   * data-l10n-name>`, it will parse and inject the associated link contained
   * in the message.
   */
  async _buildMessageFragment(doc, browser, stringId, args) {
    // Get the raw HTML translation
    const html = await lazy.RemoteL10n.formatLocalizableText({
      string_id: stringId,
      ...(args && { args }),
    });

    // If no inline anchors, just return a span
    if (!html.includes('data-l10n-name="')) {
      return lazy.RemoteL10n.createElement(doc, "span", {
        content: { string_id: stringId, ...(args && { args }) },
      });
    }

    // Otherwise parse it and set up a fragment
    const temp = new DOMParser().parseFromString(html, "text/html").body;
    const frag = doc.createDocumentFragment();

    // Prepare <a data-l10n-name> templates
    const names = [...temp.querySelectorAll("a[data-l10n-name]")].map(
      a => a.dataset.l10nName
    );
    this._ensureLinkTemplatesFor(doc, names);

    // Import each node and wire up any anchors it contains
    for (const node of temp.childNodes) {
      // Nodes from DOMParser belong to a different document, so importNode()
      // clones them into our target doc
      const importedNode = doc.importNode(node, true);

      if (importedNode.nodeType === Node.ELEMENT_NODE) {
        // collect this node if it's an anchor, and all child anchors
        const anchors = [];
        if (importedNode.matches("a[data-l10n-name]")) {
          anchors.push(importedNode);
        }
        anchors.push(...importedNode.querySelectorAll("a[data-l10n-name]"));

        const linkActions = this.message.content.linkActions || {};

        for (const a of anchors) {
          const name = a.dataset.l10nName;
          const template = doc
            .getElementById("infobar-link-templates")
            .querySelector(`a[data-l10n-name="${name}"]`);
          if (!template) {
            continue;
          }
          a.href = template.href;
          a.addEventListener("click", e => {
            e.preventDefault();
            // Open link URL
            try {
              lazy.SpecialMessageActions.handleAction(
                {
                  type: "OPEN_URL",
                  data: { args: a.href, where: args?.where || "tab" },
                },
                browser
              );
            } catch (err) {
              console.error(`Error handling OPEN_URL action:`, err);
            }
            // Then fire the defined actions for that link, if applicable
            if (linkActions[name]) {
              try {
                lazy.SpecialMessageActions.handleAction(
                  linkActions[name],
                  browser
                );
              } catch (err) {
                console.error(
                  `Error handling ${linkActions[name]} action:`,
                  err
                );
              }
              if (linkActions[name].dismiss) {
                this.notification?.dismiss();
              }
            }
          });
        }
      }

      frag.appendChild(importedNode);
    }

    return frag;
  }

  /**
   * Displays the infobar notification in the specified browser and sends an impression ping.
   * Formats the message and buttons, and appends the notification.
   * For universal infobars, only records an impression for the first instance.
   *
   * @param {object} browser - The browser reference for the currently selected tab.
   */
  async showNotification(browser) {
    let { content } = this.message;
    let { gBrowser } = browser.ownerGlobal;
    let doc = gBrowser.ownerDocument;
    let notificationContainer;
    if ([TYPES.GLOBAL, TYPES.UNIVERSAL].includes(content.type)) {
      notificationContainer = browser.ownerGlobal.gNotificationBox;
    } else {
      notificationContainer = gBrowser.getNotificationBox(browser);
    }

    let priority = content.priority || notificationContainer.PRIORITY_SYSTEM;

    let labelNode = await this.formatMessageConfig(doc, browser, content.text);

    this.notification = await notificationContainer.appendNotification(
      this.message.id,
      {
        label: labelNode,
        image: content.icon || "chrome://branding/content/icon64.png",
        priority,
        eventCallback: this.infobarCallback,
        style: content.style || {},
      },
      content.buttons.map(b => this.formatButtonConfig(b)),
      true, // Disables clickjacking protections
      content.dismissable
    );
    // If the infobar is universal, only record an impression for the first
    // instance.
    if (
      content.type !== TYPES.UNIVERSAL ||
      !InfoBar._universalInfobars.length
    ) {
      this.addImpression(browser);
    }

    // Only add if the universal infobar is still active. Prevents race condition
    // where a notification could add itself after removeUniversalInfobars().
    if (
      content.type === TYPES.UNIVERSAL &&
      InfoBar._activeInfobar?.message?.id === this.message.id
    ) {
      InfoBar._universalInfobars.push({
        box: notificationContainer,
        notification: this.notification,
      });
    }

    // After the notification exists, attach a pref observer if applicable.
    this._maybeAttachPrefObserver();
  }

  _createLinkNode(doc, browser, { href, where = "tab", string_id, args, raw }) {
    const a = doc.createElement("a");
    a.href = href;
    a.addEventListener("click", e => {
      e.preventDefault();
      lazy.SpecialMessageActions.handleAction(
        { type: "OPEN_URL", data: { args: a.href, where } },
        browser
      );
    });

    if (string_id) {
      // wrap a localized span inside
      const span = lazy.RemoteL10n.createElement(doc, "span", {
        content: { string_id, ...(args && { args }) },
      });
      a.appendChild(span);
    } else {
      a.textContent = raw || "";
    }

    return a;
  }

  async formatMessageConfig(doc, browser, content) {
    const frag = doc.createDocumentFragment();
    const parts = Array.isArray(content) ? content : [content];

    for (const part of parts) {
      if (!part) {
        continue;
      }
      if (part.href) {
        frag.appendChild(this._createLinkNode(doc, browser, part));
        continue;
      }

      if (part.string_id) {
        const subFrag = await this._buildMessageFragment(
          doc,
          browser,
          part.string_id,
          part.args
        );
        frag.appendChild(subFrag);
        continue;
      }

      if (typeof part === "string") {
        frag.appendChild(doc.createTextNode(part));
        continue;
      }

      if (part.raw && typeof part.raw === "string") {
        frag.appendChild(doc.createTextNode(part.raw));
      }
    }

    return frag;
  }

  formatButtonConfig(button) {
    let btnConfig = { callback: this.buttonCallback, ...button };
    // notificationbox will set correct data-l10n-id attributes if passed in
    // using the l10n-id key. Otherwise the `button.label` text is used.
    if (button.label.string_id) {
      btnConfig["l10n-id"] = button.label.string_id;
    }

    return btnConfig;
  }

  handleImpressionAction(browser) {
    const ALLOWED_IMPRESSION_ACTIONS = ["SET_PREF"];
    const impressionAction = this.message.content.impression_action;
    const actions =
      impressionAction.type === "MULTI_ACTION"
        ? impressionAction.data.actions
        : [impressionAction];

    actions.forEach(({ type, data, once }) => {
      if (!ALLOWED_IMPRESSION_ACTIONS.includes(type)) {
        return;
      }

      let { messageImpressions } = lazy.ASRouter.state;
      // If we only want to perform the action on first impression, ensure no
      // impressions exist for this message.
      if (once && messageImpressions[this.message.id]?.length) {
        return;
      }

      data.onImpression = true;
      try {
        lazy.SpecialMessageActions.handleAction({ type, data }, browser);
      } catch (err) {
        console.error(`Error handling ${type} impression action:`, err);
      }
    });
  }

  addImpression(browser) {
    // If the message has an impression action, handle it before dispatching the
    // impression. `this._dispatch` may be async and we want to ensure we have a
    // consistent impression count when handling impression actions that should
    // only occur once.
    if (this.message.content.impression_action) {
      this.handleImpressionAction(browser);
    }
    // Record an impression in ASRouter for frequency capping
    this._dispatch({ type: "IMPRESSION", data: this.message });
    // Send a user impression telemetry ping
    this.sendUserEventTelemetry("IMPRESSION");
  }

  /**
   * Callback fired when a button in the infobar is clicked.
   *
   * @param {Element} notificationBox - The `<notification-message>` element representing the infobar.
   * @param {object} btnDescription - An object describing the button, includes the label, the action with an optional dismiss property, and primary button styling.
   * @param {Element} target - The <button> DOM element that was clicked.
   * @returns {boolean} `true` to keep the infobar open, `false` to dismiss it.
   */
  buttonCallback(notificationBox, btnDescription, target) {
    this.dispatchUserAction(
      btnDescription.action,
      target.ownerGlobal.gBrowser.selectedBrowser
    );
    let isPrimary = target.classList.contains("primary");
    let eventName = isPrimary
      ? "CLICK_PRIMARY_BUTTON"
      : "CLICK_SECONDARY_BUTTON";
    this.sendUserEventTelemetry(eventName);

    // Prevents infobar dismissal when dismiss is explicitly set to `false`
    return btnDescription.action?.dismiss === false;
  }

  dispatchUserAction(action, selectedBrowser) {
    this._dispatch({ type: "USER_ACTION", data: action }, selectedBrowser);
  }

  /**
   * Handles infobar events triggered by the notification interactions (excluding button clicks).
   * Cleans up the notification and active infobar state when the infobar is removed or dismissed.
   * If the removed infobar is universal, ensures all universal infobars and related observers are also removed.
   *
   * @param {string} eventType - The type of event (e.g., "removed").
   */
  infobarCallback(eventType) {
    // Clean up the pref observer on any removal/dismissal path.
    this._removePrefObserver();
    const wasUniversal = this.message.content.type === TYPES.UNIVERSAL;
    const isActiveMessage =
      InfoBar._activeInfobar?.message?.id === this.message.id;
    if (eventType === "removed") {
      this.notification = null;
      if (isActiveMessage) {
        InfoBar._activeInfobar = null;
      }
    } else if (this.notification) {
      this.sendUserEventTelemetry("DISMISSED");
      this.notification = null;

      if (isActiveMessage) {
        InfoBar._activeInfobar = null;
      }
    }
    // If one instance of universal infobar is removed, remove all instances and
    // the new window observer
    if (wasUniversal && isActiveMessage && InfoBar._universalInfobars.length) {
      this.removeUniversalInfobars();
    }
  }

  /**
   * If content.dismissOnPrefChange is set (string or array), observe those
   * pref(s) and dismiss the infobar whenever any of them changes (including
   * when it is set for the first time).
   */
  _maybeAttachPrefObserver() {
    if (!this._dismissPrefs?.length || this._prefObserver) {
      return;
    }
    // Weak observer to avoid leaks.
    this._prefObserver = {
      QueryInterface: ChromeUtils.generateQI([
        "nsIObserver",
        "nsISupportsWeakReference",
      ]),
      observe: (subject, topic, data) => {
        if (topic === "nsPref:changed" && this._dismissPrefs.includes(data)) {
          try {
            this.notification?.dismiss();
          } catch (e) {
            console.error("Failed to dismiss infobar on pref change:", e);
          }
        }
      },
    };
    try {
      // Register each pref with a weak observer and ignore per-pref failures.
      for (const pref of this._dismissPrefs) {
        try {
          Services.prefs.addObserver(pref, this._prefObserver, true);
        } catch (_) {}
      }
    } catch (e) {
      console.error(
        "Failed to add prefs observer(s) for dismissOnPrefChange:",
        e
      );
    }
  }

  _removePrefObserver() {
    if (!this._dismissPrefs?.length || !this._prefObserver) {
      return;
    }
    for (const pref of this._dismissPrefs) {
      try {
        Services.prefs.removeObserver(pref, this._prefObserver);
      } catch (_) {
        // Ignore as the observer might already be removed during shutdown/teardown.
      }
    }
    this._prefObserver = null;
  }

  /**
   * Removes all active universal infobars from each window.
   * Unregisters the observer for new windows, clears the tracking array, and resets the
   * active infobar state.
   */
  removeUniversalInfobars() {
    // Remove the new window observer
    if (InfoBar._observingWindowOpened) {
      InfoBar._observingWindowOpened = false;
      Services.obs.removeObserver(InfoBar, "domwindowopened");
    }
    // Remove the universal infobar
    InfoBar._universalInfobars.forEach(({ box, notification }) => {
      try {
        if (box && notification) {
          box.removeNotification(notification);
        }
      } catch (error) {
        console.error("Failed to remove notification: ", error);
      }
    });
    InfoBar._universalInfobars = [];

    if (InfoBar._activeInfobar?.message.content.type === TYPES.UNIVERSAL) {
      InfoBar._activeInfobar = null;
    }
  }

  sendUserEventTelemetry(event) {
    const ping = {
      message_id: this.message.id,
      event,
    };
    this._dispatch({
      type: "INFOBAR_TELEMETRY",
      data: { action: "infobar_user_event", ...ping },
    });
  }
}

export const InfoBar = {
  _activeInfobar: null,
  _universalInfobars: [],
  _observingWindowOpened: false,

  maybeLoadCustomElement(win) {
    if (!win.customElements.get("remote-text")) {
      Services.scriptloader.loadSubScript(
        "chrome://browser/content/asrouter/components/remote-text.js",
        win
      );
    }
  },

  maybeInsertFTL(win) {
    FTL_FILES.forEach(path => win.MozXULElement.insertFTLIfNeeded(path));
  },

  /**
   * Helper to check the window's state and whether it's a
   * private browsing window, a popup or a taskbar tab.
   *
   * @returns {boolean} `true` if the window is valid for showing an infobar.
   */
  isValidInfobarWindow(win) {
    if (!win || win.closed) {
      return false;
    }
    if (lazy.PrivateBrowsingUtils.isWindowPrivate(win)) {
      return false;
    }
    if (!win.toolbar?.visible) {
      // Popups don't have a visible toolbar
      return false;
    }
    if (win.document.documentElement.hasAttribute("taskbartab")) {
      return false;
    }
    return true;
  },

  /**
   * Displays the universal infobar in all open, fully loaded browser windows.
   *
   * @param {InfoBarNotification} notification - The notification instance to display.
   */
  async showNotificationAllWindows(notification) {
    for (let win of Services.wm.getEnumerator("navigator:browser")) {
      if (
        !win.gBrowser ||
        win.document?.readyState !== "complete" ||
        !this.isValidInfobarWindow(win)
      ) {
        continue;
      }
      this.maybeLoadCustomElement(win);
      this.maybeInsertFTL(win);
      const browser = win.gBrowser.selectedBrowser;
      await notification.showNotification(browser);
    }
  },

  _maybeReplaceActiveInfoBar(nextMessage) {
    if (!this._activeInfobar) {
      return false;
    }
    const replacementEligible = nextMessage?.content?.canReplace || [];
    const activeId = this._activeInfobar.message?.id;
    if (!replacementEligible.includes(activeId)) {
      return false;
    }
    const activeType = this._activeInfobar.message?.content?.type;
    if (activeType === TYPES.UNIVERSAL) {
      this._activeInfobar.notification?.removeUniversalInfobars();
    } else {
      try {
        this._activeInfobar.notification?.notification.dismiss();
      } catch (e) {
        console.error("Failed to dismiss active infobar:", e);
      }
    }
    this._activeInfobar = null;
    return true;
  },

  /**
   * Displays an infobar notification in the specified browser window.
   * For the first universal infobar, shows the notification in all open browser windows
   * and sets up an observer to handle new windows.
   * For non-universal, displays the notification only in the given window.
   *
   * @param {object} browser - The browser reference for the currently selected tab.
   * @param {object} message - The message object describing the infobar content.
   * @param {function} dispatch - The dispatch function for actions.
   * @param {boolean} universalInNewWin - `True` if this is a universal infobar for a new window.
   * @returns {Promise<InfoBarNotification|null>} The notification instance, or null if not shown.
   */
  async showInfoBarMessage(browser, message, dispatch, universalInNewWin) {
    const win = browser?.ownerGlobal;
    if (!this.isValidInfobarWindow(win)) {
      return null;
    }
    const isUniversal = message.content.type === TYPES.UNIVERSAL;
    // Check if this is the first instance of a universal infobar
    const isFirstUniversal = !universalInNewWin && isUniversal;
    // Prevent stacking multiple infobars
    if (this._activeInfobar && !universalInNewWin) {
      // Check if infobar is configured to replace the current infobar.
      if (!this._maybeReplaceActiveInfoBar(message)) {
        return null;
      }
    }

    this.maybeLoadCustomElement(win);
    this.maybeInsertFTL(win);

    let notification = new InfoBarNotification(message, dispatch);

    if (!universalInNewWin) {
      this._activeInfobar = { message, dispatch, notification };
    }

    if (isFirstUniversal) {
      await this.showNotificationAllWindows(notification);
      if (!this._observingWindowOpened) {
        this._observingWindowOpened = true;
        Services.obs.addObserver(this, "domwindowopened");
      } else {
        // TODO: At least during testing it seems that we can get here more
        // than once without passing through removeUniversalInfobars(). Is
        // this expected?
        console.warn(
          "InfoBar: Already observing new windows for universal infobar."
        );
      }
    } else {
      await notification.showNotification(browser);
    }

    if (!universalInNewWin) {
      this._activeInfobar = { message, dispatch, notification };
      // If the window closes before the user interacts with the active infobar,
      // clear it
      win.addEventListener(
        "unload",
        () => {
          // Remove this window’s stale entry
          InfoBar._universalInfobars = InfoBar._universalInfobars.filter(
            ({ box }) => box.ownerGlobal !== win
          );

          if (isUniversal) {
            // If there’s still at least one live universal infobar,
            // make it the active infobar; otherwise clear the active infobar
            const nextEntry = InfoBar._universalInfobars.find(
              ({ box }) => !box.ownerGlobal?.closed
            );
            const nextNotification = nextEntry?.notification;
            InfoBar._activeInfobar = nextNotification
              ? { message, dispatch, nextNotification }
              : null;
          } else {
            // Non-universal always clears on unload
            InfoBar._activeInfobar = null;
          }
        },
        { once: true }
      );
    }

    return notification;
  },

  /**
   * Observer callback fired when a new window is opened.
   * If the topic is "domwindowopened" and the window is a valid target,
   * the universal infobar will be shown in the new window once loaded.
   *
   * @param {Window} aSubject - The newly opened window.
   * @param {string} aTopic - The topic of the observer notification.
   */
  observe(aSubject, aTopic) {
    if (aTopic !== "domwindowopened") {
      return;
    }
    const win = aSubject;

    if (!this.isValidInfobarWindow(win)) {
      return;
    }

    const { message, dispatch } = this._activeInfobar || {};
    if (!message || message.content.type !== TYPES.UNIVERSAL) {
      return;
    }

    const onWindowReady = () => {
      if (!win.gBrowser || win.closed) {
        return;
      }
      if (
        !InfoBar._activeInfobar ||
        InfoBar._activeInfobar.message !== message
      ) {
        return;
      }
      this.showInfoBarMessage(
        win.gBrowser.selectedBrowser,
        message,
        dispatch,
        true
      );
    };

    if (win.document?.readyState === "complete") {
      onWindowReady();
    } else {
      win.addEventListener("load", onWindowReady, { once: true });
    }
  },
};