summaryrefslogtreecommitdiffstats
path: root/browser/actors/LightweightThemeChild.sys.mjs
blob: 97be44511cd336444edb92987385f83163474960 (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
/* 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/. */

/**
 * LightweightThemeChild forwards theme data to in-content pages.
 */
export class LightweightThemeChild extends JSWindowActorChild {
  constructor() {
    super();
    this._initted = false;
    Services.cpmm.sharedData.addEventListener("change", this);
  }

  didDestroy() {
    Services.cpmm.sharedData.removeEventListener("change", this);
  }

  _getChromeOuterWindowID() {
    try {
      // Getting the browserChild throws an exception when it is null.
      let browserChild = this.docShell.browserChild;
      if (browserChild) {
        return browserChild.chromeOuterWindowID;
      }
    } catch (ex) {}

    if (
      Services.appinfo.processType === Services.appinfo.PROCESS_TYPE_DEFAULT
    ) {
      return this.browsingContext.topChromeWindow.docShell.outerWindowID;
    }

    // Return a false-y outerWindowID if we can't manage to get a proper one.
    // Note that no outerWindowID will ever have this ID.
    return 0;
  }

  /**
   * Handles "change" events on the child sharedData map, and notifies
   * our content page if its theme data was among the changed keys.
   */
  handleEvent(event) {
    switch (event.type) {
      // Make sure to update the theme data on first page show.
      case "pageshow":
      case "DOMContentLoaded":
        if (!this._initted && this._getChromeOuterWindowID()) {
          this._initted = true;
          this.update();
        }
        break;

      case "change":
        if (
          event.changedKeys.includes(`theme/${this._getChromeOuterWindowID()}`)
        ) {
          this.update();
        }
        break;
    }
  }

  /**
   * Forward the theme data to the page.
   */
  update() {
    const event = Cu.cloneInto(
      {
        detail: {
          data: Services.cpmm.sharedData.get(
            `theme/${this._getChromeOuterWindowID()}`
          ),
        },
      },
      this.contentWindow
    );
    this.contentWindow.dispatchEvent(
      new this.contentWindow.CustomEvent("LightweightTheme:Set", event)
    );
  }
}