tening() {
    if (this.#listening) {
      return;
    }

    Services.ww.registerNotification(this);

    this.#contextListener.on("discarded", this.#onContextDiscarded);
    this.#contextListener.startListening();

    this.#listening = true;
  }

  stopListening() {
    if (!this.#listening) {
      return;
    }

    this.#contextListener.off("discarded", this.#onContextDiscarded);
    this.#contextListener.stopListening();

    Services.ww.unregisterNotification(this);

    this.#closingWindows = new WeakSet();
    this.#listening = false;
  }

  #onContextDiscarded = (_, data = {}) => {
    const { browsingContext } = data;

    if (browsingContext.isContent || browsingContext.parent) {
      // We only care about top-level chrome browsing contexts
      return;
    }

    const window = browsingContext.topChromeWindow;
    if (this.#closingWindows.has(window)) {
      this.#closingWindows.delete(window);

      this.emit("closed", { window });
    }
  };
}
PK