summaryrefslogtreecommitdiffstats
path: root/browser/extensions/webcompat/lib/injections.js
blob: 92fdc5fbb38796696e4d89eedf980cfe90d1ef49 (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
/* 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/. */

"use strict";

/* globals browser, module */

class Injections {
  constructor(availableInjections, customFunctions) {
    this.INJECTION_PREF = "perform_injections";

    this._injectionsEnabled = true;

    this._availableInjections = availableInjections;
    this._activeInjections = new Set();
    // Only used if this.shouldUseScriptingAPI is false and we are falling back
    // to use the contentScripts API.
    this._activeInjectionHandles = new Map();
    this._customFunctions = customFunctions;

    this.shouldUseScriptingAPI =
      browser.aboutConfigPrefs.getBoolPrefSync("useScriptingAPI");
    // Debug log emit only on nightly (similarly to the debug
    // helper used in shims.js for similar purpose).
    browser.appConstants.getReleaseBranch().then(releaseBranch => {
      if (releaseBranch !== "release_or_beta") {
        console.debug(
          `WebCompat Injections will be injected using ${
            this.shouldUseScriptingAPI ? "scripting" : "contentScripts"
          } API`
        );
      }
    });
  }

  bindAboutCompatBroker(broker) {
    this._aboutCompatBroker = broker;
  }

  bootup() {
    browser.aboutConfigPrefs.onPrefChange.addListener(() => {
      this.checkInjectionPref();
    }, this.INJECTION_PREF);
    this.checkInjectionPref();
  }

  checkInjectionPref() {
    browser.aboutConfigPrefs.getPref(this.INJECTION_PREF).then(value => {
      if (value === undefined) {
        browser.aboutConfigPrefs.setPref(this.INJECTION_PREF, true);
      } else if (value === false) {
        this.unregisterContentScripts();
      } else {
        this.registerContentScripts();
      }
    });
  }

  getAvailableInjections() {
    return this._availableInjections;
  }

  isEnabled() {
    return this._injectionsEnabled;
  }

  async getPromiseRegisteredScriptIds(scriptIds) {
    let registeredScriptIds = [];

    // Try to avoid re-registering scripts already registered
    // (e.g. if the webcompat background page is restarted
    // after an extension process crash, after having registered
    // the content scripts already once), but do not prevent
    // to try registering them again if the getRegisteredContentScripts
    // method returns an unexpected rejection.
    try {
      const registeredScripts =
        await browser.scripting.getRegisteredContentScripts({
          // By default only look for script ids that belongs to Injections
          // (and ignore the ones that may belong to Shims).
          ids: scriptIds ?? this._availableInjections.map(inj => inj.id),
        });
      registeredScriptIds = registeredScripts.map(script => script.id);
    } catch (ex) {
      console.error(
        "Retrieve WebCompat GoFaster registered content scripts failed: ",
        ex
      );
    }

    return registeredScriptIds;
  }

  async registerContentScripts() {
    const platformInfo = await browser.runtime.getPlatformInfo();
    const platformMatches = [
      "all",
      platformInfo.os,
      platformInfo.os == "android" ? "android" : "desktop",
    ];

    let registeredScriptIds = this.shouldUseScriptingAPI
      ? await this.getPromiseRegisteredScriptIds()
      : [];

    for (const injection of this._availableInjections) {
      if (platformMatches.includes(injection.platform)) {
        injection.availableOnPlatform = true;
        await this.enableInjection(injection, registeredScriptIds);
      }
    }

    this._injectionsEnabled = true;
    this._aboutCompatBroker.portsToAboutCompatTabs.broadcast({
      interventionsChanged: this._aboutCompatBroker.filterOverrides(
        this._availableInjections
      ),
    });
  }

  buildContentScriptRegistrations(contentScripts) {
    let finalConfig = Object.assign({}, contentScripts);

    if (!finalConfig.runAt) {
      finalConfig.runAt = "document_start";
    }

    if (this.shouldUseScriptingAPI) {
      // Don't persist the content scripts across browser restarts
      // (at least not yet, we would need to apply some more changes
      // to adjust webcompat for accounting for the scripts to be
      // already registered).
      //
      // NOTE: scripting API has been introduced in Gecko 102,
      // prior to Gecko 105 persistAcrossSessions option was required
      // and only accepted false persistAcrossSessions, after Gecko 105
      // is optional and defaults to true.

      finalConfig.persistAcrossSessions = false;

      // Convert js/css from contentScripts.register API method
      // format to scripting.registerContentScripts API method
      // format.
      if (Array.isArray(finalConfig.js)) {
        finalConfig.js = finalConfig.js.map(e => e.file);
      }

      if (Array.isArray(finalConfig.css)) {
        finalConfig.css = finalConfig.css.map(e => e.file);
      }
    }

    return finalConfig;
  }

  async enableInjection(injection, registeredScriptIds) {
    if (injection.active) {
      return undefined;
    }

    if (injection.customFunc) {
      return this.enableCustomInjection(injection);
    }

    return this.enableContentScripts(injection, registeredScriptIds);
  }

  enableCustomInjection(injection) {
    if (injection.customFunc in this._customFunctions) {
      this._customFunctions[injection.customFunc](injection);
      injection.active = true;
    } else {
      console.error(
        `Provided function ${injection.customFunc} wasn't found in functions list`
      );
    }
  }

  async enableContentScripts(injection, registeredScriptIds) {
    let injectProps;
    try {
      const { id } = injection;
      if (this.shouldUseScriptingAPI) {
        // enableContentScripts receives a registeredScriptIds already
        // pre-computed once from registerContentScripts to register all
        // the injection, whereas it does not expect to receive one when
        // it is called from the AboutCompatBroker to re-enable one specific
        // injection.
        let activeScriptIds = Array.isArray(registeredScriptIds)
          ? registeredScriptIds
          : await this.getPromiseRegisteredScriptIds([id]);
        injectProps = this.buildContentScriptRegistrations(
          injection.contentScripts
        );
        injectProps.id = id;
        if (!activeScriptIds.includes(id)) {
          await browser.scripting.registerContentScripts([injectProps]);
        }
        this._activeInjections.add(id);
      } else {
        const handle = await browser.contentScripts.register(
          this.buildContentScriptRegistrations(injection.contentScripts)
        );
        this._activeInjections.add(id);
        this._activeInjectionHandles.set(id, handle);
      }

      injection.active = true;
    } catch (ex) {
      console.error(
        "Registering WebCompat GoFaster content scripts failed: ",
        { injection, injectProps },
        ex
      );
    }
  }

  unregisterContentScripts() {
    for (const injection of this._availableInjections) {
      this.disableInjection(injection);
    }

    this._injectionsEnabled = false;
    this._aboutCompatBroker.portsToAboutCompatTabs.broadcast({
      interventionsChanged: false,
    });
  }

  async disableInjection(injection) {
    if (!injection.active) {
      return undefined;
    }

    if (injection.customFunc) {
      return this.disableCustomInjections(injection);
    }

    return this.disableContentScripts(injection);
  }

  disableCustomInjections(injection) {
    const disableFunc = injection.customFunc + "Disable";

    if (disableFunc in this._customFunctions) {
      this._customFunctions[disableFunc](injection);
      injection.active = false;
    } else {
      console.error(
        `Provided function ${disableFunc} for disabling injection wasn't found in functions list`
      );
    }
  }

  async disableContentScripts(injection) {
    if (this._activeInjections.has(injection.id)) {
      if (this.shouldUseScriptingAPI) {
        await browser.scripting.unregisterContentScripts({
          ids: [injection.id],
        });
      } else {
        const handle = this._activeInjectionHandles.get(injection.id);
        await handle.unregister();
        this._activeInjectionHandles.delete(injection.id);
      }
      this._activeInjections.delete(injection);
    }
    injection.active = false;
  }
}

module.exports = Injections;