summaryrefslogtreecommitdiffstats
path: root/browser/extensions/formautofill/api.js
blob: 967b4a8d63c769394e3c5e99b4fbf7d140fb15a5 (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
/* 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 ExtensionAPI, Services, XPCOMUtils */

const CACHED_STYLESHEETS = new WeakMap();

ChromeUtils.defineESModuleGetters(this, {
  FormAutofill: "resource://autofill/FormAutofill.sys.mjs",
  FormAutofillParent: "resource://autofill/FormAutofillParent.sys.mjs",
  FormAutofillStatus: "resource://autofill/FormAutofillParent.sys.mjs",
  AutoCompleteParent: "resource://gre/actors/AutoCompleteParent.sys.mjs",
});

XPCOMUtils.defineLazyServiceGetter(
  this,
  "resProto",
  "@mozilla.org/network/protocol;1?name=resource",
  "nsISubstitutingProtocolHandler"
);

const RESOURCE_HOST = "formautofill";

function insertStyleSheet(domWindow, url) {
  let doc = domWindow.document;
  let styleSheetAttr = `href="${url}" type="text/css"`;
  let styleSheet = doc.createProcessingInstruction(
    "xml-stylesheet",
    styleSheetAttr
  );

  doc.insertBefore(styleSheet, doc.documentElement);

  if (CACHED_STYLESHEETS.has(domWindow)) {
    CACHED_STYLESHEETS.get(domWindow).push(styleSheet);
  } else {
    CACHED_STYLESHEETS.set(domWindow, [styleSheet]);
  }
}

function ensureCssLoaded(domWindow) {
  if (CACHED_STYLESHEETS.has(domWindow)) {
    // This window already has autofill stylesheets.
    return;
  }

  insertStyleSheet(domWindow, "chrome://formautofill/content/formautofill.css");
  insertStyleSheet(
    domWindow,
    "chrome://formautofill/content/skin/autocomplete-item-shared.css"
  );
  insertStyleSheet(
    domWindow,
    "chrome://formautofill/content/skin/autocomplete-item.css"
  );
}

this.formautofill = class extends ExtensionAPI {
  /**
   * Adjusts and checks form autofill preferences during startup.
   *
   * @param {boolean} addressAutofillAvailable
   * @param {boolean} creditCardAutofillAvailable
   */
  adjustAndCheckFormAutofillPrefs(
    addressAutofillAvailable,
    creditCardAutofillAvailable
  ) {
    // Reset the sync prefs in case the features were previously available
    // but aren't now.
    if (!creditCardAutofillAvailable) {
      Services.prefs.clearUserPref(
        "services.sync.engine.creditcards.available"
      );
    }
    if (!addressAutofillAvailable) {
      Services.prefs.clearUserPref("services.sync.engine.addresses.available");
    }

    if (!addressAutofillAvailable && !creditCardAutofillAvailable) {
      Services.prefs.clearUserPref("dom.forms.autocomplete.formautofill");
      Services.telemetry.scalarSet("formautofill.availability", false);
      return;
    }

    // This pref is used for web contents to detect the autocomplete feature.
    // When it's true, "element.autocomplete" will return tokens we currently
    // support -- otherwise it'll return an empty string.
    Services.prefs.setBoolPref("dom.forms.autocomplete.formautofill", true);
    Services.telemetry.scalarSet("formautofill.availability", true);

    // These "*.available" prefs determines whether the "addresses"/"creditcards" sync engine is
    // available (ie, whether it is shown in any UI etc) - it *does not* determine
    // whether the engine is actually enabled or not.
    if (FormAutofill.isAutofillAddressesAvailable) {
      Services.prefs.setBoolPref(
        "services.sync.engine.addresses.available",
        true
      );
    } else {
      Services.prefs.clearUserPref("services.sync.engine.addresses.available");
    }
    if (FormAutofill.isAutofillCreditCardsAvailable) {
      Services.prefs.setBoolPref(
        "services.sync.engine.creditcards.available",
        true
      );
    } else {
      Services.prefs.clearUserPref(
        "services.sync.engine.creditcards.available"
      );
    }
  }
  onStartup() {
    // We have to do this before actually determining if we're enabled, since
    // there are scripts inside of the core browser code that depend on the
    // FormAutofill JSMs being registered.
    let uri = Services.io.newURI("chrome/res/", null, this.extension.rootURI);
    resProto.setSubstitution(RESOURCE_HOST, uri);

    let aomStartup = Cc[
      "@mozilla.org/addons/addon-manager-startup;1"
    ].getService(Ci.amIAddonManagerStartup);
    const manifestURI = Services.io.newURI(
      "manifest.json",
      null,
      this.extension.rootURI
    );
    this.chromeHandle = aomStartup.registerChrome(manifestURI, [
      ["content", "formautofill", "chrome/content/"],
    ]);

    // Until we move to fluent (bug 1446164), we're stuck with
    // chrome.manifest for handling localization since its what the
    // build system can handle for localized repacks.
    if (this.extension.rootURI instanceof Ci.nsIJARURI) {
      this.autofillManifest = this.extension.rootURI.JARFile.QueryInterface(
        Ci.nsIFileURL
      ).file;
    } else if (this.extension.rootURI instanceof Ci.nsIFileURL) {
      this.autofillManifest = this.extension.rootURI.file;
    }

    if (this.autofillManifest) {
      Components.manager.addBootstrappedManifestLocation(this.autofillManifest);
    } else {
      console.error(
        "Cannot find formautofill chrome.manifest for registring translated strings"
      );
    }
    let addressAutofillAvailable = FormAutofill.isAutofillAddressesAvailable;
    let creditCardAutofillAvailable =
      FormAutofill.isAutofillCreditCardsAvailable;
    this.adjustAndCheckFormAutofillPrefs(
      addressAutofillAvailable,
      creditCardAutofillAvailable
    );
    if (!creditCardAutofillAvailable && !addressAutofillAvailable) {
      return;
    }
    // Listen for the autocomplete popup message
    // or the form submitted message (which may trigger a
    // doorhanger) to lazily append our stylesheets related
    // to the autocomplete feature.
    AutoCompleteParent.addPopupStateListener(ensureCssLoaded);
    FormAutofillParent.addMessageObserver(this);
    this.onFormSubmitted = (data, window) => ensureCssLoaded(window);

    FormAutofillStatus.init();

    ChromeUtils.registerWindowActor("FormAutofill", {
      parent: {
        esModuleURI: "resource://autofill/FormAutofillParent.sys.mjs",
      },
      child: {
        esModuleURI: "resource://autofill/FormAutofillChild.sys.mjs",
        events: {
          focusin: {},
          "form-submission-detected": {},
        },
      },
      allFrames: true,
    });
  }

  onShutdown(isAppShutdown) {
    if (isAppShutdown) {
      return;
    }

    resProto.setSubstitution(RESOURCE_HOST, null);

    this.chromeHandle.destruct();
    this.chromeHandle = null;

    if (this.autofillManifest) {
      Components.manager.removeBootstrappedManifestLocation(
        this.autofillManifest
      );
    }

    ChromeUtils.unregisterWindowActor("FormAutofill");

    AutoCompleteParent.removePopupStateListener(ensureCssLoaded);
    FormAutofillParent.removeMessageObserver(this);

    for (let win of Services.wm.getEnumerator("navigator:browser")) {
      let cachedStyleSheets = CACHED_STYLESHEETS.get(win);

      if (!cachedStyleSheets) {
        continue;
      }

      while (cachedStyleSheets.length !== 0) {
        cachedStyleSheets.pop().remove();
      }
    }
  }
};