1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";
6 import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
10 ChromeUtils.defineESModuleGetters(lazy, {
11 AboutNewTab: "resource:///modules/AboutNewTab.sys.mjs",
12 AWToolbarButton: "resource:///modules/aboutwelcome/AWToolbarUtils.sys.mjs",
13 ASRouter: "resource:///modules/asrouter/ASRouter.sys.mjs",
14 ASRouterDefaultConfig:
15 "resource:///modules/asrouter/ASRouterDefaultConfig.sys.mjs",
16 ASRouterNewTabHook: "resource:///modules/asrouter/ASRouterNewTabHook.sys.mjs",
17 ActorManagerParent: "resource://gre/modules/ActorManagerParent.sys.mjs",
18 AddonManager: "resource://gre/modules/AddonManager.sys.mjs",
19 AppMenuNotifications: "resource://gre/modules/AppMenuNotifications.sys.mjs",
20 AsyncShutdown: "resource://gre/modules/AsyncShutdown.sys.mjs",
21 BackupService: "resource:///modules/backup/BackupService.sys.mjs",
22 Blocklist: "resource://gre/modules/Blocklist.sys.mjs",
23 BookmarkHTMLUtils: "resource://gre/modules/BookmarkHTMLUtils.sys.mjs",
24 BookmarkJSONUtils: "resource://gre/modules/BookmarkJSONUtils.sys.mjs",
25 BrowserSearchTelemetry: "resource:///modules/BrowserSearchTelemetry.sys.mjs",
26 BrowserUIUtils: "resource:///modules/BrowserUIUtils.sys.mjs",
27 BrowserUsageTelemetry: "resource:///modules/BrowserUsageTelemetry.sys.mjs",
28 BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.sys.mjs",
29 BuiltInThemes: "resource:///modules/BuiltInThemes.sys.mjs",
30 ContextualIdentityService:
31 "resource://gre/modules/ContextualIdentityService.sys.mjs",
32 Corroborate: "resource://gre/modules/Corroborate.sys.mjs",
33 DAPTelemetrySender: "resource://gre/modules/DAPTelemetrySender.sys.mjs",
34 DeferredTask: "resource://gre/modules/DeferredTask.sys.mjs",
35 Discovery: "resource:///modules/Discovery.sys.mjs",
36 DoHController: "resource:///modules/DoHController.sys.mjs",
37 DownloadsViewableInternally:
38 "resource:///modules/DownloadsViewableInternally.sys.mjs",
39 E10SUtils: "resource://gre/modules/E10SUtils.sys.mjs",
40 ExtensionsUI: "resource:///modules/ExtensionsUI.sys.mjs",
41 FeatureGate: "resource://featuregates/FeatureGate.sys.mjs",
42 FirefoxBridgeExtensionUtils:
43 "resource:///modules/FirefoxBridgeExtensionUtils.sys.mjs",
44 FxAccounts: "resource://gre/modules/FxAccounts.sys.mjs",
45 HomePage: "resource:///modules/HomePage.sys.mjs",
46 Integration: "resource://gre/modules/Integration.sys.mjs",
47 Interactions: "resource:///modules/Interactions.sys.mjs",
48 LoginBreaches: "resource:///modules/LoginBreaches.sys.mjs",
49 MigrationUtils: "resource:///modules/MigrationUtils.sys.mjs",
50 NetUtil: "resource://gre/modules/NetUtil.sys.mjs",
51 NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
52 NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
53 Normandy: "resource://normandy/Normandy.sys.mjs",
54 OnboardingMessageProvider:
55 "resource:///modules/asrouter/OnboardingMessageProvider.sys.mjs",
56 OsEnvironment: "resource://gre/modules/OsEnvironment.sys.mjs",
57 PageActions: "resource:///modules/PageActions.sys.mjs",
58 PageDataService: "resource:///modules/pagedata/PageDataService.sys.mjs",
59 PageThumbs: "resource://gre/modules/PageThumbs.sys.mjs",
60 PdfJs: "resource://pdf.js/PdfJs.sys.mjs",
61 PermissionUI: "resource:///modules/PermissionUI.sys.mjs",
62 PlacesBackups: "resource://gre/modules/PlacesBackups.sys.mjs",
63 PlacesDBUtils: "resource://gre/modules/PlacesDBUtils.sys.mjs",
64 PlacesUIUtils: "resource:///modules/PlacesUIUtils.sys.mjs",
65 PlacesUtils: "resource://gre/modules/PlacesUtils.sys.mjs",
66 // PluginManager is used by listeners object below.
67 // eslint-disable-next-line mozilla/valid-lazy
68 PluginManager: "resource:///actors/PluginParent.sys.mjs",
69 PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
70 ProcessHangMonitor: "resource:///modules/ProcessHangMonitor.sys.mjs",
72 "resource://gre/modules/netwerk-dns/PublicSuffixList.sys.mjs",
73 QuickSuggest: "resource:///modules/QuickSuggest.sys.mjs",
74 RFPHelper: "resource://gre/modules/RFPHelper.sys.mjs",
75 RemoteSecuritySettings:
76 "resource://gre/modules/psm/RemoteSecuritySettings.sys.mjs",
77 RemoteSettings: "resource://services-settings/remote-settings.sys.mjs",
78 ResetPBMPanel: "resource:///modules/ResetPBMPanel.sys.mjs",
79 SafeBrowsing: "resource://gre/modules/SafeBrowsing.sys.mjs",
80 Sanitizer: "resource:///modules/Sanitizer.sys.mjs",
81 SaveToPocket: "chrome://pocket/content/SaveToPocket.sys.mjs",
82 ScreenshotsUtils: "resource:///modules/ScreenshotsUtils.sys.mjs",
83 SearchSERPDomainToCategoriesMap:
84 "resource:///modules/SearchSERPTelemetry.sys.mjs",
85 SearchSERPTelemetry: "resource:///modules/SearchSERPTelemetry.sys.mjs",
86 SessionStartup: "resource:///modules/sessionstore/SessionStartup.sys.mjs",
87 SessionStore: "resource:///modules/sessionstore/SessionStore.sys.mjs",
88 ShellService: "resource:///modules/ShellService.sys.mjs",
89 ShortcutUtils: "resource://gre/modules/ShortcutUtils.sys.mjs",
90 ShoppingUtils: "resource:///modules/ShoppingUtils.sys.mjs",
91 SpecialMessageActions:
92 "resource://messaging-system/lib/SpecialMessageActions.sys.mjs",
93 TRRRacer: "resource:///modules/TRRPerformance.sys.mjs",
94 TabCrashHandler: "resource:///modules/ContentCrashHandlers.sys.mjs",
95 TabUnloader: "resource:///modules/TabUnloader.sys.mjs",
96 TelemetryUtils: "resource://gre/modules/TelemetryUtils.sys.mjs",
97 UIState: "resource://services-sync/UIState.sys.mjs",
98 UrlbarPrefs: "resource:///modules/UrlbarPrefs.sys.mjs",
99 WebChannel: "resource://gre/modules/WebChannel.sys.mjs",
100 WindowsLaunchOnLogin: "resource://gre/modules/WindowsLaunchOnLogin.sys.mjs",
101 WindowsRegistry: "resource://gre/modules/WindowsRegistry.sys.mjs",
102 WindowsGPOParser: "resource://gre/modules/policies/WindowsGPOParser.sys.mjs",
103 clearTimeout: "resource://gre/modules/Timer.sys.mjs",
104 setTimeout: "resource://gre/modules/Timer.sys.mjs",
107 if (AppConstants.MOZ_UPDATER) {
108 ChromeUtils.defineESModuleGetters(lazy, {
109 UpdateListener: "resource://gre/modules/UpdateListener.sys.mjs",
112 if (AppConstants.MOZ_UPDATE_AGENT) {
113 ChromeUtils.defineESModuleGetters(lazy, {
114 BackgroundUpdate: "resource://gre/modules/BackgroundUpdate.sys.mjs",
118 // PluginManager is used in the listeners object below.
119 XPCOMUtils.defineLazyServiceGetters(lazy, {
120 BrowserHandler: ["@mozilla.org/browser/clh;1", "nsIBrowserHandler"],
121 PushService: ["@mozilla.org/push/Service;1", "nsIPushService"],
124 ChromeUtils.defineLazyGetter(
129 ["browser/accounts.ftl", "toolkit/branding/accounts.ftl"],
134 if (AppConstants.ENABLE_WEBDRIVER) {
135 XPCOMUtils.defineLazyServiceGetter(
138 "@mozilla.org/remote/marionette;1",
142 XPCOMUtils.defineLazyServiceGetter(
145 "@mozilla.org/remote/agent;1",
149 lazy.Marionette = { running: false };
150 lazy.RemoteAgent = { running: false };
153 const PREF_PDFJS_ISDEFAULT_CACHE_STATE = "pdfjs.enabledCache.state";
155 const PRIVATE_BROWSING_BINARY = "private_browsing.exe";
156 // Index of Private Browsing icon in private_browsing.exe
157 // Must line up with IDI_PBICON_PB_PB_EXE in nsNativeAppSupportWin.h.
158 const PRIVATE_BROWSING_EXE_ICON_INDEX = 1;
159 const PREF_PRIVATE_BROWSING_SHORTCUT_CREATED =
160 "browser.privacySegmentation.createdShortcut";
161 // Whether this launch was initiated by the OS. A launch-on-login will contain
162 // the "os-autostart" flag in the initial launch command line.
163 let gThisInstanceIsLaunchOnLogin = false;
164 // Whether this launch was initiated by a taskbar tab shortcut. A launch from
165 // a taskbar tab shortcut will contain the "taskbar-tab" flag.
166 let gThisInstanceIsTaskbarTab = false;
169 * Fission-compatible JSProcess implementations.
170 * Each actor options object takes the form of a ProcessActorOptions dictionary.
171 * Detailed documentation of these options is in dom/docs/ipc/jsactors.rst,
172 * available at https://firefox-source-docs.mozilla.org/dom/ipc/jsactors.html
174 let JSPROCESSACTORS = {
175 // Miscellaneous stuff that needs to be initialized per process.
178 esModuleURI: "resource:///actors/BrowserProcessChild.sys.mjs",
180 // WebRTC related notifications. They are here to avoid loading WebRTC
181 // components when not needed.
182 "getUserMedia:request",
183 "recording-device-stopped",
184 "PeerConnection:request",
185 "recording-device-events",
186 "recording-window-ended",
191 RefreshBlockerObserver: {
193 esModuleURI: "resource:///actors/RefreshBlockerChild.sys.mjs",
195 "webnavigation-create",
196 "chrome-webnavigation-create",
197 "webnavigation-destroy",
198 "chrome-webnavigation-destroy",
202 enablePreference: "accessibility.blockautorefresh",
203 onPreferenceChanged: (prefName, prevValue, isEnabled) => {
204 lazy.BrowserWindowTracker.orderedWindows.forEach(win => {
205 for (let browser of win.gBrowser.browsers) {
207 browser.sendMessageToActor(
221 * Fission-compatible JSWindowActor implementations.
222 * Detailed documentation of these options is in dom/docs/ipc/jsactors.rst,
223 * available at https://firefox-source-docs.mozilla.org/dom/ipc/jsactors.html
225 let JSWINDOWACTORS = {
228 esModuleURI: "resource:///actors/AboutLoginsParent.sys.mjs",
231 esModuleURI: "resource:///actors/AboutLoginsChild.sys.mjs",
233 AboutLoginsCopyLoginDetail: { wantUntrusted: true },
234 AboutLoginsCreateLogin: { wantUntrusted: true },
235 AboutLoginsDeleteLogin: { wantUntrusted: true },
236 AboutLoginsDismissBreachAlert: { wantUntrusted: true },
237 AboutLoginsImportFromBrowser: { wantUntrusted: true },
238 AboutLoginsImportFromFile: { wantUntrusted: true },
239 AboutLoginsImportReportInit: { wantUntrusted: true },
240 AboutLoginsImportReportReady: { wantUntrusted: true },
241 AboutLoginsInit: { wantUntrusted: true },
242 AboutLoginsGetHelp: { wantUntrusted: true },
243 AboutLoginsOpenPreferences: { wantUntrusted: true },
244 AboutLoginsOpenSite: { wantUntrusted: true },
245 AboutLoginsRecordTelemetryEvent: { wantUntrusted: true },
246 AboutLoginsRemoveAllLogins: { wantUntrusted: true },
247 AboutLoginsSortChanged: { wantUntrusted: true },
248 AboutLoginsSyncEnable: { wantUntrusted: true },
249 AboutLoginsSyncOptions: { wantUntrusted: true },
250 AboutLoginsUpdateLogin: { wantUntrusted: true },
251 AboutLoginsExportPasswords: { wantUntrusted: true },
254 matches: ["about:logins", "about:logins?*", "about:loginsimportreport"],
256 remoteTypes: ["privilegedabout"],
259 AboutMessagePreview: {
261 esModuleURI: "resource:///actors/AboutMessagePreviewParent.sys.mjs",
264 esModuleURI: "resource:///actors/AboutMessagePreviewChild.sys.mjs",
266 DOMDocElementInserted: { capture: true },
269 matches: ["about:messagepreview", "about:messagepreview?*"],
274 esModuleURI: "resource:///actors/AboutNewTabParent.sys.mjs",
277 esModuleURI: "resource:///actors/AboutNewTabChild.sys.mjs",
279 DOMDocElementInserted: {},
280 DOMContentLoaded: {},
281 load: { capture: true },
282 unload: { capture: true },
284 visibilitychange: {},
287 // The wildcard on about:newtab is for the # parameter
288 // that is used for the newtab devtools. The wildcard for about:home
289 // is similar, and also allows for falling back to loading the
290 // about:home document dynamically if an attempt is made to load
291 // about:home?jscache from the AboutHomeStartupCache as a top-level
293 matches: ["about:home*", "about:welcome", "about:newtab*"],
294 remoteTypes: ["privilegedabout"],
299 esModuleURI: "resource:///actors/AboutPocketParent.sys.mjs",
302 esModuleURI: "resource:///actors/AboutPocketChild.sys.mjs",
305 DOMDocElementInserted: { capture: true },
309 remoteTypes: ["privilegedabout"],
311 "about:pocket-saved*",
312 "about:pocket-signup*",
313 "about:pocket-home*",
314 "about:pocket-style-guide*",
318 AboutPrivateBrowsing: {
320 esModuleURI: "resource:///actors/AboutPrivateBrowsingParent.sys.mjs",
323 esModuleURI: "resource:///actors/AboutPrivateBrowsingChild.sys.mjs",
326 DOMDocElementInserted: { capture: true },
330 matches: ["about:privatebrowsing*"],
335 esModuleURI: "resource:///actors/AboutProtectionsParent.sys.mjs",
338 esModuleURI: "resource:///actors/AboutProtectionsChild.sys.mjs",
341 DOMDocElementInserted: { capture: true },
345 matches: ["about:protections", "about:protections?*"],
350 esModuleURI: "resource:///actors/AboutReaderParent.sys.mjs",
353 esModuleURI: "resource:///actors/AboutReaderChild.sys.mjs",
355 DOMContentLoaded: {},
356 pageshow: { mozSystemGroup: true },
357 // Don't try to create the actor if only the pagehide event fires.
358 // This can happen with the initial about:blank documents.
359 pagehide: { mozSystemGroup: true, createActor: false },
362 messageManagerGroups: ["browsers"],
367 esModuleURI: "resource:///actors/AboutTabCrashedParent.sys.mjs",
370 esModuleURI: "resource:///actors/AboutTabCrashedChild.sys.mjs",
372 DOMDocElementInserted: { capture: true },
376 matches: ["about:tabcrashed*"],
379 AboutWelcomeShopping: {
381 esModuleURI: "resource:///actors/AboutWelcomeParent.sys.mjs",
384 esModuleURI: "resource:///actors/AboutWelcomeChild.sys.mjs",
389 matches: ["about:shoppingsidebar"],
390 remoteTypes: ["privilegedabout"],
395 esModuleURI: "resource:///actors/AboutWelcomeParent.sys.mjs",
398 esModuleURI: "resource:///actors/AboutWelcomeChild.sys.mjs",
400 // This is added so the actor instantiates immediately and makes
401 // methods available to the page js on load.
402 DOMDocElementInserted: {},
405 matches: ["about:welcome"],
406 remoteTypes: ["privilegedabout"],
409 // Remove this preference check when we turn on separate about:welcome for all users.
410 enablePreference: "browser.aboutwelcome.enabled",
415 esModuleURI: "resource:///actors/BlockedSiteParent.sys.mjs",
418 esModuleURI: "resource:///actors/BlockedSiteChild.sys.mjs",
420 AboutBlockedLoaded: { wantUntrusted: true },
424 matches: ["about:blocked?*"],
430 esModuleURI: "resource:///actors/BrowserTabChild.sys.mjs",
433 messageManagerGroups: ["browsers"],
438 esModuleURI: "resource:///actors/ClickHandlerParent.sys.mjs",
441 esModuleURI: "resource:///actors/ClickHandlerChild.sys.mjs",
443 chromelinkclick: { capture: true, mozSystemGroup: true },
450 /* Note: this uses the same JSMs as ClickHandler, but because it
451 * relies on "normal" click events anywhere on the page (not just
452 * links) and is expensive, and only does something for the
453 * small group of people who have the feature enabled, it is its
454 * own actor which is only registered if the pref is enabled.
456 MiddleMousePasteHandler: {
458 esModuleURI: "resource:///actors/ClickHandlerParent.sys.mjs",
461 esModuleURI: "resource:///actors/ClickHandlerChild.sys.mjs",
463 auxclick: { capture: true, mozSystemGroup: true },
466 enablePreference: "middlemouse.contentLoadURL",
473 esModuleURI: "resource:///actors/ContentSearchParent.sys.mjs",
476 esModuleURI: "resource:///actors/ContentSearchChild.sys.mjs",
478 ContentSearchClient: { capture: true, wantUntrusted: true },
485 "about:privatebrowsing",
486 "about:test-about-content-search-ui",
488 remoteTypes: ["privilegedabout"],
493 esModuleURI: "resource:///actors/ContextMenuParent.sys.mjs",
497 esModuleURI: "resource:///actors/ContextMenuChild.sys.mjs",
499 contextmenu: { mozSystemGroup: true },
508 esModuleURI: "resource:///actors/DecoderDoctorParent.sys.mjs",
512 esModuleURI: "resource:///actors/DecoderDoctorChild.sys.mjs",
513 observers: ["decoder-doctor-notification"],
516 messageManagerGroups: ["browsers"],
522 esModuleURI: "resource:///actors/DOMFullscreenParent.sys.mjs",
526 esModuleURI: "resource:///actors/DOMFullscreenChild.sys.mjs",
528 "MozDOMFullscreen:Request": {},
529 "MozDOMFullscreen:Entered": {},
530 "MozDOMFullscreen:NewOrigin": {},
531 "MozDOMFullscreen:Exit": {},
532 "MozDOMFullscreen:Exited": {},
536 messageManagerGroups: ["browsers"],
542 esModuleURI: "resource:///actors/EncryptedMediaParent.sys.mjs",
546 esModuleURI: "resource:///actors/EncryptedMediaChild.sys.mjs",
547 observers: ["mediakeys-request"],
550 messageManagerGroups: ["browsers"],
556 esModuleURI: "resource:///actors/FormValidationParent.sys.mjs",
560 esModuleURI: "resource:///actors/FormValidationChild.sys.mjs",
563 // Listening to ‘pageshow’ event is only relevant if an invalid form
564 // popup was open, so don't create the actor when fired.
565 pageshow: { createActor: false },
574 esModuleURI: "resource:///actors/LightweightThemeChild.sys.mjs",
576 pageshow: { mozSystemGroup: true },
577 DOMContentLoaded: {},
587 "chrome://browser/content/syncedtabs/sidebar.xhtml",
588 "chrome://browser/content/places/historySidebar.xhtml",
589 "chrome://browser/content/places/bookmarksSidebar.xhtml",
596 esModuleURI: "resource:///actors/LinkHandlerParent.sys.mjs",
599 esModuleURI: "resource:///actors/LinkHandlerChild.sys.mjs",
601 DOMHeadElementParsed: {},
605 // The `pagehide` event is only used to clean up state which will not be
606 // present if the actor hasn't been created.
607 pagehide: { createActor: false },
611 messageManagerGroups: ["browsers"],
616 esModuleURI: "resource:///actors/PageInfoChild.sys.mjs",
624 esModuleURI: "resource:///actors/PageStyleParent.sys.mjs",
627 esModuleURI: "resource:///actors/PageStyleChild.sys.mjs",
629 pageshow: { createActor: false },
633 messageManagerGroups: ["browsers"],
639 esModuleURI: "resource://pdf.js/PdfjsParent.sys.mjs",
642 esModuleURI: "resource://pdf.js/PdfjsChild.sys.mjs",
647 // GMP crash reporting
650 esModuleURI: "resource:///actors/PluginParent.sys.mjs",
653 esModuleURI: "resource:///actors/PluginChild.sys.mjs",
655 PluginCrashed: { capture: true },
664 esModuleURI: "resource:///actors/PointerLockParent.sys.mjs",
667 esModuleURI: "resource:///actors/PointerLockChild.sys.mjs",
669 "MozDOMPointerLock:Entered": {},
670 "MozDOMPointerLock:Exited": {},
674 messageManagerGroups: ["browsers"],
680 esModuleURI: "resource:///actors/ProfilesParent.sys.mjs",
683 esModuleURI: "resource:///actors/ProfilesChild.sys.mjs",
685 matches: ["about:profilemanager"],
686 enablePreference: "browser.profiles.enabled",
691 esModuleURI: "resource:///actors/PromptParent.sys.mjs",
699 esModuleURI: "resource:///actors/RefreshBlockerParent.sys.mjs",
702 esModuleURI: "resource:///actors/RefreshBlockerChild.sys.mjs",
705 messageManagerGroups: ["browsers"],
706 enablePreference: "accessibility.blockautorefresh",
709 ScreenshotsComponent: {
711 esModuleURI: "resource:///modules/ScreenshotsUtils.sys.mjs",
714 esModuleURI: "resource:///actors/ScreenshotsComponentChild.sys.mjs",
716 "Screenshots:Close": {},
717 "Screenshots:Copy": {},
718 "Screenshots:Download": {},
719 "Screenshots:HidePanel": {},
720 "Screenshots:OverlaySelection": {},
721 "Screenshots:RecordEvent": {},
722 "Screenshots:ShowPanel": {},
725 enablePreference: "screenshots.browser.component.enabled",
730 esModuleURI: "resource:///modules/ScreenshotsUtils.sys.mjs",
733 esModuleURI: "resource:///modules/ScreenshotsHelperChild.sys.mjs",
736 enablePreference: "screenshots.browser.component.enabled",
739 SearchSERPTelemetry: {
741 esModuleURI: "resource:///actors/SearchSERPTelemetryParent.sys.mjs",
744 esModuleURI: "resource:///actors/SearchSERPTelemetryChild.sys.mjs",
746 DOMContentLoaded: {},
747 pageshow: { mozSystemGroup: true },
748 // The 'pagehide' event is only used to clean up state, and should not
749 // force actor creation.
750 pagehide: { createActor: false },
751 load: { mozSystemGroup: true, capture: true },
754 matches: ["https://*/*"],
759 esModuleURI: "resource://normandy-content/ShieldFrameParent.sys.mjs",
762 esModuleURI: "resource://normandy-content/ShieldFrameChild.sys.mjs",
766 ShieldPageEvent: { wantUntrusted: true },
769 matches: ["about:studies*"],
774 esModuleURI: "resource:///actors/ShoppingSidebarParent.sys.mjs",
777 esModuleURI: "resource:///actors/ShoppingSidebarChild.sys.mjs",
779 ContentReady: { wantUntrusted: true },
780 PolledRequestMade: { wantUntrusted: true },
781 // This is added so the actor instantiates immediately and makes
782 // methods available to the page js on load.
783 DOMDocElementInserted: {},
784 ReportProductAvailable: { wantUntrusted: true },
785 AdClicked: { wantUntrusted: true },
786 AdImpression: { wantUntrusted: true },
787 DisableShopping: { wantUntrusted: true },
790 matches: ["about:shoppingsidebar"],
791 remoteTypes: ["privilegedabout"],
796 esModuleURI: "resource:///actors/SpeechDispatcherParent.sys.mjs",
800 esModuleURI: "resource:///actors/SpeechDispatcherChild.sys.mjs",
801 observers: ["chrome-synth-voices-error"],
804 messageManagerGroups: ["browsers"],
810 esModuleURI: "resource:///actors/ASRouterParent.sys.mjs",
813 esModuleURI: "resource:///actors/ASRouterChild.sys.mjs",
815 // This is added so the actor instantiates immediately and makes
816 // methods available to the page js on load.
817 DOMDocElementInserted: {},
825 "about:privatebrowsing*",
827 remoteTypes: ["privilegedabout"],
830 SwitchDocumentDirection: {
832 esModuleURI: "resource:///actors/SwitchDocumentDirectionChild.sys.mjs",
840 esModuleURI: "resource:///modules/UITourParent.sys.mjs",
843 esModuleURI: "resource:///modules/UITourChild.sys.mjs",
845 mozUITour: { wantUntrusted: true },
849 messageManagerGroups: ["browsers"],
854 esModuleURI: "resource:///actors/WebRTCParent.sys.mjs",
857 esModuleURI: "resource:///actors/WebRTCChild.sys.mjs",
864 ChromeUtils.defineLazyGetter(
867 () => Cc["@mozilla.org/weave/service;1"].getService().wrappedJSObject
870 if (AppConstants.MOZ_CRASHREPORTER) {
871 ChromeUtils.defineESModuleGetters(lazy, {
872 UnsubmittedCrashHandler: "resource:///modules/ContentCrashHandlers.sys.mjs",
876 ChromeUtils.defineLazyGetter(lazy, "gBrandBundle", function () {
877 return Services.strings.createBundle(
878 "chrome://branding/locale/brand.properties"
882 ChromeUtils.defineLazyGetter(lazy, "gBrowserBundle", function () {
883 return Services.strings.createBundle(
884 "chrome://browser/locale/browser.properties"
888 ChromeUtils.defineLazyGetter(lazy, "log", () => {
889 let { ConsoleAPI } = ChromeUtils.importESModule(
890 "resource://gre/modules/Console.sys.mjs"
892 let consoleOptions = {
893 // tip: set maxLogLevel to "debug" and use lazy.log.debug() to create
894 // detailed messages during development. See LOG_LEVELS in Console.sys.mjs
896 maxLogLevel: "error",
897 maxLogLevelPref: "browser.policies.loglevel",
898 prefix: "BrowserGlue.sys.mjs",
900 return new ConsoleAPI(consoleOptions);
905 "gmp-plugin-crash": ["PluginManager"],
906 "plugin-crashed": ["PluginManager"],
909 observe(subject, topic, data) {
910 for (let module of this.observers[topic]) {
912 lazy[module].observe(subject, topic, data);
920 for (let observer of Object.keys(this.observers)) {
921 Services.obs.addObserver(this, observer);
925 if (AppConstants.MOZ_UPDATER) {
926 listeners.observers["update-downloading"] = ["UpdateListener"];
927 listeners.observers["update-staged"] = ["UpdateListener"];
928 listeners.observers["update-downloaded"] = ["UpdateListener"];
929 listeners.observers["update-available"] = ["UpdateListener"];
930 listeners.observers["update-error"] = ["UpdateListener"];
931 listeners.observers["update-swap"] = ["UpdateListener"];
934 // Seconds of idle before trying to create a bookmarks backup.
935 const BOOKMARKS_BACKUP_IDLE_TIME_SEC = 8 * 60;
936 // Minimum interval between backups. We try to not create more than one backup
938 const BOOKMARKS_BACKUP_MIN_INTERVAL_DAYS = 1;
939 // Seconds of idle time before the late idle tasks will be scheduled.
940 const LATE_TASKS_IDLE_TIME_SEC = 20;
941 // Time after we stop tracking startup crashes.
942 const STARTUP_CRASHES_END_DELAY_MS = 30 * 1000;
945 * OS X has the concept of zero-window sessions and therefore ignores the
946 * browser-lastwindow-close-* topics.
948 const OBSERVE_LASTWINDOW_CLOSE_TOPICS = AppConstants.platform != "macosx";
950 export let BrowserInitState = {};
951 BrowserInitState.startupIdleTaskPromise = new Promise(resolve => {
952 BrowserInitState._resolveStartupIdleTask = resolve;
955 export function BrowserGlue() {
956 XPCOMUtils.defineLazyServiceGetter(
959 "@mozilla.org/widget/useridleservice;1",
963 ChromeUtils.defineLazyGetter(this, "_distributionCustomizer", function () {
964 const { DistributionCustomizer } = ChromeUtils.importESModule(
965 "resource:///modules/distribution.sys.mjs"
967 return new DistributionCustomizer();
970 XPCOMUtils.defineLazyServiceGetter(
973 "@mozilla.org/alerts-service;1",
980 function WindowsRegPoliciesGetter(wrk, root, regLocation) {
981 wrk.open(root, regLocation, wrk.ACCESS_READ);
983 if (wrk.hasChild("Mozilla\\" + Services.appinfo.name)) {
984 policies = lazy.WindowsGPOParser.readPolicies(wrk, policies);
990 function isPrivateBrowsingAllowedInRegistry() {
991 // If there is an attempt to open Private Browsing before
992 // EnterprisePolicies are initialized the Windows registry
993 // can be checked to determine if it is enabled
994 if (Services.policies.status > Ci.nsIEnterprisePolicies.UNINITIALIZED) {
995 // Yield to policies engine if initialized
996 let privateAllowed = Services.policies.isAllowed("privatebrowsing");
998 `Yield to initialized policies engine: Private Browsing Allowed = ${privateAllowed}`
1000 return privateAllowed;
1002 if (AppConstants.platform !== "win") {
1003 // Not using Windows so no registry, return true
1005 "AppConstants.platform is not 'win': Private Browsing allowed"
1009 // If all other checks fail only then do we check registry
1010 let wrk = Cc["@mozilla.org/windows-registry-key;1"].createInstance(
1013 let regLocation = "SOFTWARE\\Policies";
1014 let userPolicies, machinePolicies;
1015 // Only check HKEY_LOCAL_MACHINE if not in testing
1016 if (!Cu.isInAutomation) {
1017 machinePolicies = WindowsRegPoliciesGetter(
1019 wrk.ROOT_KEY_LOCAL_MACHINE,
1023 // Check machine policies before checking user policies
1024 // HKEY_LOCAL_MACHINE supersedes HKEY_CURRENT_USER so only check
1025 // HKEY_CURRENT_USER if the registry key is not present in
1026 // HKEY_LOCAL_MACHINE at all
1027 if (machinePolicies && "DisablePrivateBrowsing" in machinePolicies) {
1029 `DisablePrivateBrowsing in HKEY_LOCAL_MACHINE is ${machinePolicies.DisablePrivateBrowsing}`
1031 return !(machinePolicies.DisablePrivateBrowsing === 1);
1033 userPolicies = WindowsRegPoliciesGetter(
1035 wrk.ROOT_KEY_CURRENT_USER,
1038 if (userPolicies && "DisablePrivateBrowsing" in userPolicies) {
1040 `DisablePrivateBrowsing in HKEY_CURRENT_USER is ${userPolicies.DisablePrivateBrowsing}`
1042 return !(userPolicies.DisablePrivateBrowsing === 1);
1044 // Private browsing allowed if no registry entry exists
1046 "No DisablePrivateBrowsing registry entry: Private Browsing allowed"
1051 BrowserGlue.prototype = {
1052 _saveSession: false,
1053 _migrationImportsDefaultBookmarks: false,
1054 _placesBrowserInitComplete: false,
1055 _isNewProfile: undefined,
1056 _defaultCookieBehaviorAtStartup: null,
1058 _setPrefToSaveSession: function BG__setPrefToSaveSession(aForce) {
1059 if (!this._saveSession && !aForce) {
1063 if (!lazy.PrivateBrowsingUtils.permanentPrivateBrowsing) {
1064 Services.prefs.setBoolPref(
1065 "browser.sessionstore.resume_session_once",
1070 // This method can be called via [NSApplication terminate:] on Mac, which
1071 // ends up causing prefs not to be flushed to disk, so we need to do that
1072 // explicitly here. See bug 497652.
1073 Services.prefs.savePrefFile(null);
1076 // nsIObserver implementation
1077 observe: async function BG_observe(subject, topic, data) {
1079 case "notifications-open-settings":
1080 this._openPreferences("privacy-permissions");
1082 case "final-ui-startup":
1083 this._beforeUIStartup();
1085 case "browser-delayed-startup-finished":
1086 this._onFirstWindowLoaded(subject);
1087 Services.obs.removeObserver(this, "browser-delayed-startup-finished");
1089 case "sessionstore-windows-restored":
1090 this._onWindowsRestored();
1092 case "browser:purge-session-history":
1093 // reset the console service's error buffer
1094 Services.console.logStringMessage(null); // clear the console (in case it's open)
1095 Services.console.reset();
1097 case "restart-in-safe-mode":
1098 this._onSafeModeRestart(subject);
1100 case "quit-application-requested":
1101 this._onQuitRequest(subject, data);
1103 case "quit-application-granted":
1104 this._onQuitApplicationGranted();
1106 case "browser-lastwindow-close-requested":
1107 if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
1108 // The application is not actually quitting, but the last full browser
1109 // window is about to be closed.
1110 this._onQuitRequest(subject, "lastwindow");
1113 case "browser-lastwindow-close-granted":
1114 if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
1115 this._setPrefToSaveSession();
1118 case "fxaccounts:onverified":
1119 this._onThisDeviceConnected();
1121 case "fxaccounts:device_connected":
1122 this._onDeviceConnected(data);
1124 case "fxaccounts:verify_login":
1125 this._onVerifyLoginNotification(JSON.parse(data));
1127 case "fxaccounts:device_disconnected":
1128 data = JSON.parse(data);
1129 if (data.isLocalDevice) {
1130 this._onDeviceDisconnected();
1133 case "fxaccounts:commands:open-uri":
1134 this._onDisplaySyncURIs(subject);
1136 case "session-save":
1137 this._setPrefToSaveSession(true);
1138 subject.QueryInterface(Ci.nsISupportsPRBool);
1139 subject.data = true;
1141 case "places-init-complete":
1142 Services.obs.removeObserver(this, "places-init-complete");
1143 if (!this._migrationImportsDefaultBookmarks) {
1144 this._initPlaces(false);
1148 this._backupBookmarks();
1150 case "distribution-customization-complete":
1151 Services.obs.removeObserver(
1153 "distribution-customization-complete"
1155 // Customization has finished, we don't need the customizer anymore.
1156 delete this._distributionCustomizer;
1158 case "browser-glue-test": // used by tests
1159 if (data == "force-ui-migration") {
1161 } else if (data == "force-distribution-customization") {
1162 this._distributionCustomizer.applyCustomizations();
1163 // To apply distribution bookmarks use "places-init-complete".
1164 } else if (data == "test-force-places-init") {
1165 this._placesInitialized = false;
1166 this._initPlaces(false);
1167 } else if (data == "mock-alerts-service") {
1168 Object.defineProperty(this, "AlertsService", {
1169 value: subject.wrappedJSObject,
1171 } else if (data == "places-browser-init-complete") {
1172 if (this._placesBrowserInitComplete) {
1173 Services.obs.notifyObservers(null, "places-browser-init-complete");
1175 } else if (data == "add-breaches-sync-handler") {
1176 this._addBreachesSyncHandler();
1179 case "initial-migration-will-import-default-bookmarks":
1180 this._migrationImportsDefaultBookmarks = true;
1182 case "initial-migration-did-import-default-bookmarks":
1183 this._initPlaces(true);
1185 case "handle-xul-text-link":
1186 let linkHandled = subject.QueryInterface(Ci.nsISupportsPRBool);
1187 if (!linkHandled.data) {
1188 let win = lazy.BrowserWindowTracker.getTopWindow();
1190 data = JSON.parse(data);
1191 let where = win.whereToOpenLink(data);
1192 // Preserve legacy behavior of non-modifier left-clicks
1193 // opening in a new selected tab.
1194 if (where == "current") {
1197 win.openTrustedLinkIn(data.href, where);
1198 linkHandled.data = true;
1202 case "profile-before-change":
1203 // Any component depending on Places should be finalized in
1204 // _onPlacesShutdown. Any component that doesn't need to act after
1205 // the UI has gone should be finalized in _onQuitApplicationGranted.
1208 case "keyword-search":
1209 // This notification is broadcast by the docshell when it "fixes up" a
1210 // URI that it's been asked to load into a keyword search.
1213 engine = Services.search.getEngineByName(
1214 subject.QueryInterface(Ci.nsISupportsString).data
1219 let win = lazy.BrowserWindowTracker.getTopWindow();
1220 lazy.BrowserSearchTelemetry.recordSearch(
1221 win.gBrowser.selectedBrowser,
1226 case "xpi-signature-changed":
1227 let disabledAddons = JSON.parse(data).disabled;
1228 let addons = await lazy.AddonManager.getAddonsByIDs(disabledAddons);
1229 if (addons.some(addon => addon)) {
1230 this._notifyUnsignedAddonsDisabled();
1233 case "sync-ui-state:update":
1234 this._updateFxaBadges(lazy.BrowserWindowTracker.getTopWindow());
1236 case "handlersvc-store-initialized":
1237 // Initialize PdfJs when running in-process and remote. This only
1238 // happens once since PdfJs registers global hooks. If the PdfJs
1239 // extension is installed the init method below will be overridden
1240 // leaving initialization to the extension.
1241 // parent only: configure default prefs, set up pref observers, register
1242 // pdf content handler, and initializes parent side message manager
1243 // shim for privileged api access.
1244 lazy.PdfJs.init(this._isNewProfile);
1246 // Allow certain viewable internally types to be opened from downloads.
1247 lazy.DownloadsViewableInternally.register();
1251 this._earlyBlankFirstPaint(subject);
1252 gThisInstanceIsTaskbarTab = subject.handleFlag("taskbar-tab", false);
1253 gThisInstanceIsLaunchOnLogin = subject.handleFlag(
1257 let launchOnLoginPref = "browser.startup.windowsLaunchOnLogin.enabled";
1258 let profileSvc = Cc[
1259 "@mozilla.org/toolkit/profile-service;1"
1260 ].getService(Ci.nsIToolkitProfileService);
1262 AppConstants.platform == "win" &&
1263 !profileSvc.startWithLastProfile
1265 // If we don't start with last profile, the user
1266 // likely sees the profile selector on launch.
1267 if (Services.prefs.getBoolPref(launchOnLoginPref)) {
1268 Services.telemetry.setEventRecordingEnabled(
1272 Services.telemetry.recordEvent(
1274 "last_profile_disable",
1278 Services.prefs.setBoolPref(launchOnLoginPref, false);
1279 // Only remove registry key, not shortcut here as we can assume
1280 // if a user manually created a shortcut they want this behavior.
1281 await lazy.WindowsLaunchOnLogin.removeLaunchOnLoginRegistryKey();
1287 // initialization (called on application startup)
1288 _init: function BG__init() {
1289 let os = Services.obs;
1291 "notifications-open-settings",
1293 "browser-delayed-startup-finished",
1294 "sessionstore-windows-restored",
1295 "browser:purge-session-history",
1296 "quit-application-requested",
1297 "quit-application-granted",
1298 "fxaccounts:onverified",
1299 "fxaccounts:device_connected",
1300 "fxaccounts:verify_login",
1301 "fxaccounts:device_disconnected",
1302 "fxaccounts:commands:open-uri",
1304 "places-init-complete",
1305 "distribution-customization-complete",
1306 "handle-xul-text-link",
1307 "profile-before-change",
1309 "restart-in-safe-mode",
1310 "xpi-signature-changed",
1311 "sync-ui-state:update",
1312 "handlersvc-store-initialized",
1313 ].forEach(topic => os.addObserver(this, topic, true));
1314 if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
1315 os.addObserver(this, "browser-lastwindow-close-requested", true);
1316 os.addObserver(this, "browser-lastwindow-close-granted", true);
1319 lazy.ActorManagerParent.addJSProcessActors(JSPROCESSACTORS);
1320 lazy.ActorManagerParent.addJSWindowActors(JSWINDOWACTORS);
1322 this._firstWindowReady = new Promise(
1323 resolve => (this._firstWindowLoaded = resolve)
1327 // cleanup (called on application shutdown)
1328 _dispose: function BG__dispose() {
1329 // AboutHomeStartupCache might write to the cache during
1330 // quit-application-granted, so we defer uninitialization
1332 AboutHomeStartupCache.uninit();
1334 if (this._bookmarksBackupIdleTime) {
1335 this._userIdleService.removeIdleObserver(
1337 this._bookmarksBackupIdleTime
1339 this._bookmarksBackupIdleTime = null;
1341 if (this._lateTasksIdleObserver) {
1342 this._userIdleService.removeIdleObserver(
1343 this._lateTasksIdleObserver,
1344 LATE_TASKS_IDLE_TIME_SEC
1346 delete this._lateTasksIdleObserver;
1348 if (this._gmpInstallManager) {
1349 this._gmpInstallManager.uninit();
1350 delete this._gmpInstallManager;
1353 Services.prefs.removeObserver(
1354 "privacy.trackingprotection",
1355 this._matchCBCategory
1357 Services.prefs.removeObserver(
1358 "network.cookie.cookieBehavior",
1359 this._matchCBCategory
1361 Services.prefs.removeObserver(
1362 "network.cookie.cookieBehavior.pbmode",
1363 this._matchCBCategory
1365 Services.prefs.removeObserver(
1366 "network.http.referer.disallowCrossSiteRelaxingDefault",
1367 this._matchCBCategory
1369 Services.prefs.removeObserver(
1370 "network.http.referer.disallowCrossSiteRelaxingDefault.top_navigation",
1371 this._matchCBCategory
1373 Services.prefs.removeObserver(
1374 "privacy.partition.network_state.ocsp_cache",
1375 this._matchCBCategory
1377 Services.prefs.removeObserver(
1378 "privacy.query_stripping.enabled",
1379 this._matchCBCategory
1381 Services.prefs.removeObserver(
1382 "privacy.query_stripping.enabled.pbmode",
1383 this._matchCBCategory
1385 Services.prefs.removeObserver(
1386 "privacy.fingerprintingProtection",
1387 this._matchCBCategory
1389 Services.prefs.removeObserver(
1390 "privacy.fingerprintingProtection.pbmode",
1391 this._matchCBCategory
1393 Services.prefs.removeObserver(
1394 ContentBlockingCategoriesPrefs.PREF_CB_CATEGORY,
1395 this._updateCBCategory
1397 Services.prefs.removeObserver(
1398 "privacy.trackingprotection",
1399 this._setPrefExpectations
1401 Services.prefs.removeObserver(
1402 "browser.contentblocking.features.strict",
1403 this._setPrefExpectationsAndUpdate
1407 // runs on startup, before the first command line handler is invoked
1408 // (i.e. before the first window is opened)
1409 _beforeUIStartup: function BG__beforeUIStartup() {
1410 lazy.SessionStartup.init();
1412 // check if we're in safe mode
1413 if (Services.appinfo.inSafeMode) {
1414 Services.ww.openWindow(
1416 "chrome://browser/content/safeMode.xhtml",
1418 "chrome,centerscreen,modal,resizable=no",
1423 // apply distribution customizations
1424 this._distributionCustomizer.applyCustomizations();
1426 // handle any UI migration
1429 if (!Services.prefs.prefHasUserValue(PREF_PDFJS_ISDEFAULT_CACHE_STATE)) {
1430 lazy.PdfJs.checkIsDefault(this._isNewProfile);
1435 lazy.SessionStore.init();
1437 lazy.BuiltInThemes.maybeInstallActiveBuiltInTheme();
1439 if (AppConstants.MOZ_NORMANDY) {
1440 lazy.Normandy.init();
1443 lazy.SaveToPocket.init();
1445 lazy.ResetPBMPanel.init();
1447 AboutHomeStartupCache.init();
1449 Services.obs.notifyObservers(null, "browser-ui-startup-complete");
1452 _checkForOldBuildUpdates() {
1453 // check for update if our build is old
1455 AppConstants.MOZ_UPDATER &&
1456 Services.prefs.getBoolPref("app.update.checkInstallTime")
1458 let buildID = Services.appinfo.appBuildID;
1459 let today = new Date().getTime();
1460 /* eslint-disable no-multi-spaces */
1461 let buildDate = new Date(
1462 buildID.slice(0, 4), // year
1463 buildID.slice(4, 6) - 1, // months are zero-based.
1464 buildID.slice(6, 8), // day
1465 buildID.slice(8, 10), // hour
1466 buildID.slice(10, 12), // min
1467 buildID.slice(12, 14)
1470 /* eslint-enable no-multi-spaces */
1472 const millisecondsIn24Hours = 86400000;
1474 Services.prefs.getIntPref("app.update.checkInstallTime.days") *
1475 millisecondsIn24Hours;
1477 if (buildDate + acceptableAge < today) {
1478 Cc["@mozilla.org/updates/update-service;1"]
1479 .getService(Ci.nsIApplicationUpdateService)
1480 .checkForBackgroundUpdates();
1485 async _onSafeModeRestart(window) {
1486 // prompt the user to confirm
1487 let productName = lazy.gBrandBundle.GetStringFromName("brandShortName");
1488 let strings = lazy.gBrowserBundle;
1489 let promptTitle = strings.formatStringFromName(
1490 "troubleshootModeRestartPromptTitle",
1493 let promptMessage = strings.GetStringFromName(
1494 "troubleshootModeRestartPromptMessage"
1496 let restartText = strings.GetStringFromName(
1497 "troubleshootModeRestartButton"
1500 Services.prompt.BUTTON_POS_0 * Services.prompt.BUTTON_TITLE_IS_STRING +
1501 Services.prompt.BUTTON_POS_1 * Services.prompt.BUTTON_TITLE_CANCEL +
1502 Services.prompt.BUTTON_POS_0_DEFAULT;
1504 let rv = await Services.prompt.asyncConfirmEx(
1505 window.browsingContext,
1506 Ci.nsIPrompt.MODAL_TYPE_INTERNAL_WINDOW,
1516 if (rv.get("buttonNumClicked") != 0) {
1520 let cancelQuit = Cc["@mozilla.org/supports-PRBool;1"].createInstance(
1521 Ci.nsISupportsPRBool
1523 Services.obs.notifyObservers(
1525 "quit-application-requested",
1529 if (!cancelQuit.data) {
1530 Services.startup.restartInSafeMode(Ci.nsIAppStartup.eAttemptQuit);
1535 * Show a notification bar offering a reset.
1538 * String of either "unused" or "uninstall", specifying the reason
1539 * why a profile reset is offered.
1541 _resetProfileNotification(reason) {
1542 let win = lazy.BrowserWindowTracker.getTopWindow();
1547 const { ResetProfile } = ChromeUtils.importESModule(
1548 "resource://gre/modules/ResetProfile.sys.mjs"
1550 if (!ResetProfile.resetSupported()) {
1554 let productName = lazy.gBrandBundle.GetStringFromName("brandShortName");
1555 let resetBundle = Services.strings.createBundle(
1556 "chrome://global/locale/resetProfile.properties"
1560 if (reason == "unused") {
1561 message = resetBundle.formatStringFromName("resetUnusedProfile.message", [
1564 } else if (reason == "uninstall") {
1565 message = resetBundle.formatStringFromName("resetUninstalled.message", [
1570 `Unknown reason (${reason}) given to _resetProfileNotification.`
1575 label: resetBundle.formatStringFromName(
1576 "refreshProfile.resetButton.label",
1579 accessKey: resetBundle.GetStringFromName(
1580 "refreshProfile.resetButton.accesskey"
1583 ResetProfile.openConfirmationDialog(win);
1588 win.gNotificationBox.appendNotification(
1589 "reset-profile-notification",
1592 image: "chrome://global/skin/icons/question-64.png",
1593 priority: win.gNotificationBox.PRIORITY_INFO_LOW,
1599 _notifyUnsignedAddonsDisabled() {
1600 let win = lazy.BrowserWindowTracker.getTopWindow();
1605 let message = win.gNavigatorBundle.getString(
1606 "unsignedAddonsDisabled.message"
1610 label: win.gNavigatorBundle.getString(
1611 "unsignedAddonsDisabled.learnMore.label"
1613 accessKey: win.gNavigatorBundle.getString(
1614 "unsignedAddonsDisabled.learnMore.accesskey"
1617 win.BrowserOpenAddonsMgr("addons://list/extension?unsigned=true");
1622 win.gNotificationBox.appendNotification(
1623 "unsigned-addons-disabled",
1626 priority: win.gNotificationBox.PRIORITY_WARNING_MEDIUM,
1632 _earlyBlankFirstPaint(cmdLine) {
1633 let startTime = Cu.now();
1635 AppConstants.platform == "macosx" ||
1636 Services.startup.wasSilentlyStarted ||
1637 !Services.prefs.getBoolPref("browser.startup.blankWindow", false)
1642 // Until bug 1450626 and bug 1488384 are fixed, skip the blank window when
1643 // using a non-default theme.
1645 !Services.startup.showedPreXULSkeletonUI &&
1646 Services.prefs.getCharPref(
1647 "extensions.activeThemeID",
1648 "default-theme@mozilla.org"
1649 ) != "default-theme@mozilla.org"
1654 let store = Services.xulStore;
1655 let getValue = attr =>
1656 store.getValue(AppConstants.BROWSER_CHROME_URL, "main-window", attr);
1657 let width = getValue("width");
1658 let height = getValue("height");
1660 // The clean profile case isn't handled yet. Return early for now.
1661 if (!width || !height) {
1665 let browserWindowFeatures =
1666 "chrome,all,dialog=no,extrachrome,menubar,resizable,scrollbars,status," +
1667 "location,toolbar,personalbar";
1668 // This needs to be set when opening the window to ensure that the AppUserModelID
1669 // is set correctly on Windows. Without it, initial launches with `-private-window`
1670 // will show up under the regular Firefox taskbar icon first, and then switch
1671 // to the Private Browsing icon shortly thereafter.
1672 if (cmdLine.findFlag("private-window", false) != -1) {
1673 if (isPrivateBrowsingAllowedInRegistry()) {
1674 browserWindowFeatures += ",private";
1677 let win = Services.ww.openWindow(
1681 browserWindowFeatures,
1685 // Hide the titlebar if the actual browser window will draw in it.
1686 let hiddenTitlebar = Services.appinfo.drawInTitlebar;
1687 if (hiddenTitlebar) {
1688 win.windowUtils.setChromeMargin(0, 2, 2, 2);
1691 let docElt = win.document.documentElement;
1692 docElt.setAttribute("screenX", getValue("screenX"));
1693 docElt.setAttribute("screenY", getValue("screenY"));
1695 // The sizemode="maximized" attribute needs to be set before first paint.
1696 let sizemode = getValue("sizemode");
1697 if (sizemode == "maximized") {
1698 docElt.setAttribute("sizemode", sizemode);
1700 // Set the size to use when the user leaves the maximized mode.
1701 // The persisted size is the outer size, but the height/width
1702 // attributes set the inner size.
1703 let appWin = win.docShell.treeOwner
1704 .QueryInterface(Ci.nsIInterfaceRequestor)
1705 .getInterface(Ci.nsIAppWindow);
1706 height -= appWin.outerToInnerHeightDifferenceInCSSPixels;
1707 width -= appWin.outerToInnerWidthDifferenceInCSSPixels;
1708 docElt.setAttribute("height", height);
1709 docElt.setAttribute("width", width);
1711 // Setting the size of the window in the features string instead of here
1712 // causes the window to grow by the size of the titlebar.
1713 win.resizeTo(width, height);
1716 // Set this before showing the window so that graphics code can use it to
1717 // decide to skip some expensive code paths (eg. starting the GPU process).
1718 docElt.setAttribute("windowtype", "navigator:blank");
1720 // The window becomes visible after OnStopRequest, so make this happen now.
1723 ChromeUtils.addProfilerMarker("earlyBlankFirstPaint", startTime);
1724 win.openTime = Cu.now();
1726 let { TelemetryTimestamps } = ChromeUtils.importESModule(
1727 "resource://gre/modules/TelemetryTimestamps.sys.mjs"
1729 TelemetryTimestamps.add("blankWindowShown");
1732 _firstWindowTelemetry(aWindow) {
1733 let scaling = aWindow.devicePixelRatio * 100;
1735 Services.telemetry.getHistogramById("DISPLAY_SCALING").add(scaling);
1739 _collectStartupConditionsTelemetry() {
1740 let nowSeconds = Math.round(Date.now() / 1000);
1741 // Don't include cases where we don't have the pref. This rules out the first install
1742 // as well as the first run of a build since this was introduced. These could by some
1743 // definitions be referred to as "cold" startups, but probably not since we likely
1744 // just wrote many of the files we use to disk. This way we should approximate a lower
1745 // bound to the number of cold startups rather than an upper bound.
1746 let lastCheckSeconds = Services.prefs.getIntPref(
1747 "browser.startup.lastColdStartupCheck",
1750 Services.prefs.setIntPref(
1751 "browser.startup.lastColdStartupCheck",
1755 let secondsSinceLastOSRestart =
1756 Services.startup.secondsSinceLastOSRestart;
1758 nowSeconds - secondsSinceLastOSRestart > lastCheckSeconds;
1759 Services.telemetry.scalarSet("startup.is_cold", isColdStartup);
1760 Services.telemetry.scalarSet(
1761 "startup.seconds_since_last_os_restart",
1762 secondsSinceLastOSRestart
1769 // the first browser window has finished initializing
1770 _onFirstWindowLoaded: function BG__onFirstWindowLoaded(aWindow) {
1771 lazy.AboutNewTab.init();
1773 lazy.TabCrashHandler.init();
1775 lazy.ProcessHangMonitor.init();
1777 lazy.UrlbarPrefs.updateFirefoxSuggestScenario();
1779 // A channel for "remote troubleshooting" code...
1780 let channel = new lazy.WebChannel(
1781 "remote-troubleshooting",
1782 "remote-troubleshooting"
1784 channel.listen((id, data, target) => {
1785 if (data.command == "request") {
1786 let { Troubleshoot } = ChromeUtils.importESModule(
1787 "resource://gre/modules/Troubleshoot.sys.mjs"
1789 Troubleshoot.snapshot().then(snapshotData => {
1790 // for privacy we remove crash IDs and all preferences (but bug 1091944
1791 // exists to expose prefs once we are confident of privacy implications)
1792 delete snapshotData.crashes;
1793 delete snapshotData.modifiedPreferences;
1794 delete snapshotData.printingPreferences;
1795 channel.send(snapshotData, target);
1800 // Offer to reset a user's profile if it hasn't been used for 60 days.
1801 const OFFER_PROFILE_RESET_INTERVAL_MS = 60 * 24 * 60 * 60 * 1000;
1802 let lastUse = Services.appinfo.replacedLockTime;
1803 let disableResetPrompt = Services.prefs.getBoolPref(
1804 "browser.disableResetPrompt",
1809 !disableResetPrompt &&
1811 Date.now() - lastUse >= OFFER_PROFILE_RESET_INTERVAL_MS
1813 this._resetProfileNotification("unused");
1814 } else if (AppConstants.platform == "win" && !disableResetPrompt) {
1815 // Check if we were just re-installed and offer Firefox Reset
1818 updateChannel = ChromeUtils.importESModule(
1819 "resource://gre/modules/UpdateUtils.sys.mjs"
1820 ).UpdateUtils.UpdateChannel;
1822 if (updateChannel) {
1823 let uninstalledValue = lazy.WindowsRegistry.readRegKey(
1824 Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
1825 "Software\\Mozilla\\Firefox",
1826 `Uninstalled-${updateChannel}`
1828 let removalSuccessful = lazy.WindowsRegistry.removeRegKey(
1829 Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
1830 "Software\\Mozilla\\Firefox",
1831 `Uninstalled-${updateChannel}`
1833 if (removalSuccessful && uninstalledValue == "True") {
1834 this._resetProfileNotification("uninstall");
1839 this._checkForOldBuildUpdates();
1841 // Check if Sync is configured
1842 if (Services.prefs.prefHasUserValue("services.sync.username")) {
1843 lazy.WeaveService.init();
1846 lazy.PageThumbs.init();
1848 lazy.NewTabUtils.init();
1850 Services.telemetry.setEventRecordingEnabled(
1851 "security.ui.protections",
1855 Services.telemetry.setEventRecordingEnabled("security.doh.neterror", true);
1857 lazy.PageActions.init();
1859 lazy.DoHController.init();
1861 this._firstWindowTelemetry(aWindow);
1862 this._firstWindowLoaded();
1864 this._collectStartupConditionsTelemetry();
1866 // Set the default favicon size for UI views that use the page-icon protocol.
1867 lazy.PlacesUtils.favicons.setDefaultIconURIPreferredSize(
1868 16 * aWindow.devicePixelRatio
1871 this._setPrefExpectationsAndUpdate();
1872 this._matchCBCategory();
1874 // This observes the entire privacy.trackingprotection.* pref tree.
1875 Services.prefs.addObserver(
1876 "privacy.trackingprotection",
1877 this._matchCBCategory
1879 Services.prefs.addObserver(
1880 "network.cookie.cookieBehavior",
1881 this._matchCBCategory
1883 Services.prefs.addObserver(
1884 "network.cookie.cookieBehavior.pbmode",
1885 this._matchCBCategory
1887 Services.prefs.addObserver(
1888 "network.http.referer.disallowCrossSiteRelaxingDefault",
1889 this._matchCBCategory
1891 Services.prefs.addObserver(
1892 "network.http.referer.disallowCrossSiteRelaxingDefault.top_navigation",
1893 this._matchCBCategory
1895 Services.prefs.addObserver(
1896 "privacy.partition.network_state.ocsp_cache",
1897 this._matchCBCategory
1899 Services.prefs.addObserver(
1900 "privacy.query_stripping.enabled",
1901 this._matchCBCategory
1903 Services.prefs.addObserver(
1904 "privacy.query_stripping.enabled.pbmode",
1905 this._matchCBCategory
1907 Services.prefs.addObserver(
1908 "privacy.fingerprintingProtection",
1909 this._matchCBCategory
1911 Services.prefs.addObserver(
1912 "privacy.fingerprintingProtection.pbmode",
1913 this._matchCBCategory
1915 Services.prefs.addObserver(
1916 ContentBlockingCategoriesPrefs.PREF_CB_CATEGORY,
1917 this._updateCBCategory
1919 Services.prefs.addObserver(
1920 "media.autoplay.default",
1921 this._updateAutoplayPref
1923 Services.prefs.addObserver(
1924 "privacy.trackingprotection",
1925 this._setPrefExpectations
1927 Services.prefs.addObserver(
1928 "browser.contentblocking.features.strict",
1929 this._setPrefExpectationsAndUpdate
1933 _updateAutoplayPref() {
1934 const blocked = Services.prefs.getIntPref("media.autoplay.default", 1);
1935 const telemetry = Services.telemetry.getHistogramById(
1936 "AUTOPLAY_DEFAULT_SETTING_CHANGE"
1938 const labels = { 0: "allow", 1: "blockAudible", 5: "blockAll" };
1939 if (blocked in labels) {
1940 telemetry.add(labels[blocked]);
1944 _setPrefExpectations() {
1945 ContentBlockingCategoriesPrefs.setPrefExpectations();
1948 _setPrefExpectationsAndUpdate() {
1949 ContentBlockingCategoriesPrefs.setPrefExpectations();
1950 ContentBlockingCategoriesPrefs.updateCBCategory();
1953 _matchCBCategory() {
1954 ContentBlockingCategoriesPrefs.matchCBCategory();
1957 _updateCBCategory() {
1958 ContentBlockingCategoriesPrefs.updateCBCategory();
1961 _recordContentBlockingTelemetry() {
1962 Services.telemetry.setEventRecordingEnabled(
1963 "security.ui.protectionspopup",
1964 Services.prefs.getBoolPref(
1965 "security.protectionspopup.recordEventTelemetry"
1968 Services.telemetry.setEventRecordingEnabled(
1969 "security.ui.app_menu",
1970 Services.prefs.getBoolPref("security.app_menu.recordEventTelemetry")
1973 let tpEnabled = Services.prefs.getBoolPref(
1974 "privacy.trackingprotection.enabled"
1977 .getHistogramById("TRACKING_PROTECTION_ENABLED")
1980 let tpPBDisabled = Services.prefs.getBoolPref(
1981 "privacy.trackingprotection.pbmode.enabled"
1984 .getHistogramById("TRACKING_PROTECTION_PBM_DISABLED")
1985 .add(!tpPBDisabled);
1987 let cookieBehavior = Services.prefs.getIntPref(
1988 "network.cookie.cookieBehavior"
1990 Services.telemetry.getHistogramById("COOKIE_BEHAVIOR").add(cookieBehavior);
1992 let fpEnabled = Services.prefs.getBoolPref(
1993 "privacy.trackingprotection.fingerprinting.enabled"
1995 let cmEnabled = Services.prefs.getBoolPref(
1996 "privacy.trackingprotection.cryptomining.enabled"
2000 Services.prefs.getStringPref("browser.contentblocking.category", null)
2012 // Any other value is unsupported.
2017 Services.telemetry.scalarSet(
2018 "contentblocking.fingerprinting_blocking_enabled",
2021 Services.telemetry.scalarSet(
2022 "contentblocking.cryptomining_blocking_enabled",
2025 Services.telemetry.scalarSet("contentblocking.category", categoryPref);
2028 _recordDataSanitizationPrefs() {
2029 Services.telemetry.scalarSet(
2030 "datasanitization.privacy_sanitize_sanitizeOnShutdown",
2031 Services.prefs.getBoolPref("privacy.sanitize.sanitizeOnShutdown")
2033 Services.telemetry.scalarSet(
2034 "datasanitization.privacy_clearOnShutdown_cookies",
2035 Services.prefs.getBoolPref("privacy.clearOnShutdown.cookies")
2037 Services.telemetry.scalarSet(
2038 "datasanitization.privacy_clearOnShutdown_history",
2039 Services.prefs.getBoolPref("privacy.clearOnShutdown.history")
2041 Services.telemetry.scalarSet(
2042 "datasanitization.privacy_clearOnShutdown_formdata",
2043 Services.prefs.getBoolPref("privacy.clearOnShutdown.formdata")
2045 Services.telemetry.scalarSet(
2046 "datasanitization.privacy_clearOnShutdown_downloads",
2047 Services.prefs.getBoolPref("privacy.clearOnShutdown.downloads")
2049 Services.telemetry.scalarSet(
2050 "datasanitization.privacy_clearOnShutdown_cache",
2051 Services.prefs.getBoolPref("privacy.clearOnShutdown.cache")
2053 Services.telemetry.scalarSet(
2054 "datasanitization.privacy_clearOnShutdown_sessions",
2055 Services.prefs.getBoolPref("privacy.clearOnShutdown.sessions")
2057 Services.telemetry.scalarSet(
2058 "datasanitization.privacy_clearOnShutdown_offlineApps",
2059 Services.prefs.getBoolPref("privacy.clearOnShutdown.offlineApps")
2061 Services.telemetry.scalarSet(
2062 "datasanitization.privacy_clearOnShutdown_siteSettings",
2063 Services.prefs.getBoolPref("privacy.clearOnShutdown.siteSettings")
2065 Services.telemetry.scalarSet(
2066 "datasanitization.privacy_clearOnShutdown_openWindows",
2067 Services.prefs.getBoolPref("privacy.clearOnShutdown.openWindows")
2071 for (let permission of Services.perms.all) {
2072 // We consider just permissions set for http, https and file URLs.
2074 permission.type == "cookie" &&
2075 permission.capability == Ci.nsICookiePermission.ACCESS_SESSION &&
2076 ["http", "https", "file"].some(scheme =>
2077 permission.principal.schemeIs(scheme)
2083 Services.telemetry.scalarSet(
2084 "datasanitization.session_permission_exceptions",
2090 * Application shutdown handler.
2092 _onQuitApplicationGranted() {
2094 // This pref must be set here because SessionStore will use its value
2095 // on quit-application.
2096 () => this._setPrefToSaveSession(),
2098 // Call trackStartupCrashEnd here in case the delayed call on startup hasn't
2099 // yet occurred (see trackStartupCrashEnd caller in browser.js).
2100 () => Services.startup.trackStartupCrashEnd(),
2103 if (this._bookmarksBackupIdleTime) {
2104 this._userIdleService.removeIdleObserver(
2106 this._bookmarksBackupIdleTime
2108 this._bookmarksBackupIdleTime = null;
2112 () => lazy.BrowserUsageTelemetry.uninit(),
2113 () => lazy.SearchSERPTelemetry.uninit(),
2114 () => lazy.SearchSERPDomainToCategoriesMap.uninit(),
2115 () => lazy.Interactions.uninit(),
2116 () => lazy.PageDataService.uninit(),
2117 () => lazy.PageThumbs.uninit(),
2118 () => lazy.NewTabUtils.uninit(),
2119 () => lazy.Normandy.uninit(),
2120 () => lazy.RFPHelper.uninit(),
2121 () => lazy.ShoppingUtils.uninit(),
2122 () => lazy.ASRouterNewTabHook.destroy(),
2124 if (AppConstants.MOZ_UPDATER) {
2125 lazy.UpdateListener.reset();
2129 // bug 1839426 - The FOG service needs to be instantiated reliably so it
2130 // can perform at-shutdown tasks later in shutdown.
2135 for (let task of tasks) {
2139 console.error(`Error during quit-application-granted: ${ex}`);
2140 if (Cu.isInAutomation) {
2141 // This usually happens after the test harness is done collecting
2142 // test errors, thus we can't easily add a failure to it. The only
2143 // noticeable solution we have is crashing.
2144 Cc["@mozilla.org/xpcom/debug;1"]
2145 .getService(Ci.nsIDebug2)
2146 .abort(ex.filename, ex.lineNumber);
2152 // Set up a listener to enable/disable the screenshots extension
2153 // based on its preference.
2154 _monitorScreenshotsPref() {
2155 const SCREENSHOTS_PREF = "extensions.screenshots.disabled";
2156 const COMPONENT_PREF = "screenshots.browser.component.enabled";
2157 const ID = "screenshots@mozilla.org";
2158 const _checkScreenshotsPref = async () => {
2159 let screenshotsDisabled = Services.prefs.getBoolPref(
2163 let componentEnabled = Services.prefs.getBoolPref(COMPONENT_PREF, true);
2165 let screenshotsAddon = await lazy.AddonManager.getAddonByID(ID);
2167 if (screenshotsDisabled) {
2168 if (componentEnabled) {
2169 lazy.ScreenshotsUtils.uninitialize();
2170 } else if (screenshotsAddon?.isActive) {
2171 await screenshotsAddon.disable({ allowSystemAddons: true });
2173 } else if (componentEnabled) {
2174 lazy.ScreenshotsUtils.initialize();
2175 if (screenshotsAddon?.isActive) {
2176 await screenshotsAddon.disable({ allowSystemAddons: true });
2180 await screenshotsAddon.enable({ allowSystemAddons: true });
2182 console.error(`Error trying to enable screenshots extension: ${ex}`);
2184 lazy.ScreenshotsUtils.uninitialize();
2187 Services.prefs.addObserver(SCREENSHOTS_PREF, _checkScreenshotsPref);
2188 Services.prefs.addObserver(COMPONENT_PREF, _checkScreenshotsPref);
2189 _checkScreenshotsPref();
2192 _monitorWebcompatReporterPref() {
2193 const PREF = "extensions.webcompat-reporter.enabled";
2194 const ID = "webcompat-reporter@mozilla.org";
2195 Services.prefs.addObserver(PREF, async () => {
2196 let addon = await lazy.AddonManager.getAddonByID(ID);
2200 let enabled = Services.prefs.getBoolPref(PREF, false);
2201 if (enabled && !addon.isActive) {
2202 await addon.enable({ allowSystemAddons: true });
2203 } else if (!enabled && addon.isActive) {
2204 await addon.disable({ allowSystemAddons: true });
2209 async _setupSearchDetection() {
2210 // There is no pref for this add-on because it shouldn't be disabled.
2211 const ID = "addons-search-detection@mozilla.com";
2213 let addon = await lazy.AddonManager.getAddonByID(ID);
2215 // first time install of addon and install on firefox update
2217 (await lazy.AddonManager.maybeInstallBuiltinAddon(
2220 "resource://builtin-addons/search-detection/"
2223 if (!addon.isActive) {
2228 _monitorHTTPSOnlyPref() {
2229 const PREF_ENABLED = "dom.security.https_only_mode";
2230 const PREF_WAS_ENABLED = "dom.security.https_only_mode_ever_enabled";
2231 const _checkHTTPSOnlyPref = async () => {
2232 const enabled = Services.prefs.getBoolPref(PREF_ENABLED, false);
2233 const was_enabled = Services.prefs.getBoolPref(PREF_WAS_ENABLED, false);
2237 Services.prefs.setBoolPref(PREF_WAS_ENABLED, true);
2238 } else if (was_enabled) {
2241 Services.telemetry.scalarSet("security.https_only_mode_enabled", value);
2244 Services.prefs.addObserver(PREF_ENABLED, _checkHTTPSOnlyPref);
2245 _checkHTTPSOnlyPref();
2247 const PREF_PBM_WAS_ENABLED =
2248 "dom.security.https_only_mode_ever_enabled_pbm";
2249 const PREF_PBM_ENABLED = "dom.security.https_only_mode_pbm";
2251 const _checkHTTPSOnlyPBMPref = async () => {
2252 const enabledPBM = Services.prefs.getBoolPref(PREF_PBM_ENABLED, false);
2253 const was_enabledPBM = Services.prefs.getBoolPref(
2254 PREF_PBM_WAS_ENABLED,
2260 Services.prefs.setBoolPref(PREF_PBM_WAS_ENABLED, true);
2261 } else if (was_enabledPBM) {
2264 Services.telemetry.scalarSet(
2265 "security.https_only_mode_enabled_pbm",
2270 Services.prefs.addObserver(PREF_PBM_ENABLED, _checkHTTPSOnlyPBMPref);
2271 _checkHTTPSOnlyPBMPref();
2275 const PREF_ION_ID = "toolkit.telemetry.pioneerId";
2277 const _checkIonPref = async () => {
2278 for (let win of Services.wm.getEnumerator("navigator:browser")) {
2279 win.document.getElementById("ion-button").hidden =
2280 !Services.prefs.getStringPref(PREF_ION_ID, null);
2284 const windowListener = {
2285 onOpenWindow(xulWindow) {
2286 const win = xulWindow.docShell.domWindow;
2287 win.addEventListener("load", () => {
2288 const ionButton = win.document.getElementById("ion-button");
2290 ionButton.hidden = !Services.prefs.getStringPref(PREF_ION_ID, null);
2297 Services.prefs.addObserver(PREF_ION_ID, _checkIonPref);
2298 Services.wm.addListener(windowListener);
2302 _monitorIonStudies() {
2303 const STUDY_ADDON_COLLECTION_KEY = "pioneer-study-addons-v1";
2304 const PREF_ION_NEW_STUDIES_AVAILABLE =
2305 "toolkit.telemetry.pioneer-new-studies-available";
2307 const _badgeIcon = async () => {
2308 for (let win of Services.wm.getEnumerator("navigator:browser")) {
2310 .getElementById("ion-button")
2311 .querySelector(".toolbarbutton-badge")
2312 .classList.add("feature-callout");
2316 const windowListener = {
2317 onOpenWindow(xulWindow) {
2318 const win = xulWindow.docShell.domWindow;
2319 win.addEventListener("load", () => {
2320 const ionButton = win.document.getElementById("ion-button");
2322 const badge = ionButton.querySelector(".toolbarbutton-badge");
2324 Services.prefs.getBoolPref(PREF_ION_NEW_STUDIES_AVAILABLE, false)
2326 badge.classList.add("feature-callout");
2328 badge.classList.remove("feature-callout");
2336 // Update all open windows if the pref changes.
2337 Services.prefs.addObserver(PREF_ION_NEW_STUDIES_AVAILABLE, _badgeIcon);
2339 // Badge any currently-open windows.
2340 if (Services.prefs.getBoolPref(PREF_ION_NEW_STUDIES_AVAILABLE, false)) {
2344 lazy.RemoteSettings(STUDY_ADDON_COLLECTION_KEY).on("sync", async () => {
2345 Services.prefs.setBoolPref(PREF_ION_NEW_STUDIES_AVAILABLE, true);
2348 // When a new window opens, check if we need to badge the icon.
2349 Services.wm.addListener(windowListener);
2353 const FEATURE_PREF_ENABLED = "privacy.globalprivacycontrol.enabled";
2354 const FUNCTIONALITY_PREF_ENABLED =
2355 "privacy.globalprivacycontrol.functionality.enabled";
2356 const PREF_WAS_ENABLED = "privacy.globalprivacycontrol.was_ever_enabled";
2357 const _checkGPCPref = async () => {
2358 const feature_enabled = Services.prefs.getBoolPref(
2359 FEATURE_PREF_ENABLED,
2362 const functionality_enabled = Services.prefs.getBoolPref(
2363 FUNCTIONALITY_PREF_ENABLED,
2366 const was_enabled = Services.prefs.getBoolPref(PREF_WAS_ENABLED, false);
2368 if (feature_enabled && functionality_enabled) {
2370 Services.prefs.setBoolPref(PREF_WAS_ENABLED, true);
2371 } else if (was_enabled) {
2374 Services.telemetry.scalarSet(
2375 "security.global_privacy_control_enabled",
2380 Services.prefs.addObserver(FEATURE_PREF_ENABLED, _checkGPCPref);
2381 Services.prefs.addObserver(FUNCTIONALITY_PREF_ENABLED, _checkGPCPref);
2385 // All initial windows have opened.
2386 _onWindowsRestored: function BG__onWindowsRestored() {
2387 if (this._windowsWereRestored) {
2390 this._windowsWereRestored = true;
2392 lazy.BrowserUsageTelemetry.init();
2393 lazy.SearchSERPTelemetry.init();
2395 lazy.Interactions.init();
2396 lazy.PageDataService.init();
2397 lazy.ExtensionsUI.init();
2399 let signingRequired;
2400 if (AppConstants.MOZ_REQUIRE_SIGNING) {
2401 signingRequired = true;
2403 signingRequired = Services.prefs.getBoolPref(
2404 "xpinstall.signatures.required"
2408 if (signingRequired) {
2409 let disabledAddons = lazy.AddonManager.getStartupChanges(
2410 lazy.AddonManager.STARTUP_CHANGE_DISABLED
2412 lazy.AddonManager.getAddonsByIDs(disabledAddons).then(addons => {
2413 for (let addon of addons) {
2414 if (addon.signedState <= lazy.AddonManager.SIGNEDSTATE_MISSING) {
2415 this._notifyUnsignedAddonsDisabled();
2422 if (AppConstants.MOZ_CRASHREPORTER) {
2423 lazy.UnsubmittedCrashHandler.init();
2424 lazy.UnsubmittedCrashHandler.scheduleCheckForUnsubmittedCrashReports();
2425 lazy.FeatureGate.annotateCrashReporter();
2426 lazy.FeatureGate.observePrefChangesForCrashReportAnnotation();
2429 if (AppConstants.ASAN_REPORTER) {
2430 var { AsanReporter } = ChromeUtils.importESModule(
2431 "resource://gre/modules/AsanReporter.sys.mjs"
2433 AsanReporter.init();
2436 lazy.Sanitizer.onStartup();
2437 this._maybeShowRestoreSessionInfoBar();
2438 this._scheduleStartupIdleTasks();
2439 this._lateTasksIdleObserver = (idleService, topic) => {
2440 if (topic == "idle") {
2441 idleService.removeIdleObserver(
2442 this._lateTasksIdleObserver,
2443 LATE_TASKS_IDLE_TIME_SEC
2445 delete this._lateTasksIdleObserver;
2446 this._scheduleBestEffortUserIdleTasks();
2449 this._userIdleService.addIdleObserver(
2450 this._lateTasksIdleObserver,
2451 LATE_TASKS_IDLE_TIME_SEC
2454 this._monitorWebcompatReporterPref();
2455 this._monitorHTTPSOnlyPref();
2456 this._monitorIonPref();
2457 this._monitorIonStudies();
2458 this._setupSearchDetection();
2460 this._monitorGPCPref();
2462 // Loading the MigrationUtils module does the work of registering the
2463 // migration wizard JSWindowActor pair. In case nothing else has done
2464 // this yet, load the MigrationUtils so that the wizard is ready to be
2466 lazy.MigrationUtils;
2470 * Use this function as an entry point to schedule tasks that
2471 * need to run only once after startup, and can be scheduled
2472 * by using an idle callback.
2474 * The functions scheduled here will fire from idle callbacks
2475 * once every window has finished being restored by session
2476 * restore, and it's guaranteed that they will run before
2477 * the equivalent per-window idle tasks
2478 * (from _schedulePerWindowIdleTasks in browser.js).
2480 * If you have something that can wait even further than the
2481 * per-window initialization, and is okay with not being run in some
2482 * sessions, please schedule them using
2483 * _scheduleBestEffortUserIdleTasks.
2484 * Don't be fooled by thinking that the use of the timeout parameter
2485 * will delay your function: it will just ensure that it potentially
2486 * happens _earlier_ than expected (when the timeout limit has been reached),
2487 * but it will not make it happen later (and out of order) compared
2488 * to the other ones scheduled together.
2490 _scheduleStartupIdleTasks() {
2492 // It's important that SafeBrowsing is initialized reasonably
2493 // early, so we use a maximum timeout for it.
2495 name: "SafeBrowsing.init",
2497 lazy.SafeBrowsing.init();
2503 name: "ContextualIdentityService.load",
2505 await lazy.ContextualIdentityService.load();
2506 lazy.Discovery.update();
2511 name: "PlacesUIUtils.unblockToolbars",
2513 // We postponed loading bookmarks toolbar content until startup
2514 // has finished, so we can start loading it now:
2515 lazy.PlacesUIUtils.unblockToolbars();
2520 name: "PlacesDBUtils.telemetry",
2521 condition: lazy.TelemetryUtils.isTelemetryEnabled,
2523 lazy.PlacesDBUtils.telemetry().catch(console.error);
2527 // Begin listening for incoming push messages.
2529 name: "PushService.ensureReady",
2532 lazy.PushService.wrappedJSObject.ensureReady();
2534 // NS_ERROR_NOT_AVAILABLE will get thrown for the PushService
2535 // getter if the PushService is disabled.
2536 if (ex.result != Cr.NS_ERROR_NOT_AVAILABLE) {
2544 name: "BrowserGlue._recordContentBlockingTelemetry",
2546 this._recordContentBlockingTelemetry();
2551 name: "BrowserGlue._recordDataSanitizationPrefs",
2553 this._recordDataSanitizationPrefs();
2558 name: "enableCertErrorUITelemetry",
2560 let enableCertErrorUITelemetry = Services.prefs.getBoolPref(
2561 "security.certerrors.recordEventTelemetry",
2564 Services.telemetry.setEventRecordingEnabled(
2565 "security.ui.certerror",
2566 enableCertErrorUITelemetry
2568 Services.telemetry.setEventRecordingEnabled(
2569 "security.ui.tlserror",
2570 enableCertErrorUITelemetry
2575 // Load the Login Manager data from disk off the main thread, some time
2576 // after startup. If the data is required before this runs, for example
2577 // because a restored page contains a password field, it will be loaded on
2578 // the main thread, and this initialization request will be ignored.
2580 name: "Services.logins",
2591 // Add breach alerts pref observer reasonably early so the pref flip works
2593 name: "_addBreachAlertsPrefObserver",
2595 this._addBreachAlertsPrefObserver();
2599 // Report pinning status and the type of shortcut used to launch
2601 name: "pinningStatusTelemetry",
2602 condition: AppConstants.platform == "win",
2604 let shellService = Cc[
2605 "@mozilla.org/browser/shell-service;1"
2606 ].getService(Ci.nsIWindowsShellService);
2607 let winTaskbar = Cc["@mozilla.org/windows-taskbar;1"].getService(
2612 Services.telemetry.scalarSet(
2613 "os.environment.is_taskbar_pinned",
2614 await shellService.isCurrentAppPinnedToTaskbarAsync(
2615 winTaskbar.defaultGroupId
2618 Services.telemetry.scalarSet(
2619 "os.environment.is_taskbar_pinned_private",
2620 await shellService.isCurrentAppPinnedToTaskbarAsync(
2621 winTaskbar.defaultPrivateGroupId
2631 shortcut = Services.appinfo.processStartupShortcut;
2632 classification = shellService.classifyShortcut(shortcut);
2637 if (!classification) {
2638 if (gThisInstanceIsLaunchOnLogin) {
2639 classification = "Autostart";
2640 } else if (shortcut) {
2641 classification = "OtherShortcut";
2643 classification = "Other";
2646 // Because of how taskbar tabs work, it may be classifed as a taskbar
2647 // shortcut, in which case we want to overwrite it.
2648 if (gThisInstanceIsTaskbarTab) {
2649 classification = "TaskbarTab";
2651 Services.telemetry.scalarSet(
2652 "os.environment.launch_method",
2659 name: "firefoxBridgeNativeMessaging",
2661 (AppConstants.platform == "macosx" ||
2662 AppConstants.platform == "win") &&
2663 Services.prefs.getBoolPref("browser.firefoxbridge.enabled", false),
2665 await lazy.FirefoxBridgeExtensionUtils.ensureRegistered();
2669 // Ensure a Private Browsing Shortcut exists. This is needed in case
2670 // a user tries to use Windows functionality to pin our Private Browsing
2671 // mode icon to the Taskbar (eg: the "Pin to Taskbar" context menu item).
2672 // This is also created by the installer, but it's possible that a user
2673 // has removed it, or is running out of a zip build. The consequences of not
2674 // having a Shortcut for this are that regular Firefox will be pinned instead
2675 // of the Private Browsing version -- so it's quite important we do our best
2676 // to make sure one is available.
2677 // See https://bugzilla.mozilla.org/show_bug.cgi?id=1762994 for additional
2680 name: "ensurePrivateBrowsingShortcutExists",
2682 AppConstants.platform == "win" &&
2683 // Pref'ed off until Private Browsing window separation is enabled by default
2684 // to avoid a situation where a user pins the Private Browsing shortcut to
2685 // the Taskbar, which will end up launching into a different Taskbar icon.
2686 lazy.NimbusFeatures.majorRelease2022.getVariable(
2687 "feltPrivacyWindowSeparation"
2689 // We don't want a shortcut if it's been disabled, eg: by enterprise policy.
2690 lazy.PrivateBrowsingUtils.enabled &&
2691 // Private Browsing shortcuts for packaged builds come with the package,
2692 // if they exist at all. We shouldn't try to create our own.
2693 !Services.sysinfo.getProperty("hasWinPackageId") &&
2694 // If we've ever done this successfully before, don't try again. The
2695 // user may have deleted the shortcut, and we don't want to force it
2697 !Services.prefs.getBoolPref(
2698 PREF_PRIVATE_BROWSING_SHORTCUT_CREATED,
2702 let shellService = Cc[
2703 "@mozilla.org/browser/shell-service;1"
2704 ].getService(Ci.nsIWindowsShellService);
2705 let winTaskbar = Cc["@mozilla.org/windows-taskbar;1"].getService(
2710 !(await shellService.hasMatchingShortcut(
2711 winTaskbar.defaultPrivateGroupId,
2715 let appdir = Services.dirsvc.get("GreD", Ci.nsIFile);
2716 let exe = appdir.clone();
2717 exe.append(PRIVATE_BROWSING_BINARY);
2718 let strings = new Localization(
2719 ["branding/brand.ftl", "browser/browser.ftl"],
2722 let [desc] = await strings.formatValues([
2723 "private-browsing-shortcut-text-2",
2725 await shellService.createShortcut(
2730 // The code we're calling indexes from 0 instead of 1
2731 PRIVATE_BROWSING_EXE_ICON_INDEX - 1,
2732 winTaskbar.defaultPrivateGroupId,
2738 // We always set this as long as no exception has been thrown. This
2739 // ensure that it is `true` both if we created one because it didn't
2740 // exist, or if it already existed (most likely because it was created
2741 // by the installer). This avoids the need to call `hasMatchingShortcut`
2742 // again, which necessarily does pointless I/O.
2743 Services.prefs.setBoolPref(
2744 PREF_PRIVATE_BROWSING_SHORTCUT_CREATED,
2750 // Report whether Firefox is the default handler for various files types,
2751 // in particular, ".pdf".
2753 name: "IsDefaultHandlerForPDF",
2754 condition: AppConstants.platform == "win",
2756 Services.telemetry.keyedScalarSet(
2757 "os.environment.is_default_handler",
2759 lazy.ShellService.isDefaultHandlerFor(".pdf")
2764 // Install built-in themes. We already installed the active built-in
2765 // theme, if any, before UI startup.
2767 name: "BuiltInThemes.ensureBuiltInThemes",
2769 await lazy.BuiltInThemes.ensureBuiltInThemes();
2774 name: "WinTaskbarJumpList.startup",
2775 condition: AppConstants.platform == "win",
2777 // For Windows 7, initialize the jump list module.
2778 const WINTASKBAR_CONTRACTID = "@mozilla.org/windows-taskbar;1";
2780 WINTASKBAR_CONTRACTID in Cc &&
2781 Cc[WINTASKBAR_CONTRACTID].getService(Ci.nsIWinTaskbar).available
2783 const { WinTaskbarJumpList } = ChromeUtils.importESModule(
2784 "resource:///modules/WindowsJumpLists.sys.mjs"
2786 WinTaskbarJumpList.startup();
2791 // Report macOS Dock status
2793 name: "MacDockSupport.isAppInDock",
2794 condition: AppConstants.platform == "macosx",
2797 Services.telemetry.scalarSet(
2798 "os.environment.is_kept_in_dock",
2799 Cc["@mozilla.org/widget/macdocksupport;1"].getService(
2800 Ci.nsIMacDockSupport
2810 name: "BrowserGlue._maybeShowDefaultBrowserPrompt",
2812 this._maybeShowDefaultBrowserPrompt();
2817 name: "BrowserGlue._monitorScreenshotsPref",
2819 this._monitorScreenshotsPref();
2824 name: "trackStartupCrashEndSetTimeout",
2826 lazy.setTimeout(function () {
2827 Services.tm.idleDispatchToMainThread(
2828 Services.startup.trackStartupCrashEnd
2830 }, STARTUP_CRASHES_END_DELAY_MS);
2835 name: "handlerService.asyncInit",
2837 let handlerService = Cc[
2838 "@mozilla.org/uriloader/handler-service;1"
2839 ].getService(Ci.nsIHandlerService);
2840 handlerService.asyncInit();
2845 name: "RFPHelper.init",
2847 lazy.RFPHelper.init();
2852 name: "Blocklist.loadBlocklistAsync",
2854 lazy.Blocklist.loadBlocklistAsync();
2859 name: "TabUnloader.init",
2861 lazy.TabUnloader.init();
2865 // Run TRR performance measurements for DoH.
2867 name: "doh-rollout.trrRacer.run",
2869 let enabledPref = "doh-rollout.trrRace.enabled";
2870 let completePref = "doh-rollout.trrRace.complete";
2872 if (Services.prefs.getBoolPref(enabledPref, false)) {
2873 if (!Services.prefs.getBoolPref(completePref, false)) {
2874 new lazy.TRRRacer().run(() => {
2875 Services.prefs.setBoolPref(completePref, true);
2879 Services.prefs.addObserver(enabledPref, function observer() {
2880 if (Services.prefs.getBoolPref(enabledPref, false)) {
2881 Services.prefs.removeObserver(enabledPref, observer);
2883 if (!Services.prefs.getBoolPref(completePref, false)) {
2884 new lazy.TRRRacer().run(() => {
2885 Services.prefs.setBoolPref(completePref, true);
2894 // FOG doesn't need to be initialized _too_ early because it has a
2897 name: "initializeFOG",
2899 Services.fog.initializeFOG();
2901 // Register Glean to listen for experiment updates releated to the
2902 // "gleanInternalSdk" feature defined in the t/c/nimbus/FeatureManifest.yaml
2903 // This feature is intended for internal Glean use only. For features wishing
2904 // to set a remote metric configuration, please use the "glean" feature for
2905 // the purpose of setting the data-control-plane features via Server Knobs.
2906 lazy.NimbusFeatures.gleanInternalSdk.onUpdate(() => {
2907 let cfg = lazy.NimbusFeatures.gleanInternalSdk.getVariable(
2908 "gleanMetricConfiguration"
2910 Services.fog.setMetricsFeatureConfig(JSON.stringify(cfg));
2913 // Register Glean to listen for experiment updates releated to the
2914 // "glean" feature defined in the t/c/nimbus/FeatureManifest.yaml
2915 lazy.NimbusFeatures.glean.onUpdate(() => {
2916 let cfg = lazy.NimbusFeatures.glean.getVariable(
2917 "gleanMetricConfiguration"
2919 Services.fog.setMetricsFeatureConfig(JSON.stringify(cfg));
2924 // Add the import button if this is the first startup.
2926 name: "PlacesUIUtils.ImportButton",
2928 // First check if we've already added the import button, in which
2929 // case we should check for events indicating we can remove it.
2931 Services.prefs.getBoolPref(
2932 "browser.bookmarks.addedImportButton",
2936 lazy.PlacesUIUtils.removeImportButtonWhenImportSucceeds();
2940 // Otherwise, check if this is a new profile where we need to add it.
2941 // `maybeAddImportButton` will call
2942 // `removeImportButtonWhenImportSucceeds`itself if/when it adds the
2943 // button. Doing things in this order avoids listening for removal
2946 this._isNewProfile &&
2947 // Not in automation: the button changes CUI state, breaking tests
2950 await lazy.PlacesUIUtils.maybeAddImportButton();
2955 // Add the setup button if this is the first startup
2957 name: "AWToolbarButton.SetupButton",
2960 // Not in automation: the button changes CUI state,
2961 // breaking tests. Check this first, so that the module
2962 // doesn't load if it doesn't have to.
2963 !Cu.isInAutomation &&
2964 lazy.AWToolbarButton.hasToolbarButtonEnabled
2966 await lazy.AWToolbarButton.maybeAddSetupButton();
2972 name: "ASRouterNewTabHook.createInstance",
2974 lazy.ASRouterNewTabHook.createInstance(lazy.ASRouterDefaultConfig());
2979 name: "BackgroundUpdate",
2980 condition: AppConstants.MOZ_UPDATE_AGENT,
2982 // Never in automation! This is close to
2983 // `UpdateService.disabledForTesting`, but without creating the
2984 // service, which can perform a good deal of I/O in order to log its
2985 // state. Since this is in the startup path, we avoid all of that.
2986 let disabledForTesting =
2987 (Cu.isInAutomation ||
2988 lazy.Marionette.running ||
2989 lazy.RemoteAgent.running) &&
2990 Services.prefs.getBoolPref("app.update.disabledForTesting", false);
2991 if (!disabledForTesting) {
2993 await lazy.BackgroundUpdate.scheduleFirefoxMessagingSystemTargetingSnapshotting();
2996 "There was an error scheduling Firefox Messaging System targeting snapshotting: ",
3000 await lazy.BackgroundUpdate.maybeScheduleBackgroundUpdateTask();
3005 // Login detection service is used in fission to identify high value sites.
3007 name: "LoginDetection.init",
3009 let loginDetection = Cc[
3010 "@mozilla.org/login-detection-service;1"
3011 ].createInstance(Ci.nsILoginDetectionService);
3012 loginDetection.init();
3017 name: "BrowserGlue._collectTelemetryPiPEnabled",
3019 this._collectTelemetryPiPEnabled();
3022 // Schedule a sync (if enabled) after we've loaded
3024 name: "WeaveService",
3026 if (lazy.WeaveService.enabled) {
3027 await lazy.WeaveService.whenLoaded();
3028 lazy.WeaveService.Weave.Service.scheduler.autoConnect();
3034 name: "unblock-untrusted-modules-thread",
3035 condition: AppConstants.platform == "win",
3037 Services.obs.notifyObservers(
3039 "unblock-untrusted-modules-thread"
3045 name: "UpdateListener.maybeShowUnsupportedNotification",
3046 condition: AppConstants.MOZ_UPDATER,
3048 lazy.UpdateListener.maybeShowUnsupportedNotification();
3053 name: "QuickSuggest.init",
3055 lazy.QuickSuggest.init();
3060 name: "DAPTelemetrySender.startup",
3062 lazy.TelemetryUtils.isTelemetryEnabled &&
3063 lazy.NimbusFeatures.dapTelemetry.getVariable("enabled"),
3065 lazy.DAPTelemetrySender.startup();
3070 name: "ShoppingUtils.init",
3072 lazy.ShoppingUtils.init();
3077 // Starts the JSOracle process for ORB JavaScript validation, if it hasn't started already.
3078 name: "start-orb-javascript-oracle",
3080 ChromeUtils.ensureJSOracleStarted();
3085 name: "SearchSERPDomainToCategoriesMap.init",
3087 lazy.SearchSERPDomainToCategoriesMap.init().catch(console.error);
3092 name: "BackupService initialization",
3093 condition: Services.prefs.getBoolPref("browser.backup.enabled", false),
3095 lazy.BackupService.init();
3100 name: "browser-startup-idle-tasks-finished",
3102 // Use idleDispatch a second time to run this after the per-window
3104 ChromeUtils.idleDispatch(() => {
3105 Services.obs.notifyObservers(
3107 "browser-startup-idle-tasks-finished"
3109 BrowserInitState._resolveStartupIdleTask();
3113 // Do NOT add anything after idle tasks finished.
3116 for (let task of idleTasks) {
3117 if ("condition" in task && !task.condition) {
3121 ChromeUtils.idleDispatch(
3123 if (!Services.startup.shuttingDown) {
3124 let startTime = Cu.now();
3130 ChromeUtils.addProfilerMarker(
3138 task.timeout ? { timeout: task.timeout } : undefined
3144 * Use this function as an entry point to schedule tasks that we hope
3145 * to run once per session, at any arbitrary point in time, and which we
3146 * are okay with sometimes not running at all.
3148 * This function will be called from an idle observer. Check the value of
3149 * LATE_TASKS_IDLE_TIME_SEC to see the current value for this idle
3152 * Note: this function may never be called if the user is never idle for the
3153 * requisite time (LATE_TASKS_IDLE_TIME_SEC). Be certain before adding
3154 * something here that it's okay that it never be run.
3156 _scheduleBestEffortUserIdleTasks() {
3158 function primaryPasswordTelemetry() {
3159 // Telemetry for primary-password - we do this after a delay as it
3160 // can cause IO if NSS/PSM has not already initialized.
3161 let tokenDB = Cc["@mozilla.org/security/pk11tokendb;1"].getService(
3164 let token = tokenDB.getInternalKeyToken();
3165 let mpEnabled = token.hasPassword;
3168 .getHistogramById("MASTER_PASSWORD_ENABLED")
3173 function GMPInstallManagerSimpleCheckAndInstall() {
3174 let { GMPInstallManager } = ChromeUtils.importESModule(
3175 "resource://gre/modules/GMPInstallManager.sys.mjs"
3177 this._gmpInstallManager = new GMPInstallManager();
3178 // We don't really care about the results, if someone is interested they
3179 // can check the log.
3180 this._gmpInstallManager.simpleCheckAndInstall().catch(() => {});
3183 function RemoteSettingsInit() {
3184 lazy.RemoteSettings.init();
3185 this._addBreachesSyncHandler();
3188 function PublicSuffixListInit() {
3189 lazy.PublicSuffixList.init();
3192 function RemoteSecuritySettingsInit() {
3193 lazy.RemoteSecuritySettings.init();
3196 function CorroborateInit() {
3197 if (Services.prefs.getBoolPref("corroborator.enabled", false)) {
3198 lazy.Corroborate.init().catch(console.error);
3202 function BrowserUsageTelemetryReportProfileCount() {
3203 lazy.BrowserUsageTelemetry.reportProfileCount();
3206 function reportAllowedAppSources() {
3207 lazy.OsEnvironment.reportAllowedAppSources();
3210 function searchBackgroundChecks() {
3211 Services.search.runBackgroundChecks();
3214 function reportInstallationTelemetry() {
3215 lazy.BrowserUsageTelemetry.reportInstallationTelemetry();
3219 for (let task of idleTasks) {
3220 ChromeUtils.idleDispatch(async () => {
3221 if (!Services.startup.shuttingDown) {
3222 let startTime = Cu.now();
3228 ChromeUtils.addProfilerMarker(
3229 "startupLateIdleTask",
3239 _addBreachesSyncHandler() {
3241 Services.prefs.getBoolPref(
3242 "signon.management.page.breach-alerts.enabled",
3247 .RemoteSettings(lazy.LoginBreaches.REMOTE_SETTINGS_COLLECTION)
3248 .on("sync", async event => {
3249 await lazy.LoginBreaches.update(event.data.current);
3254 _addBreachAlertsPrefObserver() {
3255 const BREACH_ALERTS_PREF = "signon.management.page.breach-alerts.enabled";
3256 const clearVulnerablePasswordsIfBreachAlertsDisabled = async function () {
3257 if (!Services.prefs.getBoolPref(BREACH_ALERTS_PREF)) {
3258 await lazy.LoginBreaches.clearAllPotentiallyVulnerablePasswords();
3261 clearVulnerablePasswordsIfBreachAlertsDisabled();
3262 Services.prefs.addObserver(
3264 clearVulnerablePasswordsIfBreachAlertsDisabled
3268 _quitSource: "unknown",
3269 _registerQuitSource(source) {
3270 this._quitSource = source;
3273 _onQuitRequest: function BG__onQuitRequest(aCancelQuit, aQuitType) {
3274 // If user has already dismissed quit request, then do nothing
3275 if (aCancelQuit instanceof Ci.nsISupportsPRBool && aCancelQuit.data) {
3279 // There are several cases where we won't show a dialog here:
3280 // 1. There is only 1 tab open in 1 window
3281 // 2. browser.warnOnQuit == false
3282 // 3. The browser is currently in Private Browsing mode
3283 // 4. The browser will be restarted.
3284 // 5. The user has automatic session restore enabled and
3285 // browser.sessionstore.warnOnQuit is not set to true.
3286 // 6. The user doesn't have automatic session restore enabled
3287 // and browser.tabs.warnOnClose is not set to true.
3289 // Otherwise, we will show the "closing multiple tabs" dialog.
3291 // aQuitType == "lastwindow" is overloaded. "lastwindow" is used to indicate
3292 // "the last window is closing but we're not quitting (a non-browser window is open)"
3293 // and also "we're quitting by closing the last window".
3295 if (aQuitType == "restart" || aQuitType == "os-restart") {
3299 // browser.warnOnQuit is a hidden global boolean to override all quit prompts.
3300 if (!Services.prefs.getBoolPref("browser.warnOnQuit")) {
3304 let windowcount = 0;
3306 let pinnedcount = 0;
3307 for (let win of lazy.BrowserWindowTracker.orderedWindows) {
3312 let tabbrowser = win.gBrowser;
3314 pinnedcount += tabbrowser._numPinnedTabs;
3315 pagecount += tabbrowser.visibleTabs.length - tabbrowser._numPinnedTabs;
3319 // No windows open so no need for a warning.
3324 // browser.warnOnQuitShortcut is checked when quitting using the shortcut key.
3325 // The warning will appear even when only one window/tab is open. For other
3326 // methods of quitting, the warning only appears when there is more than one
3327 // window or tab open.
3328 let shouldWarnForShortcut =
3329 this._quitSource == "shortcut" &&
3330 Services.prefs.getBoolPref("browser.warnOnQuitShortcut");
3331 let shouldWarnForTabs =
3332 pagecount >= 2 && Services.prefs.getBoolPref("browser.tabs.warnOnClose");
3333 if (!shouldWarnForTabs && !shouldWarnForShortcut) {
3341 let win = lazy.BrowserWindowTracker.getTopWindow();
3343 // Our prompt for quitting is most important, so replace others.
3344 win.gDialogBox.replaceDialogIfOpen();
3346 let titleId, buttonLabelId;
3347 if (windowcount > 1) {
3348 // More than 1 window. Compose our own message.
3350 id: "tabbrowser-confirm-close-windows-title",
3351 args: { windowCount: windowcount },
3353 buttonLabelId = "tabbrowser-confirm-close-windows-button";
3354 } else if (shouldWarnForShortcut) {
3355 titleId = "tabbrowser-confirm-close-tabs-with-key-title";
3356 buttonLabelId = "tabbrowser-confirm-close-tabs-with-key-button";
3359 id: "tabbrowser-confirm-close-tabs-title",
3360 args: { tabCount: pagecount },
3362 buttonLabelId = "tabbrowser-confirm-close-tabs-button";
3365 // The checkbox label is different depending on whether the shortcut
3366 // was used to quit or not.
3367 let checkboxLabelId;
3368 if (shouldWarnForShortcut) {
3369 const quitKeyElement = win.document.getElementById("key_quitApplication");
3370 const quitKey = lazy.ShortcutUtils.prettifyShortcut(quitKeyElement);
3372 id: "tabbrowser-confirm-close-tabs-with-key-checkbox",
3376 checkboxLabelId = "tabbrowser-confirm-close-tabs-checkbox";
3379 const [title, buttonLabel, checkboxLabel] =
3380 win.gBrowser.tabLocalization.formatMessagesSync([
3386 let warnOnClose = { value: true };
3388 Services.prompt.BUTTON_TITLE_IS_STRING * Services.prompt.BUTTON_POS_0 +
3389 Services.prompt.BUTTON_TITLE_CANCEL * Services.prompt.BUTTON_POS_1;
3390 // buttonPressed will be 0 for closing, 1 for cancel (don't close/quit)
3391 let buttonPressed = Services.prompt.confirmEx(
3399 checkboxLabel.value,
3402 Services.telemetry.setEventRecordingEnabled("close_tab_warning", true);
3403 let warnCheckbox = warnOnClose.value ? "checked" : "unchecked";
3405 let sessionWillBeRestored =
3406 Services.prefs.getIntPref("browser.startup.page") == 3 ||
3407 Services.prefs.getBoolPref("browser.sessionstore.resume_session_once");
3408 Services.telemetry.recordEvent(
3409 "close_tab_warning",
3414 source: this._quitSource,
3415 button: buttonPressed == 0 ? "close" : "cancel",
3416 warn_checkbox: warnCheckbox,
3417 closing_wins: "" + windowcount,
3418 closing_tabs: "" + (pagecount + pinnedcount),
3419 will_restore: sessionWillBeRestored ? "yes" : "no",
3423 // If the user has unticked the box, and has confirmed closing, stop showing
3425 if (buttonPressed == 0 && !warnOnClose.value) {
3426 if (shouldWarnForShortcut) {
3427 Services.prefs.setBoolPref("browser.warnOnQuitShortcut", false);
3429 Services.prefs.setBoolPref("browser.tabs.warnOnClose", false);
3433 this._quitSource = "unknown";
3435 aCancelQuit.data = buttonPressed != 0;
3440 * - imports the bookmarks html file if bookmarks database is empty, try to
3441 * restore bookmarks from a JSON backup if the backend indicates that the
3442 * database was corrupt.
3444 * These prefs can be set up by the frontend:
3446 * WARNING: setting these preferences to true will overwite existing bookmarks
3448 * - browser.places.importBookmarksHTML
3449 * Set to true will import the bookmarks.html file from the profile folder.
3450 * - browser.bookmarks.restore_default_bookmarks
3451 * Set to true by safe-mode dialog to indicate we must restore default
3454 _initPlaces: function BG__initPlaces(aInitialMigrationPerformed) {
3455 if (this._placesInitialized) {
3456 throw new Error("Cannot initialize Places more than once");
3458 this._placesInitialized = true;
3460 // We must instantiate the history service since it will tell us if we
3461 // need to import or restore bookmarks due to first-run, corruption or
3462 // forced migration (due to a major schema change).
3463 // If the database is corrupt or has been newly created we should
3464 // import bookmarks.
3465 let dbStatus = lazy.PlacesUtils.history.databaseStatus;
3467 // Show a notification with a "more info" link for a locked places.sqlite.
3468 if (dbStatus == lazy.PlacesUtils.history.DATABASE_STATUS_LOCKED) {
3469 // Note: initPlaces should always happen when the first window is ready,
3470 // in any case, better safe than sorry.
3471 this._firstWindowReady.then(() => {
3472 this._showPlacesLockedNotificationBox();
3473 this._placesBrowserInitComplete = true;
3474 Services.obs.notifyObservers(null, "places-browser-init-complete");
3479 let importBookmarks =
3480 !aInitialMigrationPerformed &&
3481 (dbStatus == lazy.PlacesUtils.history.DATABASE_STATUS_CREATE ||
3482 dbStatus == lazy.PlacesUtils.history.DATABASE_STATUS_CORRUPT);
3484 // Check if user or an extension has required to import bookmarks.html
3485 let importBookmarksHTML = false;
3487 importBookmarksHTML = Services.prefs.getBoolPref(
3488 "browser.places.importBookmarksHTML"
3490 if (importBookmarksHTML) {
3491 importBookmarks = true;
3495 // Support legacy bookmarks.html format for apps that depend on that format.
3496 let autoExportHTML = Services.prefs.getBoolPref(
3497 "browser.bookmarks.autoExportHTML",
3499 ); // Do not export.
3500 if (autoExportHTML) {
3501 // Sqlite.sys.mjs and Places shutdown happen at profile-before-change, thus,
3502 // to be on the safe side, this should run earlier.
3503 lazy.AsyncShutdown.profileChangeTeardown.addBlocker(
3504 "Places: export bookmarks.html",
3506 lazy.BookmarkHTMLUtils.exportToFile(
3507 lazy.BookmarkHTMLUtils.defaultPath
3513 // Check if Safe Mode or the user has required to restore bookmarks from
3514 // default profile's bookmarks.html
3515 let restoreDefaultBookmarks = false;
3517 restoreDefaultBookmarks = Services.prefs.getBoolPref(
3518 "browser.bookmarks.restore_default_bookmarks"
3520 if (restoreDefaultBookmarks) {
3521 // Ensure that we already have a bookmarks backup for today.
3522 await this._backupBookmarks();
3523 importBookmarks = true;
3527 // If the user did not require to restore default bookmarks, or import
3528 // from bookmarks.html, we will try to restore from JSON
3529 if (importBookmarks && !restoreDefaultBookmarks && !importBookmarksHTML) {
3530 // get latest JSON backup
3531 let lastBackupFile = await lazy.PlacesBackups.getMostRecentBackup();
3532 if (lastBackupFile) {
3533 // restore from JSON backup
3534 await lazy.BookmarkJSONUtils.importFromFile(lastBackupFile, {
3536 source: lazy.PlacesUtils.bookmarks.SOURCES.RESTORE_ON_STARTUP,
3538 importBookmarks = false;
3540 // We have created a new database but we don't have any backup available
3541 importBookmarks = true;
3542 if (await IOUtils.exists(lazy.BookmarkHTMLUtils.defaultPath)) {
3543 // If bookmarks.html is available in current profile import it...
3544 importBookmarksHTML = true;
3546 // ...otherwise we will restore defaults
3547 restoreDefaultBookmarks = true;
3552 // Import default bookmarks when necessary.
3553 // Otherwise, if any kind of import runs, default bookmarks creation should be
3554 // delayed till the import operations has finished. Not doing so would
3555 // cause them to be overwritten by the newly imported bookmarks.
3556 if (!importBookmarks) {
3557 // Now apply distribution customized bookmarks.
3558 // This should always run after Places initialization.
3560 await this._distributionCustomizer.applyBookmarks();
3565 // An import operation is about to run.
3566 let bookmarksUrl = null;
3567 if (restoreDefaultBookmarks) {
3568 // User wants to restore the default set of bookmarks shipped with the
3569 // browser, those that new profiles start with.
3570 bookmarksUrl = "chrome://browser/content/default-bookmarks.html";
3571 } else if (await IOUtils.exists(lazy.BookmarkHTMLUtils.defaultPath)) {
3572 bookmarksUrl = PathUtils.toFileURI(
3573 lazy.BookmarkHTMLUtils.defaultPath
3578 // Import from bookmarks.html file.
3581 Services.policies.isAllowed("defaultBookmarks") &&
3582 // Default bookmarks are imported after startup, and they may
3583 // influence the outcome of tests, thus it's possible to use
3584 // this test-only pref to skip the import.
3586 Cu.isInAutomation &&
3587 Services.prefs.getBoolPref(
3588 "browser.bookmarks.testing.skipDefaultBookmarksImport",
3593 await lazy.BookmarkHTMLUtils.importFromURL(bookmarksUrl, {
3595 source: lazy.PlacesUtils.bookmarks.SOURCES.RESTORE_ON_STARTUP,
3599 console.error("Bookmarks.html file could be corrupt. ", e);
3602 // Now apply distribution customized bookmarks.
3603 // This should always run after Places initialization.
3604 await this._distributionCustomizer.applyBookmarks();
3609 console.error(new Error("Unable to find bookmarks.html file."));
3612 // Reset preferences, so we won't try to import again at next run
3613 if (importBookmarksHTML) {
3614 Services.prefs.setBoolPref(
3615 "browser.places.importBookmarksHTML",
3619 if (restoreDefaultBookmarks) {
3620 Services.prefs.setBoolPref(
3621 "browser.bookmarks.restore_default_bookmarks",
3627 // Initialize bookmark archiving on idle.
3628 // If the last backup has been created before the last browser session,
3629 // and is days old, be more aggressive with the idle timer.
3630 let idleTime = BOOKMARKS_BACKUP_IDLE_TIME_SEC;
3631 if (!(await lazy.PlacesBackups.hasRecentBackup())) {
3634 this._userIdleService.addIdleObserver(this, idleTime);
3635 this._bookmarksBackupIdleTime = idleTime;
3637 if (this._isNewProfile) {
3638 // New profiles may have existing bookmarks (imported from another browser or
3639 // copied into the profile) and we want to show the bookmark toolbar for them
3641 await lazy.PlacesUIUtils.maybeToggleBookmarkToolbarVisibility();
3648 // NB: deliberately after the catch so that we always do this, even if
3649 // we threw halfway through initializing in the Task above.
3650 this._placesBrowserInitComplete = true;
3651 Services.obs.notifyObservers(null, "places-browser-init-complete");
3656 * If a backup for today doesn't exist, this creates one.
3658 _backupBookmarks: function BG__backupBookmarks() {
3659 return (async function () {
3660 let lastBackupFile = await lazy.PlacesBackups.getMostRecentBackup();
3661 // Should backup bookmarks if there are no backups or the maximum
3662 // interval between backups elapsed.
3665 new Date() - lazy.PlacesBackups.getDateForFile(lastBackupFile) >
3666 BOOKMARKS_BACKUP_MIN_INTERVAL_DAYS * 86400000
3668 let maxBackups = Services.prefs.getIntPref(
3669 "browser.bookmarks.max_backups"
3671 await lazy.PlacesBackups.create(maxBackups);
3677 * Show the notificationBox for a locked places database.
3679 _showPlacesLockedNotificationBox:
3680 async function BG__showPlacesLockedNotificationBox() {
3681 var win = lazy.BrowserWindowTracker.getTopWindow();
3682 var buttons = [{ supportPage: "places-locked" }];
3684 var notifyBox = win.gBrowser.getNotificationBox();
3685 var notification = await notifyBox.appendNotification(
3688 label: { "l10n-id": "places-locked-prompt" },
3689 priority: win.gNotificationBox.PRIORITY_CRITICAL_MEDIUM,
3693 notification.persistence = -1; // Until user closes it
3696 _onThisDeviceConnected() {
3697 const [title, body] = lazy.accountsL10n.formatValuesSync([
3698 "account-connection-title",
3699 "account-connection-connected",
3702 let clickCallback = (subject, topic) => {
3703 if (topic != "alertclickcallback") {
3706 this._openPreferences("sync");
3708 this.AlertsService.showAlertNotification(
3718 _migrateXULStoreForDocument(fromURL, toURL) {
3719 Array.from(Services.xulStore.getIDsEnumerator(fromURL)).forEach(id => {
3720 Array.from(Services.xulStore.getAttributeEnumerator(fromURL, id)).forEach(
3722 let value = Services.xulStore.getValue(fromURL, id, attr);
3723 Services.xulStore.setValue(toURL, id, attr, value);
3729 _migrateHashedKeysForXULStoreForDocument(docUrl) {
3730 Array.from(Services.xulStore.getIDsEnumerator(docUrl))
3731 .filter(id => id.startsWith("place:"))
3733 Services.xulStore.removeValue(docUrl, id, "open");
3734 let hashedId = lazy.PlacesUIUtils.obfuscateUrlForXulStore(id);
3735 Services.xulStore.setValue(docUrl, hashedId, "open", "true");
3739 // eslint-disable-next-line complexity
3741 // Use an increasing number to keep track of the current migration state.
3742 // Completely unrelated to the current Firefox release number.
3743 const UI_VERSION = 143;
3744 const BROWSER_DOCURL = AppConstants.BROWSER_CHROME_URL;
3746 if (!Services.prefs.prefHasUserValue("browser.migration.version")) {
3747 // This is a new profile, nothing to migrate.
3748 Services.prefs.setIntPref("browser.migration.version", UI_VERSION);
3749 this._isNewProfile = true;
3751 if (AppConstants.platform == "win") {
3752 // Ensure that the Firefox Bridge protocols are registered for the new profile.
3753 // No-op if they are registered for the user or the local machine already.
3754 lazy.FirefoxBridgeExtensionUtils.maybeRegisterFirefoxBridgeProtocols();
3760 this._isNewProfile = false;
3761 let currentUIVersion = Services.prefs.getIntPref(
3762 "browser.migration.version"
3764 if (currentUIVersion >= UI_VERSION) {
3768 let xulStore = Services.xulStore;
3770 if (currentUIVersion < 90) {
3771 this._migrateXULStoreForDocument(
3772 "chrome://browser/content/places/historySidebar.xul",
3773 "chrome://browser/content/places/historySidebar.xhtml"
3775 this._migrateXULStoreForDocument(
3776 "chrome://browser/content/places/places.xul",
3777 "chrome://browser/content/places/places.xhtml"
3779 this._migrateXULStoreForDocument(
3780 "chrome://browser/content/places/bookmarksSidebar.xul",
3781 "chrome://browser/content/places/bookmarksSidebar.xhtml"
3785 // Clear socks proxy values if they were shared from http, to prevent
3786 // websocket breakage after bug 1577862 (see bug 969282).
3788 currentUIVersion < 91 &&
3789 Services.prefs.getBoolPref("network.proxy.share_proxy_settings", false) &&
3790 Services.prefs.getIntPref("network.proxy.type", 0) == 1
3792 let httpProxy = Services.prefs.getCharPref("network.proxy.http", "");
3793 let httpPort = Services.prefs.getIntPref("network.proxy.http_port", 0);
3794 let socksProxy = Services.prefs.getCharPref("network.proxy.socks", "");
3795 let socksPort = Services.prefs.getIntPref("network.proxy.socks_port", 0);
3796 if (httpProxy && httpProxy == socksProxy && httpPort == socksPort) {
3797 Services.prefs.setCharPref(
3798 "network.proxy.socks",
3799 Services.prefs.getCharPref("network.proxy.backup.socks", "")
3801 Services.prefs.setIntPref(
3802 "network.proxy.socks_port",
3803 Services.prefs.getIntPref("network.proxy.backup.socks_port", 0)
3808 if (currentUIVersion < 92) {
3809 // privacy.userContext.longPressBehavior pref was renamed and changed to a boolean
3810 let longpress = Services.prefs.getIntPref(
3811 "privacy.userContext.longPressBehavior",
3814 if (longpress == 1) {
3815 Services.prefs.setBoolPref(
3816 "privacy.userContext.newTabContainerOnLeftClick.enabled",
3822 if (currentUIVersion < 93) {
3823 // The Gecko Profiler Addon is now an internal component. Remove the old
3824 // addon, and enable the new UI.
3826 function enableProfilerButton(wasAddonActive) {
3827 // Enable the feature pref. This will add it to the customization palette,
3828 // but not to the the navbar.
3829 Services.prefs.setBoolPref(
3830 "devtools.performance.popup.feature-flag",
3834 if (wasAddonActive) {
3835 const { ProfilerMenuButton } = ChromeUtils.importESModule(
3836 "resource://devtools/client/performance-new/popup/menu-button.sys.mjs"
3838 if (!ProfilerMenuButton.isInNavbar()) {
3839 // The profiler menu button is not enabled. Turn it on now.
3840 const win = lazy.BrowserWindowTracker.getTopWindow();
3841 if (win && win.document) {
3842 ProfilerMenuButton.addToNavbar(win.document);
3850 addonPromise = lazy.AddonManager.getAddonByID(
3851 "geckoprofiler@mozilla.com"
3855 "Could not access the AddonManager to upgrade the profile. This is most " +
3856 "likely because the upgrader is being run from an xpcshell test where " +
3857 "the AddonManager is not initialized."
3860 Promise.resolve(addonPromise).then(addon => {
3862 // Either the addon wasn't installed, or the call to getAddonByID failed.
3865 // Remove the old addon.
3866 const wasAddonActive = addon.isActive;
3869 .catch(console.error)
3870 .then(() => enableProfilerButton(wasAddonActive))
3871 .catch(console.error);
3875 // Clear unused socks proxy backup values - see bug 1625773.
3876 if (currentUIVersion < 94) {
3877 let backup = Services.prefs.getCharPref("network.proxy.backup.socks", "");
3878 let backupPort = Services.prefs.getIntPref(
3879 "network.proxy.backup.socks_port",
3882 let socksProxy = Services.prefs.getCharPref("network.proxy.socks", "");
3883 let socksPort = Services.prefs.getIntPref("network.proxy.socks_port", 0);
3884 if (backup == socksProxy) {
3885 Services.prefs.clearUserPref("network.proxy.backup.socks");
3887 if (backupPort == socksPort) {
3888 Services.prefs.clearUserPref("network.proxy.backup.socks_port");
3892 if (currentUIVersion < 95) {
3893 const oldPrefName = "media.autoplay.enabled.user-gestures-needed";
3894 const oldPrefValue = Services.prefs.getBoolPref(oldPrefName, true);
3895 const newPrefValue = oldPrefValue ? 0 : 1;
3896 Services.prefs.setIntPref("media.autoplay.blocking_policy", newPrefValue);
3897 Services.prefs.clearUserPref(oldPrefName);
3900 if (currentUIVersion < 96) {
3901 const oldPrefName = "browser.urlbar.openViewOnFocus";
3902 const oldPrefValue = Services.prefs.getBoolPref(oldPrefName, true);
3903 Services.prefs.setBoolPref(
3904 "browser.urlbar.suggest.topsites",
3907 Services.prefs.clearUserPref(oldPrefName);
3910 if (currentUIVersion < 97) {
3911 let userCustomizedWheelMax = Services.prefs.prefHasUserValue(
3912 "general.smoothScroll.mouseWheel.durationMaxMS"
3914 let userCustomizedWheelMin = Services.prefs.prefHasUserValue(
3915 "general.smoothScroll.mouseWheel.durationMinMS"
3918 if (!userCustomizedWheelMin && !userCustomizedWheelMax) {
3919 // If the user has an existing profile but hasn't customized the wheel
3920 // animation duration, they will now get the new default values. This
3921 // condition used to set a migrationPercent pref to 0, so that users
3922 // upgrading an older profile would gradually have their wheel animation
3923 // speed migrated to the new values. However, that "gradual migration"
3924 // was phased out by FF 86, so we don't need to set that pref anymore.
3925 } else if (userCustomizedWheelMin && !userCustomizedWheelMax) {
3926 // If they customized just one of the two, save the old value for the
3927 // other one as well, because the two values go hand-in-hand and we
3928 // don't want to move just one to a new value and leave the other one
3929 // at a customized value. In both of these cases, we leave the "migration
3930 // complete" percentage at 100, because they have customized this and
3931 // don't need any further migration.
3932 Services.prefs.setIntPref(
3933 "general.smoothScroll.mouseWheel.durationMaxMS",
3936 } else if (!userCustomizedWheelMin && userCustomizedWheelMax) {
3937 // Same as above case, but for the other pref.
3938 Services.prefs.setIntPref(
3939 "general.smoothScroll.mouseWheel.durationMinMS",
3943 // The last remaining case is if they customized both values, in which
3944 // case also don't need to do anything; the user's customized values
3945 // will be retained and respected.
3949 if (currentUIVersion < 98) {
3950 Services.prefs.clearUserPref("browser.search.cohort");
3953 if (currentUIVersion < 99) {
3954 Services.prefs.clearUserPref("security.tls.version.enable-deprecated");
3957 if (currentUIVersion < 102) {
3958 // In Firefox 83, we moved to a dynamic button, so it needs to be removed
3959 // from default placement. This is done early enough that it doesn't
3960 // impact adding new managed bookmarks.
3961 const { CustomizableUI } = ChromeUtils.importESModule(
3962 "resource:///modules/CustomizableUI.sys.mjs"
3964 CustomizableUI.removeWidgetFromArea("managed-bookmarks");
3967 // We have to rerun these because we had to use 102 on beta.
3968 // They were 101 and 102 before.
3969 if (currentUIVersion < 103) {
3970 // Set a pref if the bookmarks toolbar was already visible,
3971 // so we can keep it visible when navigating away from newtab
3972 let bookmarksToolbarWasVisible =
3973 Services.xulStore.getValue(
3978 if (bookmarksToolbarWasVisible) {
3979 // Migrate the user to the "always visible" value. See firefox.js for
3980 // the other possible states.
3981 Services.prefs.setCharPref(
3982 "browser.toolbars.bookmarks.visibility",
3986 Services.xulStore.removeValue(
3992 Services.prefs.clearUserPref(
3993 "browser.livebookmarks.migrationAttemptsLeft"
3997 // For existing profiles, continue putting bookmarks in the
3998 // "other bookmarks" folder.
3999 if (currentUIVersion < 104) {
4000 Services.prefs.setCharPref(
4001 "browser.bookmarks.defaultLocation",
4006 // Renamed and flipped the logic of a pref to make its purpose more clear.
4007 if (currentUIVersion < 105) {
4008 const oldPrefName = "browser.urlbar.imeCompositionClosesPanel";
4009 const oldPrefValue = Services.prefs.getBoolPref(oldPrefName, true);
4010 Services.prefs.setBoolPref(
4011 "browser.urlbar.keepPanelOpenDuringImeComposition",
4014 Services.prefs.clearUserPref(oldPrefName);
4017 // Initialize the new browser.urlbar.showSuggestionsBeforeGeneral pref.
4018 if (currentUIVersion < 106) {
4019 lazy.UrlbarPrefs.initializeShowSearchSuggestionsFirstPref();
4022 if (currentUIVersion < 107) {
4023 // Migrate old http URIs for mailto handlers to their https equivalents.
4024 // The handler service will do this. We need to wait with migrating
4025 // until the handler service has started up, so just set a pref here.
4026 const kPref = "browser.handlers.migrations";
4027 // We might have set up another migration further up. Create an array,
4028 // and drop empty strings resulting from the `split`:
4029 let migrations = Services.prefs
4030 .getCharPref(kPref, "")
4033 migrations.push("secure-mail");
4034 Services.prefs.setCharPref(kPref, migrations.join(","));
4037 if (currentUIVersion < 108) {
4038 // Migrate old ctrlTab pref to new ctrlTab pref
4039 let defaultValue = false;
4040 let oldPrefName = "browser.ctrlTab.recentlyUsedOrder";
4041 let oldPrefDefault = true;
4042 // Use old pref value if the user used Ctrl+Tab before, elsewise use new default value
4043 if (Services.prefs.getBoolPref("browser.engagement.ctrlTab.has-used")) {
4044 let newPrefValue = Services.prefs.getBoolPref(
4048 Services.prefs.setBoolPref(
4049 "browser.ctrlTab.sortByRecentlyUsed",
4053 Services.prefs.setBoolPref(
4054 "browser.ctrlTab.sortByRecentlyUsed",
4060 if (currentUIVersion < 109) {
4061 // Migrate old pref to new pref
4063 Services.prefs.prefHasUserValue("signon.recipes.remoteRecipesEnabled")
4065 // Fetch the previous value of signon.recipes.remoteRecipesEnabled and assign it to signon.recipes.remoteRecipes.enabled.
4066 Services.prefs.setBoolPref(
4067 "signon.recipes.remoteRecipes.enabled",
4068 Services.prefs.getBoolPref(
4069 "signon.recipes.remoteRecipesEnabled",
4073 //Then clear user pref
4074 Services.prefs.clearUserPref("signon.recipes.remoteRecipesEnabled");
4078 if (currentUIVersion < 120) {
4079 // Migrate old titlebar bool pref to new int-based one.
4080 const oldPref = "browser.tabs.drawInTitlebar";
4081 const newPref = "browser.tabs.inTitlebar";
4082 if (Services.prefs.prefHasUserValue(oldPref)) {
4083 // We may have int prefs for builds between bug 1736518 and bug 1739539.
4084 const oldPrefType = Services.prefs.getPrefType(oldPref);
4085 if (oldPrefType == Services.prefs.PREF_BOOL) {
4086 Services.prefs.setIntPref(
4088 Services.prefs.getBoolPref(oldPref) ? 1 : 0
4091 Services.prefs.setIntPref(
4093 Services.prefs.getIntPref(oldPref)
4096 Services.prefs.clearUserPref(oldPref);
4100 if (currentUIVersion < 121) {
4101 // Migrate stored uris and convert them to use hashed keys
4102 this._migrateHashedKeysForXULStoreForDocument(BROWSER_DOCURL);
4103 this._migrateHashedKeysForXULStoreForDocument(
4104 "chrome://browser/content/places/bookmarksSidebar.xhtml"
4106 this._migrateHashedKeysForXULStoreForDocument(
4107 "chrome://browser/content/places/historySidebar.xhtml"
4111 if (currentUIVersion < 122) {
4112 // Migrate xdg-desktop-portal pref from old to new prefs.
4114 const oldPref = "widget.use-xdg-desktop-portal";
4115 if (Services.prefs.getBoolPref(oldPref)) {
4116 Services.prefs.setIntPref(
4117 "widget.use-xdg-desktop-portal.file-picker",
4120 Services.prefs.setIntPref(
4121 "widget.use-xdg-desktop-portal.mime-handler",
4125 Services.prefs.clearUserPref(oldPref);
4129 // Bug 1745248: Due to multiple backouts, do not use UI Version 123
4130 // as this version is most likely set for the Nightly channel
4132 if (currentUIVersion < 124) {
4133 // Migrate "extensions.formautofill.available" and
4134 // "extensions.formautofill.creditCards.available" from old to new prefs
4135 const oldFormAutofillModule = "extensions.formautofill.available";
4136 const oldCreditCardsAvailable =
4137 "extensions.formautofill.creditCards.available";
4138 const newCreditCardsAvailable =
4139 "extensions.formautofill.creditCards.supported";
4140 const newAddressesAvailable =
4141 "extensions.formautofill.addresses.supported";
4142 if (Services.prefs.prefHasUserValue(oldFormAutofillModule)) {
4143 let moduleAvailability = Services.prefs.getCharPref(
4144 oldFormAutofillModule
4146 if (moduleAvailability == "on") {
4147 Services.prefs.setCharPref(newAddressesAvailable, moduleAvailability);
4148 Services.prefs.setCharPref(
4149 newCreditCardsAvailable,
4150 Services.prefs.getBoolPref(oldCreditCardsAvailable) ? "on" : "off"
4154 if (moduleAvailability == "off") {
4155 Services.prefs.setCharPref(
4156 newCreditCardsAvailable,
4159 Services.prefs.setCharPref(newAddressesAvailable, moduleAvailability);
4163 // after migrating, clear old prefs so we can remove them later.
4164 Services.prefs.clearUserPref(oldFormAutofillModule);
4165 Services.prefs.clearUserPref(oldCreditCardsAvailable);
4168 if (currentUIVersion < 125) {
4169 // Bug 1756243 - Clear PiP cached coordinates since we changed their
4170 // coordinate space.
4171 const PIP_PLAYER_URI =
4172 "chrome://global/content/pictureinpicture/player.xhtml";
4174 for (let value of ["left", "top", "width", "height"]) {
4175 Services.xulStore.removeValue(
4177 "picture-in-picture",
4182 console.error("Failed to clear XULStore PiP values: ", ex);
4186 function migrateXULAttributeToStyle(url, id, attr) {
4188 let value = Services.xulStore.getValue(url, id, attr);
4190 Services.xulStore.setValue(url, id, "style", `${attr}: ${value}px;`);
4193 console.error(`Error migrating ${id}'s ${attr} value: `, ex);
4197 // Bug 1792748 used version 129 with a buggy variant of the sidebar width
4198 // migration. This version is already in use in the nightly channel, so it
4199 // shouldn't be used.
4201 // Bug 1793366: migrate sidebar persisted attribute from width to style.
4202 if (currentUIVersion < 130) {
4203 migrateXULAttributeToStyle(BROWSER_DOCURL, "sidebar-box", "width");
4206 // Migration 131 was moved to 133 to allow for an uplift.
4208 if (currentUIVersion < 132) {
4209 // These attributes are no longer persisted, thus remove them from xulstore.
4211 "chrome://browser/content/places/bookmarkProperties.xhtml",
4212 "chrome://browser/content/places/bookmarkProperties2.xhtml",
4214 for (let attr of ["width", "screenX", "screenY"]) {
4215 xulStore.removeValue(url, "bookmarkproperties", attr);
4220 if (currentUIVersion < 133) {
4221 xulStore.removeValue(BROWSER_DOCURL, "urlbar-container", "width");
4224 // Migration 134 was removed because it was no longer necessary.
4226 if (currentUIVersion < 135 && AppConstants.platform == "linux") {
4227 // Avoid changing titlebar setting for users that used to had it off.
4229 if (!Services.prefs.prefHasUserValue("browser.tabs.inTitlebar")) {
4230 let de = Services.appinfo.desktopEnvironment;
4231 let oldDefault = de.includes("gnome") || de.includes("pantheon");
4233 Services.prefs.setIntPref("browser.tabs.inTitlebar", 0);
4237 console.error("Error migrating tabsInTitlebar setting", e);
4241 if (currentUIVersion < 136) {
4242 migrateXULAttributeToStyle(
4243 "chrome://browser/content/places/places.xhtml",
4249 if (currentUIVersion < 137) {
4250 // The default value for enabling smooth scrolls is now false if the
4251 // user prefers reduced motion. If the value was previously set, do
4252 // not reset it, but if it was not explicitly set preserve the old
4255 !Services.prefs.prefHasUserValue("general.smoothScroll") &&
4256 Services.appinfo.prefersReducedMotion
4258 Services.prefs.setBoolPref("general.smoothScroll", true);
4262 if (currentUIVersion < 138) {
4263 // Bug 1757297: Change scheme of all existing 'https-only-load-insecure'
4264 // permissions with https scheme to http scheme.
4267 .getAllByTypes(["https-only-load-insecure"])
4268 .filter(permission => permission.principal.schemeIs("https"))
4269 .forEach(permission => {
4270 const capability = permission.capability;
4271 const uri = permission.principal.URI.mutate()
4275 Services.scriptSecurityManager.createContentPrincipal(uri, {});
4276 Services.perms.removePermission(permission);
4277 Services.perms.addFromPrincipal(
4279 "https-only-load-insecure",
4284 console.error("Error migrating https-only-load-insecure permission", e);
4288 if (currentUIVersion < 139) {
4289 // Reset the default permissions to ALLOW_ACTION to rollback issues for
4290 // affected users, see Bug 1579517
4291 // originInfo in the format [origin, type]
4293 ["https://www.mozilla.org", "uitour"],
4294 ["https://support.mozilla.org", "uitour"],
4295 ["about:home", "uitour"],
4296 ["about:newtab", "uitour"],
4297 ["https://addons.mozilla.org", "install"],
4298 ["https://support.mozilla.org", "remote-troubleshooting"],
4299 ["about:welcome", "autoplay-media"],
4300 ].forEach(originInfo => {
4301 // Reset permission on the condition that it is set to
4302 // UNKNOWN_ACTION, we want to prevent resetting user
4303 // manipulated permissions
4305 Services.perms.UNKNOWN_ACTION ==
4306 Services.perms.testPermissionFromPrincipal(
4307 Services.scriptSecurityManager.createContentPrincipalFromOrigin(
4313 // Adding permissions which have default values does not create
4314 // new permissions, but rather remove the UNKNOWN_ACTION permission
4315 // overrides. User's not affected by Bug 1579517 will not be affected by this addition.
4316 Services.perms.addFromPrincipal(
4317 Services.scriptSecurityManager.createContentPrincipalFromOrigin(
4321 Services.perms.ALLOW_ACTION
4327 if (currentUIVersion < 140) {
4328 // Remove browser.fixup.alternate.enabled pref in Bug 1850902.
4329 Services.prefs.clearUserPref("browser.fixup.alternate.enabled");
4332 if (currentUIVersion < 141) {
4333 for (const filename of ["signons.sqlite", "signons.sqlite.corrupt"]) {
4334 const filePath = PathUtils.join(PathUtils.profileDir, filename);
4335 IOUtils.remove(filePath, { ignoreAbsent: true }).catch(console.error);
4339 if (currentUIVersion < 142) {
4340 // Bug 1860392 - Remove incorrectly persisted theming values from sidebar style.
4342 let value = xulStore.getValue(BROWSER_DOCURL, "sidebar-box", "style");
4344 // Remove custom properties.
4347 .filter(v => !v.trim().startsWith("--"))
4349 xulStore.setValue(BROWSER_DOCURL, "sidebar-box", "style", value);
4356 if (currentUIVersion < 143) {
4357 if (AppConstants.platform == "win") {
4358 // In Firefox 122, we enabled the firefox and firefox-private protocols.
4359 // We switched over to using firefox-bridge and firefox-private-bridge,
4360 // but we want to clean up the use of the other protocols.
4361 lazy.FirefoxBridgeExtensionUtils.maybeDeleteBridgeProtocolRegistryEntries();
4363 // Register the new firefox bridge related protocols now
4364 lazy.FirefoxBridgeExtensionUtils.maybeRegisterFirefoxBridgeProtocols();
4366 // Clean up the old user prefs from FX 122
4367 Services.prefs.clearUserPref(
4368 "network.protocol-handler.external.firefox"
4370 Services.prefs.clearUserPref(
4371 "network.protocol-handler.external.firefox-private"
4373 Services.prefs.clearUserPref("browser.shell.customProtocolsRegistered");
4377 // Update the migration version.
4378 Services.prefs.setIntPref("browser.migration.version", UI_VERSION);
4381 async _showUpgradeDialog() {
4382 const data = await lazy.OnboardingMessageProvider.getUpgradeMessage();
4383 const { gBrowser } = lazy.BrowserWindowTracker.getTopWindow();
4385 // We'll be adding a new tab open the tab-modal dialog in.
4388 const upgradeTabsProgressListener = {
4389 onLocationChange(aBrowser) {
4390 if (aBrowser === tab.linkedBrowser) {
4391 lazy.setTimeout(() => {
4392 // We're now far enough along in the load that we no longer have to
4393 // worry about a call to onLocationChange triggering SubDialog.abort,
4394 // so display the dialog
4396 type: "SHOW_SPOTLIGHT",
4399 lazy.SpecialMessageActions.handleAction(config, tab.linkedBrowser);
4401 gBrowser.removeTabsProgressListener(upgradeTabsProgressListener);
4407 // Make sure we're ready to show the dialog once onLocationChange gets
4409 gBrowser.addTabsProgressListener(upgradeTabsProgressListener);
4411 tab = gBrowser.addTrustedTab("about:home", {
4412 relatedToCurrent: true,
4415 gBrowser.selectedTab = tab;
4418 async _showAboutWelcomeModal() {
4419 const { gBrowser } = lazy.BrowserWindowTracker.getTopWindow();
4420 const data = await lazy.NimbusFeatures.aboutwelcome.getAllVariables();
4423 type: "SHOW_SPOTLIGHT",
4426 template: "multistage",
4427 id: data?.id || "ABOUT_WELCOME_MODAL",
4428 backdrop: data?.backdrop,
4429 screens: data?.screens,
4430 UTMTerm: data?.UTMTerm,
4435 lazy.SpecialMessageActions.handleAction(config, gBrowser);
4438 async _maybeShowDefaultBrowserPrompt() {
4439 // Highest priority is about:welcome window modal experiment
4440 // Second highest priority is the upgrade dialog, which can include a "primary
4441 // browser" request and is limited in various ways, e.g., major upgrades.
4443 lazy.BrowserHandler.firstRunProfile &&
4444 lazy.NimbusFeatures.aboutwelcome.getVariable("showModal")
4446 this._showAboutWelcomeModal();
4449 const dialogVersion = 106;
4450 const dialogVersionPref = "browser.startup.upgradeDialog.version";
4451 const dialogReason = await (async () => {
4452 if (!lazy.BrowserHandler.majorUpgrade) {
4455 const lastVersion = Services.prefs.getIntPref(dialogVersionPref, 0);
4456 if (lastVersion > dialogVersion) {
4457 return "newer-shown";
4459 if (lastVersion === dialogVersion) {
4460 return "already-shown";
4463 // Check the default branch as enterprise policies can set prefs there.
4464 const defaultPrefs = Services.prefs.getDefaultBranch("");
4466 !defaultPrefs.getBoolPref(
4467 "browser.messaging-system.whatsNewPanel.enabled",
4471 return "no-whatsNew";
4473 if (!defaultPrefs.getBoolPref("browser.aboutwelcome.enabled", true)) {
4474 return "no-welcome";
4476 if (!Services.policies.isAllowed("postUpdateCustomPage")) {
4477 return "disallow-postUpdate";
4480 const useMROnboarding =
4481 lazy.NimbusFeatures.majorRelease2022.getVariable("onboarding");
4482 const showUpgradeDialog =
4484 lazy.NimbusFeatures.upgradeDialog.getVariable("enabled");
4486 return showUpgradeDialog ? "" : "disabled";
4489 // Record why the dialog is showing or not.
4490 Services.telemetry.setEventRecordingEnabled("upgrade_dialog", true);
4491 Services.telemetry.recordEvent(
4495 dialogReason || "satisfied"
4498 // Show the upgrade dialog if allowed and remember the version.
4499 if (!dialogReason) {
4500 Services.prefs.setIntPref(dialogVersionPref, dialogVersion);
4501 this._showUpgradeDialog();
4505 const willPrompt = await DefaultBrowserCheck.willCheckDefaultBrowser(
4506 /* isStartupCheck */ true
4509 let win = lazy.BrowserWindowTracker.getTopWindow();
4510 DefaultBrowserCheck.prompt(win);
4511 } else if (await lazy.QuickSuggest.maybeShowOnboardingDialog()) {
4515 await lazy.ASRouter.waitForInitialized;
4516 lazy.ASRouter.sendTriggerMessage({
4518 lazy.BrowserWindowTracker.getTopWindow()?.gBrowser.selectedBrowser,
4519 // triggerId and triggerContext
4520 id: "defaultBrowserCheck",
4521 context: { willShowDefaultPrompt: willPrompt, source: "startup" },
4526 * Only show the infobar when canRestoreLastSession and the pref value == 1
4528 async _maybeShowRestoreSessionInfoBar() {
4529 let count = Services.prefs.getIntPref(
4530 "browser.startup.couldRestoreSession.count",
4533 if (count < 0 || count >= 2) {
4537 // We don't show the infobar right after the update which establishes this pref
4538 // Increment the counter so we can consider it next time
4539 Services.prefs.setIntPref(
4540 "browser.startup.couldRestoreSession.count",
4546 const win = lazy.BrowserWindowTracker.getTopWindow();
4547 // We've restarted at least once; we will show the notification if possible.
4548 // We can't do that if there's no session to restore, or this is a private window.
4550 !lazy.SessionStore.canRestoreLastSession ||
4551 lazy.PrivateBrowsingUtils.isWindowPrivate(win)
4556 Services.prefs.setIntPref(
4557 "browser.startup.couldRestoreSession.count",
4561 const messageFragment = win.document.createDocumentFragment();
4562 const message = win.document.createElement("span");
4563 const icon = win.document.createElement("img");
4564 icon.src = "chrome://browser/skin/menu.svg";
4565 icon.setAttribute("data-l10n-name", "icon");
4566 icon.className = "inline-icon";
4567 message.appendChild(icon);
4568 messageFragment.appendChild(message);
4569 win.document.l10n.setAttributes(
4571 "restore-session-startup-suggestion-message"
4576 "l10n-id": "restore-session-startup-suggestion-button",
4579 win.PanelUI.selectAndMarkItem([
4580 "appMenu-history-button",
4581 "appMenu-restoreSession",
4587 const notifyBox = win.gBrowser.getNotificationBox();
4588 const notification = await notifyBox.appendNotification(
4589 "startup-restore-session-suggestion",
4591 label: messageFragment,
4592 priority: notifyBox.PRIORITY_INFO_MEDIUM,
4596 // Don't allow it to be immediately hidden:
4597 notification.timeout = Date.now() + 3000;
4601 * Open preferences even if there are no open windows.
4603 _openPreferences(...args) {
4604 let chromeWindow = lazy.BrowserWindowTracker.getTopWindow();
4606 chromeWindow.openPreferences(...args);
4610 if (Services.appShell.hiddenDOMWindow.openPreferences) {
4611 Services.appShell.hiddenDOMWindow.openPreferences(...args);
4615 _openURLInNewWindow(url) {
4616 let urlString = Cc["@mozilla.org/supports-string;1"].createInstance(
4617 Ci.nsISupportsString
4619 urlString.data = url;
4620 return new Promise(resolve => {
4621 let win = Services.ww.openWindow(
4623 AppConstants.BROWSER_CHROME_URL,
4625 "chrome,all,dialog=no",
4628 win.addEventListener(
4639 * Called as an observer when Sync's "display URIs" notification is fired.
4641 * We open the received URIs in background tabs.
4643 async _onDisplaySyncURIs(data) {
4645 // The payload is wrapped weirdly because of how Sync does notifications.
4646 const URIs = data.wrappedJSObject.object;
4648 // win can be null, but it's ok, we'll assign it later in openTab()
4649 let win = lazy.BrowserWindowTracker.getTopWindow({ private: false });
4651 const openTab = async URI => {
4654 win = await this._openURLInNewWindow(URI.uri);
4655 let tabs = win.gBrowser.tabs;
4656 tab = tabs[tabs.length - 1];
4658 tab = win.gBrowser.addWebTab(URI.uri);
4660 tab.attention = true;
4664 const firstTab = await openTab(URIs[0]);
4665 await Promise.all(URIs.slice(1).map(URI => openTab(URI)));
4667 const deviceName = URIs[0].sender && URIs[0].sender.name;
4668 let titleL10nId, body;
4669 if (URIs.length == 1) {
4670 // Due to bug 1305895, tabs from iOS may not have device information, so
4671 // we have separate strings to handle those cases. (See Also
4672 // unnamedTabsArrivingNotificationNoDevice.body below)
4673 titleL10nId = deviceName
4675 id: "account-single-tab-arriving-from-device-title",
4676 args: { deviceName },
4678 : { id: "account-single-tab-arriving-title" };
4679 // Use the page URL as the body. We strip the fragment and query (after
4680 // the `?` and `#` respectively) to reduce size, and also format it the
4681 // same way that the url bar would.
4682 let url = URIs[0].uri.replace(/([?#]).*$/, "$1");
4683 const wasTruncated = url.length < URIs[0].uri.length;
4684 url = lazy.BrowserUIUtils.trimURL(url);
4686 body = await lazy.accountsL10n.formatValue(
4687 "account-single-tab-arriving-truncated-url",
4694 titleL10nId = { id: "account-multiple-tabs-arriving-title" };
4695 const allKnownSender = URIs.every(URI => URI.sender != null);
4696 const allSameDevice =
4698 URIs.every(URI => URI.sender.id == URIs[0].sender.id);
4700 if (allSameDevice) {
4701 bodyL10nId = deviceName
4702 ? "account-multiple-tabs-arriving-from-single-device"
4703 : "account-multiple-tabs-arriving-from-unknown-device";
4705 bodyL10nId = "account-multiple-tabs-arriving-from-multiple-devices";
4708 body = await lazy.accountsL10n.formatValue(bodyL10nId, {
4710 tabCount: URIs.length,
4713 const title = await lazy.accountsL10n.formatValue(titleL10nId);
4715 const clickCallback = (obsSubject, obsTopic) => {
4716 if (obsTopic == "alertclickcallback") {
4717 win.gBrowser.selectedTab = firstTab;
4721 // Specify an icon because on Windows no icon is shown at the moment
4723 if (AppConstants.platform == "win") {
4724 imageURL = "chrome://branding/content/icon64.png";
4726 this.AlertsService.showAlertNotification(
4735 console.error("Error displaying tab(s) received by Sync: ", ex);
4739 async _onVerifyLoginNotification({ body, title, url }) {
4742 if (AppConstants.platform == "win") {
4743 imageURL = "chrome://branding/content/icon64.png";
4745 let win = lazy.BrowserWindowTracker.getTopWindow({ private: false });
4747 win = await this._openURLInNewWindow(url);
4748 let tabs = win.gBrowser.tabs;
4749 tab = tabs[tabs.length - 1];
4751 tab = win.gBrowser.addWebTab(url);
4753 tab.attention = true;
4754 let clickCallback = (subject, topic) => {
4755 if (topic != "alertclickcallback") {
4758 win.gBrowser.selectedTab = tab;
4762 this.AlertsService.showAlertNotification(
4771 console.error("Error notifying of a verify login event: ", ex);
4775 _onDeviceConnected(deviceName) {
4776 const [title, body] = lazy.accountsL10n.formatValuesSync([
4777 { id: "account-connection-title" },
4779 ? { id: "account-connection-connected-with", args: { deviceName } }
4780 : { id: "account-connection-connected-with-noname" },
4783 let clickCallback = async (subject, topic) => {
4784 if (topic != "alertclickcallback") {
4787 let url = await lazy.FxAccounts.config.promiseManageDevicesURI(
4788 "device-connected-notification"
4790 let win = lazy.BrowserWindowTracker.getTopWindow({ private: false });
4792 this._openURLInNewWindow(url);
4794 win.gBrowser.addWebTab(url);
4799 this.AlertsService.showAlertNotification(
4808 console.error("Error notifying of a new Sync device: ", ex);
4812 _onDeviceDisconnected() {
4813 const [title, body] = lazy.accountsL10n.formatValuesSync([
4814 "account-connection-title",
4815 "account-connection-disconnected",
4818 let clickCallback = (subject, topic) => {
4819 if (topic != "alertclickcallback") {
4822 this._openPreferences("sync");
4824 this.AlertsService.showAlertNotification(
4834 _updateFxaBadges(win) {
4835 let fxaButton = win.document.getElementById("fxa-toolbar-menu-button");
4836 let badge = fxaButton?.querySelector(".toolbarbutton-badge");
4838 let state = lazy.UIState.get();
4840 state.status == lazy.UIState.STATUS_LOGIN_FAILED ||
4841 state.status == lazy.UIState.STATUS_NOT_VERIFIED
4843 // If the fxa toolbar button is in the toolbox, we display the notification
4844 // on the fxa button instead of the app menu.
4845 let navToolbox = win.document.getElementById("navigator-toolbox");
4846 let isFxAButtonShown = navToolbox.contains(fxaButton);
4847 if (isFxAButtonShown) {
4848 state.status == lazy.UIState.STATUS_LOGIN_FAILED
4849 ? fxaButton?.setAttribute("badge-status", state.status)
4850 : badge?.classList.add("feature-callout");
4852 lazy.AppMenuNotifications.showBadgeOnlyNotification(
4853 "fxa-needs-authentication"
4857 fxaButton?.removeAttribute("badge-status");
4858 badge?.classList.remove("feature-callout");
4859 lazy.AppMenuNotifications.removeNotification("fxa-needs-authentication");
4863 _collectTelemetryPiPEnabled() {
4864 Services.telemetry.setEventRecordingEnabled(
4865 "pictureinpicture.settings",
4868 Services.telemetry.setEventRecordingEnabled("pictureinpicture", true);
4870 const TOGGLE_ENABLED_PREF =
4871 "media.videocontrols.picture-in-picture.video-toggle.enabled";
4873 const observe = (subject, topic) => {
4874 const enabled = Services.prefs.getBoolPref(TOGGLE_ENABLED_PREF, false);
4875 Services.telemetry.scalarSet("pictureinpicture.toggle_enabled", enabled);
4877 // Record events when preferences change
4878 if (topic === "nsPref:changed") {
4880 Services.telemetry.recordEvent(
4881 "pictureinpicture.settings",
4889 Services.prefs.addObserver(TOGGLE_ENABLED_PREF, observe);
4893 QueryInterface: ChromeUtils.generateQI([
4895 "nsISupportsWeakReference",
4899 var ContentBlockingCategoriesPrefs = {
4900 PREF_CB_CATEGORY: "browser.contentblocking.category",
4901 PREF_STRICT_DEF: "browser.contentblocking.features.strict",
4902 switchingCategory: false,
4904 setPrefExpectations() {
4905 // The prefs inside CATEGORY_PREFS are initial values.
4906 // If the pref remains null, then it will expect the default value.
4907 // The "standard" category is defined as expecting all 5 default values.
4908 this.CATEGORY_PREFS = {
4910 "network.cookie.cookieBehavior": null,
4911 "network.cookie.cookieBehavior.pbmode": null,
4912 "privacy.trackingprotection.pbmode.enabled": null,
4913 "privacy.trackingprotection.enabled": null,
4914 "privacy.trackingprotection.socialtracking.enabled": null,
4915 "privacy.trackingprotection.fingerprinting.enabled": null,
4916 "privacy.trackingprotection.cryptomining.enabled": null,
4917 "privacy.trackingprotection.emailtracking.enabled": null,
4918 "privacy.trackingprotection.emailtracking.pbmode.enabled": null,
4919 "privacy.annotate_channels.strict_list.enabled": null,
4920 "network.http.referer.disallowCrossSiteRelaxingDefault": null,
4921 "network.http.referer.disallowCrossSiteRelaxingDefault.top_navigation":
4923 "privacy.partition.network_state.ocsp_cache": null,
4924 "privacy.query_stripping.enabled": null,
4925 "privacy.query_stripping.enabled.pbmode": null,
4926 "privacy.fingerprintingProtection": null,
4927 "privacy.fingerprintingProtection.pbmode": null,
4930 "network.cookie.cookieBehavior": null,
4931 "network.cookie.cookieBehavior.pbmode": null,
4932 "privacy.trackingprotection.pbmode.enabled": null,
4933 "privacy.trackingprotection.enabled": null,
4934 "privacy.trackingprotection.socialtracking.enabled": null,
4935 "privacy.trackingprotection.fingerprinting.enabled": null,
4936 "privacy.trackingprotection.cryptomining.enabled": null,
4937 "privacy.trackingprotection.emailtracking.enabled": null,
4938 "privacy.trackingprotection.emailtracking.pbmode.enabled": null,
4939 "privacy.annotate_channels.strict_list.enabled": null,
4940 "network.http.referer.disallowCrossSiteRelaxingDefault": null,
4941 "network.http.referer.disallowCrossSiteRelaxingDefault.top_navigation":
4943 "privacy.partition.network_state.ocsp_cache": null,
4944 "privacy.query_stripping.enabled": null,
4945 "privacy.query_stripping.enabled.pbmode": null,
4946 "privacy.fingerprintingProtection": null,
4947 "privacy.fingerprintingProtection.pbmode": null,
4950 let type = "strict";
4951 let rulesArray = Services.prefs
4952 .getStringPref(this.PREF_STRICT_DEF)
4954 for (let item of rulesArray) {
4957 this.CATEGORY_PREFS[type][
4958 "privacy.trackingprotection.enabled"
4962 this.CATEGORY_PREFS[type][
4963 "privacy.trackingprotection.enabled"
4967 this.CATEGORY_PREFS[type][
4968 "privacy.trackingprotection.pbmode.enabled"
4972 this.CATEGORY_PREFS[type][
4973 "privacy.trackingprotection.pbmode.enabled"
4977 this.CATEGORY_PREFS[type][
4978 "privacy.trackingprotection.fingerprinting.enabled"
4982 this.CATEGORY_PREFS[type][
4983 "privacy.trackingprotection.fingerprinting.enabled"
4987 this.CATEGORY_PREFS[type][
4988 "privacy.trackingprotection.cryptomining.enabled"
4992 this.CATEGORY_PREFS[type][
4993 "privacy.trackingprotection.cryptomining.enabled"
4997 this.CATEGORY_PREFS[type][
4998 "privacy.trackingprotection.socialtracking.enabled"
5002 this.CATEGORY_PREFS[type][
5003 "privacy.trackingprotection.socialtracking.enabled"
5007 this.CATEGORY_PREFS[type][
5008 "privacy.trackingprotection.emailtracking.enabled"
5012 this.CATEGORY_PREFS[type][
5013 "privacy.trackingprotection.emailtracking.enabled"
5016 case "emailTPPrivate":
5017 this.CATEGORY_PREFS[type][
5018 "privacy.trackingprotection.emailtracking.pbmode.enabled"
5021 case "-emailTPPrivate":
5022 this.CATEGORY_PREFS[type][
5023 "privacy.trackingprotection.emailtracking.pbmode.enabled"
5027 this.CATEGORY_PREFS[type][
5028 "privacy.annotate_channels.strict_list.enabled"
5032 this.CATEGORY_PREFS[type][
5033 "privacy.annotate_channels.strict_list.enabled"
5037 this.CATEGORY_PREFS[type][
5038 "network.http.referer.disallowCrossSiteRelaxingDefault"
5042 this.CATEGORY_PREFS[type][
5043 "network.http.referer.disallowCrossSiteRelaxingDefault"
5047 this.CATEGORY_PREFS[type][
5048 "network.http.referer.disallowCrossSiteRelaxingDefault.top_navigation"
5052 this.CATEGORY_PREFS[type][
5053 "network.http.referer.disallowCrossSiteRelaxingDefault.top_navigation"
5057 this.CATEGORY_PREFS[type][
5058 "privacy.partition.network_state.ocsp_cache"
5062 this.CATEGORY_PREFS[type][
5063 "privacy.partition.network_state.ocsp_cache"
5067 this.CATEGORY_PREFS[type]["privacy.query_stripping.enabled"] = true;
5070 this.CATEGORY_PREFS[type]["privacy.query_stripping.enabled"] = false;
5073 this.CATEGORY_PREFS[type][
5074 "privacy.query_stripping.enabled.pbmode"
5078 this.CATEGORY_PREFS[type][
5079 "privacy.query_stripping.enabled.pbmode"
5083 this.CATEGORY_PREFS[type]["privacy.fingerprintingProtection"] = true;
5086 this.CATEGORY_PREFS[type]["privacy.fingerprintingProtection"] = false;
5089 this.CATEGORY_PREFS[type][
5090 "privacy.fingerprintingProtection.pbmode"
5094 this.CATEGORY_PREFS[type][
5095 "privacy.fingerprintingProtection.pbmode"
5098 case "cookieBehavior0":
5099 this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior"] =
5100 Ci.nsICookieService.BEHAVIOR_ACCEPT;
5102 case "cookieBehavior1":
5103 this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior"] =
5104 Ci.nsICookieService.BEHAVIOR_REJECT_FOREIGN;
5106 case "cookieBehavior2":
5107 this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior"] =
5108 Ci.nsICookieService.BEHAVIOR_REJECT;
5110 case "cookieBehavior3":
5111 this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior"] =
5112 Ci.nsICookieService.BEHAVIOR_LIMIT_FOREIGN;
5114 case "cookieBehavior4":
5115 this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior"] =
5116 Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER;
5118 case "cookieBehavior5":
5119 this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior"] =
5120 Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN;
5122 case "cookieBehaviorPBM0":
5123 this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior.pbmode"] =
5124 Ci.nsICookieService.BEHAVIOR_ACCEPT;
5126 case "cookieBehaviorPBM1":
5127 this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior.pbmode"] =
5128 Ci.nsICookieService.BEHAVIOR_REJECT_FOREIGN;
5130 case "cookieBehaviorPBM2":
5131 this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior.pbmode"] =
5132 Ci.nsICookieService.BEHAVIOR_REJECT;
5134 case "cookieBehaviorPBM3":
5135 this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior.pbmode"] =
5136 Ci.nsICookieService.BEHAVIOR_LIMIT_FOREIGN;
5138 case "cookieBehaviorPBM4":
5139 this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior.pbmode"] =
5140 Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER;
5142 case "cookieBehaviorPBM5":
5143 this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior.pbmode"] =
5144 Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN;
5147 console.error(`Error: Unknown rule observed ${item}`);
5153 * Checks if CB prefs match perfectly with one of our pre-defined categories.
5155 prefsMatch(category) {
5156 // The category pref must be either unset, or match.
5158 Services.prefs.prefHasUserValue(this.PREF_CB_CATEGORY) &&
5159 Services.prefs.getStringPref(this.PREF_CB_CATEGORY) != category
5163 for (let pref in this.CATEGORY_PREFS[category]) {
5164 let value = this.CATEGORY_PREFS[category][pref];
5165 if (value == null) {
5166 if (Services.prefs.prefHasUserValue(pref)) {
5170 let prefType = Services.prefs.getPrefType(pref);
5172 (prefType == Services.prefs.PREF_BOOL &&
5173 Services.prefs.getBoolPref(pref) != value) ||
5174 (prefType == Services.prefs.PREF_INT &&
5175 Services.prefs.getIntPref(pref) != value) ||
5176 (prefType == Services.prefs.PREF_STRING &&
5177 Services.prefs.getStringPref(pref) != value)
5187 if (this.switchingCategory) {
5190 // If PREF_CB_CATEGORY is not set match users to a Content Blocking category. Check if prefs fit
5191 // perfectly into strict or standard, otherwise match with custom. If PREF_CB_CATEGORY has previously been set,
5192 // a change of one of these prefs necessarily puts us in "custom".
5193 if (this.prefsMatch("standard")) {
5194 Services.prefs.setStringPref(this.PREF_CB_CATEGORY, "standard");
5195 } else if (this.prefsMatch("strict")) {
5196 Services.prefs.setStringPref(this.PREF_CB_CATEGORY, "strict");
5198 Services.prefs.setStringPref(this.PREF_CB_CATEGORY, "custom");
5201 // If there is a custom policy which changes a related pref, then put the user in custom so
5202 // they still have access to other content blocking prefs, and to keep our default definitions
5204 let policy = Services.policies.getActivePolicies();
5205 if (policy && (policy.EnableTrackingProtection || policy.Cookies)) {
5206 Services.prefs.setStringPref(this.PREF_CB_CATEGORY, "custom");
5210 updateCBCategory() {
5212 this.switchingCategory ||
5213 !Services.prefs.prefHasUserValue(this.PREF_CB_CATEGORY)
5217 // Turn on switchingCategory flag, to ensure that when the individual prefs that change as a result
5218 // of the category change do not trigger yet another category change.
5219 this.switchingCategory = true;
5220 let value = Services.prefs.getStringPref(this.PREF_CB_CATEGORY);
5221 this.setPrefsToCategory(value);
5222 this.switchingCategory = false;
5226 * Sets all user-exposed content blocking preferences to values that match the selected category.
5228 setPrefsToCategory(category) {
5229 // Leave prefs as they were if we are switching to "custom" category.
5230 if (category == "custom") {
5234 for (let pref in this.CATEGORY_PREFS[category]) {
5235 let value = this.CATEGORY_PREFS[category][pref];
5236 if (!Services.prefs.prefIsLocked(pref)) {
5237 if (value == null) {
5238 Services.prefs.clearUserPref(pref);
5240 switch (Services.prefs.getPrefType(pref)) {
5241 case Services.prefs.PREF_BOOL:
5242 Services.prefs.setBoolPref(pref, value);
5244 case Services.prefs.PREF_INT:
5245 Services.prefs.setIntPref(pref, value);
5247 case Services.prefs.PREF_STRING:
5248 Services.prefs.setStringPref(pref, value);
5258 * ContentPermissionIntegration is responsible for showing the user
5259 * simple permission prompts when content requests additional
5262 * While there are some built-in permission prompts, createPermissionPrompt
5263 * can also be overridden by system add-ons or tests to provide new ones.
5265 * This override ability is provided by Integration.sys.mjs. See
5266 * PermissionUI.sys.mjs for an example of how to provide a new prompt
5269 const ContentPermissionIntegration = {
5271 * Creates a PermissionPrompt for a given permission type and
5272 * nsIContentPermissionRequest.
5274 * @param {string} type
5275 * The type of the permission request from content. This normally
5276 * matches the "type" field of an nsIContentPermissionType, but it
5277 * can be something else if the permission does not use the
5278 * nsIContentPermissionRequest model. Note that this type might also
5279 * be different from the permission key used in the permissions
5281 * Example: "geolocation"
5282 * @param {nsIContentPermissionRequest} request
5283 * The request for a permission from content.
5284 * @return {PermissionPrompt} (see PermissionUI.sys.mjs),
5285 * or undefined if the type cannot be handled.
5287 createPermissionPrompt(type, request) {
5289 case "geolocation": {
5290 return new lazy.PermissionUI.GeolocationPermissionPrompt(request);
5293 return new lazy.PermissionUI.XRPermissionPrompt(request);
5295 case "desktop-notification": {
5296 return new lazy.PermissionUI.DesktopNotificationPermissionPrompt(
5300 case "persistent-storage": {
5301 return new lazy.PermissionUI.PersistentStoragePermissionPrompt(request);
5304 return new lazy.PermissionUI.MIDIPermissionPrompt(request);
5306 case "storage-access": {
5307 return new lazy.PermissionUI.StorageAccessPermissionPrompt(request);
5314 export function ContentPermissionPrompt() {}
5316 ContentPermissionPrompt.prototype = {
5317 classID: Components.ID("{d8903bf6-68d5-4e97-bcd1-e4d3012f721a}"),
5319 QueryInterface: ChromeUtils.generateQI(["nsIContentPermissionPrompt"]),
5322 * This implementation of nsIContentPermissionPrompt.prompt ensures
5323 * that there's only one nsIContentPermissionType in the request,
5324 * and that it's of type nsIContentPermissionType. Failing to
5325 * satisfy either of these conditions will result in this method
5326 * throwing NS_ERRORs. If the combined ContentPermissionIntegration
5327 * cannot construct a prompt for this particular request, an
5328 * NS_ERROR_FAILURE will be thrown.
5330 * Any time an error is thrown, the nsIContentPermissionRequest is
5331 * cancelled automatically.
5333 * @param {nsIContentPermissionRequest} request
5334 * The request that we're to show a prompt for.
5337 if (request.element && request.element.fxrPermissionPrompt) {
5338 // For Firefox Reality on Desktop, switch to a different mechanism to
5339 // prompt the user since fewer permissions are available and since many
5340 // UI dependencies are not availabe.
5341 request.element.fxrPermissionPrompt(request);
5347 // Only allow exactly one permission request here.
5348 let types = request.types.QueryInterface(Ci.nsIArray);
5349 if (types.length != 1) {
5350 throw Components.Exception(
5351 "Expected an nsIContentPermissionRequest with only 1 type.",
5352 Cr.NS_ERROR_UNEXPECTED
5356 type = types.queryElementAt(0, Ci.nsIContentPermissionType).type;
5357 let combinedIntegration = lazy.Integration.contentPermission.getCombined(
5358 ContentPermissionIntegration
5361 let permissionPrompt = combinedIntegration.createPermissionPrompt(
5365 if (!permissionPrompt) {
5366 throw Components.Exception(
5367 `Failed to handle permission of type ${type}`,
5372 permissionPrompt.prompt();
5379 let schemeHistogram = Services.telemetry.getKeyedHistogramById(
5380 "PERMISSION_REQUEST_ORIGIN_SCHEME"
5384 if (request.principal.schemeIs("http")) {
5386 } else if (request.principal.schemeIs("https")) {
5390 // If the request principal is not available at this point,
5391 // the request has likely been cancelled before being shown to the
5392 // user. We shouldn't record this request.
5393 if (ex.result != Cr.NS_ERROR_FAILURE) {
5398 schemeHistogram.add(type, scheme);
5400 let userInputHistogram = Services.telemetry.getKeyedHistogramById(
5401 "PERMISSION_REQUEST_HANDLING_USER_INPUT"
5403 userInputHistogram.add(
5405 request.hasValidTransientUserGestureActivation
5410 export var DefaultBrowserCheck = {
5412 const shellService = win.getShellService();
5413 const needPin = await shellService.doesAppNeedPin();
5415 win.MozXULElement.insertFTLIfNeeded("branding/brand.ftl");
5416 win.MozXULElement.insertFTLIfNeeded(
5417 "browser/defaultBrowserNotification.ftl"
5419 // Resolve the translations for the prompt elements and return only the
5422 AppConstants.platform == "macosx"
5423 ? "default-browser-prompt-message-pin-mac"
5424 : "default-browser-prompt-message-pin";
5425 let [promptTitle, promptMessage, askLabel, yesButton, notNowButton] = (
5426 await win.document.l10n.formatMessages([
5429 ? "default-browser-prompt-title-pin"
5430 : "default-browser-prompt-title-alt",
5433 id: needPin ? pinMessage : "default-browser-prompt-message-alt",
5435 { id: "default-browser-prompt-checkbox-not-again-label" },
5438 ? "default-browser-prompt-button-primary-pin"
5439 : "default-browser-prompt-button-primary-alt",
5441 { id: "default-browser-prompt-button-secondary" },
5443 ).map(({ value }) => value);
5445 let ps = Services.prompt;
5447 ps.BUTTON_TITLE_IS_STRING * ps.BUTTON_POS_0 +
5448 ps.BUTTON_TITLE_IS_STRING * ps.BUTTON_POS_1 +
5449 ps.BUTTON_POS_0_DEFAULT;
5450 let rv = await ps.asyncConfirmEx(
5451 win.browsingContext,
5452 ps.MODAL_TYPE_INTERNAL_WINDOW,
5460 false, // checkbox state
5461 { headerIconURL: "chrome://branding/content/icon32.png" }
5463 let buttonNumClicked = rv.get("buttonNumClicked");
5464 let checkboxState = rv.get("checked");
5465 if (buttonNumClicked == 0) {
5467 await shellService.setAsDefault();
5469 this.log.error("Failed to set the default browser", e);
5472 shellService.pinToTaskbar();
5474 if (checkboxState) {
5475 shellService.shouldCheckDefaultBrowser = false;
5479 let resultEnum = buttonNumClicked * 2 + !checkboxState;
5481 .getHistogramById("BROWSER_SET_DEFAULT_RESULT")
5484 /* Don't break if Telemetry is acting up. */
5489 * Checks if the default browser check prompt will be shown.
5490 * @param {boolean} isStartupCheck
5491 * If true, prefs will be set and telemetry will be recorded.
5492 * @returns {boolean} True if the default browser check prompt will be shown.
5494 async willCheckDefaultBrowser(isStartupCheck) {
5495 let win = lazy.BrowserWindowTracker.getTopWindow();
5496 let shellService = win.getShellService();
5498 // Perform default browser checking.
5499 if (!shellService) {
5504 !AppConstants.DEBUG && shellService.shouldCheckDefaultBrowser;
5506 // Even if we shouldn't check the default browser, we still continue when
5507 // isStartupCheck = true to set prefs and telemetry.
5508 if (!shouldCheck && !isStartupCheck) {
5512 // Skip the "Set Default Browser" check during first-run or after the
5513 // browser has been run a few times.
5514 const skipDefaultBrowserCheck =
5515 Services.prefs.getBoolPref(
5516 "browser.shell.skipDefaultBrowserCheckOnFirstRun"
5518 !Services.prefs.getBoolPref(
5519 "browser.shell.didSkipDefaultBrowserCheckOnFirstRun"
5522 let promptCount = Services.prefs.getIntPref(
5523 "browser.shell.defaultBrowserCheckCount",
5527 // If SessionStartup's state is not initialized, checking sessionType will set
5528 // its internal state to "do not restore".
5529 await lazy.SessionStartup.onceInitialized;
5530 let willRecoverSession =
5531 lazy.SessionStartup.sessionType == lazy.SessionStartup.RECOVER_SESSION;
5533 // Don't show the prompt if we're already the default browser.
5534 let isDefault = false;
5535 let isDefaultError = false;
5537 isDefault = shellService.isDefaultBrowser(isStartupCheck, false);
5539 isDefaultError = true;
5542 if (isDefault && isStartupCheck) {
5543 let now = Math.floor(Date.now() / 1000).toString();
5544 Services.prefs.setCharPref(
5545 "browser.shell.mostRecentDateSetAsDefault",
5550 let willPrompt = shouldCheck && !isDefault && !willRecoverSession;
5553 if (skipDefaultBrowserCheck) {
5554 if (isStartupCheck) {
5555 Services.prefs.setBoolPref(
5556 "browser.shell.didSkipDefaultBrowserCheckOnFirstRun",
5563 if (isStartupCheck) {
5564 Services.prefs.setIntPref(
5565 "browser.shell.defaultBrowserCheckCount",
5569 if (!AppConstants.RELEASE_OR_BETA && promptCount > 3) {
5575 if (isStartupCheck) {
5577 // Report default browser status on startup to telemetry
5578 // so we can track whether we are the default.
5580 .getHistogramById("BROWSER_IS_USER_DEFAULT")
5583 .getHistogramById("BROWSER_IS_USER_DEFAULT_ERROR")
5584 .add(isDefaultError);
5586 .getHistogramById("BROWSER_SET_DEFAULT_ALWAYS_CHECK")
5589 .getHistogramById("BROWSER_SET_DEFAULT_DIALOG_PROMPT_RAWCOUNT")
5592 /* Don't break the default prompt if telemetry is broken. */
5601 * AboutHomeStartupCache is responsible for reading and writing the
5602 * initial about:home document from the HTTP cache as a startup
5603 * performance optimization. It only works when the "privileged about
5604 * content process" is enabled and when ENABLED_PREF is set to true.
5606 * See https://firefox-source-docs.mozilla.org/browser/components/newtab/docs/v2-system-addon/about_home_startup_cache.html
5607 * for further details.
5609 export var AboutHomeStartupCache = {
5610 ABOUT_HOME_URI_STRING: "about:home",
5611 SCRIPT_EXTENSION: "script",
5612 ENABLED_PREF: "browser.startup.homepage.abouthome_cache.enabled",
5613 PRELOADED_NEWTAB_PREF: "browser.newtab.preload",
5614 LOG_LEVEL_PREF: "browser.startup.homepage.abouthome_cache.loglevel",
5616 // It's possible that the layout of about:home will change such that
5617 // we want to invalidate any pre-existing caches. We do this by setting
5618 // this meta key in the nsICacheEntry for the page.
5620 // The version is currently set to the build ID, meaning that the cache
5621 // is invalidated after every upgrade (like the main startup cache).
5622 CACHE_VERSION_META_KEY: "version",
5624 LOG_NAME: "AboutHomeStartupCache",
5626 // These messages are used to request the "privileged about content process"
5627 // to create the cached document, and then to receive that document.
5628 CACHE_REQUEST_MESSAGE: "AboutHomeStartupCache:CacheRequest",
5629 CACHE_RESPONSE_MESSAGE: "AboutHomeStartupCache:CacheResponse",
5630 CACHE_USAGE_RESULT_MESSAGE: "AboutHomeStartupCache:UsageResult",
5632 // When a "privileged about content process" is launched, this message is
5633 // sent to give it some nsIInputStream's for the about:home document they
5635 SEND_STREAMS_MESSAGE: "AboutHomeStartupCache:InputStreams",
5637 // This time in ms is used to debounce messages that are broadcast to
5638 // all about:newtab's, or the preloaded about:newtab. We use those
5639 // messages as a signal that it's likely time to refresh the cache.
5640 CACHE_DEBOUNCE_RATE_MS: 5000,
5642 // This is how long we'll block the AsyncShutdown while waiting for
5643 // the cache to write. If we fail to write within that time, we will
5644 // allow the shutdown to proceed.
5645 SHUTDOWN_CACHE_WRITE_TIMEOUT_MS: 1000,
5647 // The following values are as possible values for the
5648 // browser.startup.abouthome_cache_result scalar. Keep these in sync with the
5649 // scalar definition in Scalars.yaml. See setDeferredResult for more
5651 CACHE_RESULT_SCALARS: {
5660 NOT_LOADING_ABOUTHOME: 8,
5661 PRELOADING_DISABLED: 9,
5664 // This will be set to one of the values of CACHE_RESULT_SCALARS
5665 // once it is determined which result best suits what occurred.
5666 _cacheDeferredResultScalar: -1,
5668 // A reference to the nsICacheEntry to read from and write to.
5671 // These nsIPipe's are sent down to the "privileged about content process"
5672 // immediately after the process launches. This allows us to race the loading
5673 // of the cache entry in the parent process with the load of the about:home
5674 // page in the content process, since we'll connect the InputStream's to
5675 // the pipes as soon as the nsICacheEntry is available.
5677 // The page pipe is for the HTML markup for the page.
5679 // The script pipe is for the JavaScript that the HTML markup loads
5680 // to set its internal state.
5682 _cacheDeferred: null,
5686 _hasWrittenThisSession: false,
5688 _firstPrivilegedProcessCreated: false,
5691 if (this._initted) {
5692 throw new Error("AboutHomeStartupCache already initted.");
5695 this.setDeferredResult(this.CACHE_RESULT_SCALARS.UNSET);
5697 this._enabled = !!lazy.NimbusFeatures.abouthomecache.getVariable("enabled");
5699 if (!this._enabled) {
5700 this.recordResult(this.CACHE_RESULT_SCALARS.DISABLED);
5704 this.log = console.createInstance({
5705 prefix: this.LOG_NAME,
5706 maxLogLevelPref: this.LOG_LEVEL_PREF,
5709 this.log.trace("Initting.");
5711 // If the user is not configured to load about:home at startup, then
5712 // let's not bother with the cache - loading it needlessly is more likely
5713 // to hinder what we're actually trying to load.
5714 let willLoadAboutHome =
5715 !lazy.HomePage.overridden &&
5716 Services.prefs.getIntPref("browser.startup.page") === 1;
5718 if (!willLoadAboutHome) {
5719 this.log.trace("Not configured to load about:home by default.");
5720 this.recordResult(this.CACHE_RESULT_SCALARS.NOT_LOADING_ABOUTHOME);
5724 if (!Services.prefs.getBoolPref(this.PRELOADED_NEWTAB_PREF, false)) {
5725 this.log.trace("Preloaded about:newtab disabled.");
5726 this.recordResult(this.CACHE_RESULT_SCALARS.PRELOADING_DISABLED);
5730 Services.obs.addObserver(this, "ipc:content-created");
5731 Services.obs.addObserver(this, "process-type-set");
5732 Services.obs.addObserver(this, "ipc:content-shutdown");
5733 Services.obs.addObserver(this, "intl:app-locales-changed");
5735 this.log.trace("Constructing pipes.");
5736 this._pagePipe = this.makePipe();
5737 this._scriptPipe = this.makePipe();
5739 this._cacheEntryPromise = new Promise(resolve => {
5740 this._cacheEntryResolver = resolve;
5743 let lci = Services.loadContextInfo.default;
5744 let storage = Services.cache2.diskCacheStorage(lci);
5746 storage.asyncOpenURI(
5749 Ci.nsICacheStorage.OPEN_PRIORITY,
5753 this.log.error("Failed to open about:home cache entry", e);
5756 this._cacheTask = new lazy.DeferredTask(async () => {
5757 await this.cacheNow();
5758 }, this.CACHE_DEBOUNCE_RATE_MS);
5760 lazy.AsyncShutdown.quitApplicationGranted.addBlocker(
5761 "AboutHomeStartupCache: Writing cache",
5763 await this.onShutdown();
5765 () => this._cacheProgress
5768 this._cacheDeferred = null;
5769 this._initted = true;
5770 this.log.trace("Initialized.");
5774 return this._initted;
5778 if (!this._enabled) {
5783 Services.obs.removeObserver(this, "ipc:content-created");
5784 Services.obs.removeObserver(this, "process-type-set");
5785 Services.obs.removeObserver(this, "ipc:content-shutdown");
5786 Services.obs.removeObserver(this, "intl:app-locales-changed");
5788 // If we failed to initialize and register for these observer
5789 // notifications, then attempting to remove them will throw.
5790 // It's fine to ignore that case on shutdown.
5793 if (this._cacheTask) {
5794 this._cacheTask.disarm();
5795 this._cacheTask = null;
5798 this._pagePipe = null;
5799 this._scriptPipe = null;
5800 this._initted = false;
5801 this._cacheEntry = null;
5802 this._hasWrittenThisSession = false;
5803 this._cacheEntryPromise = null;
5804 this._cacheEntryResolver = null;
5805 this._cacheDeferredResultScalar = -1;
5808 this.log.trace("Uninitialized.");
5812 this._procManager = null;
5813 this._procManagerID = null;
5814 this._appender = null;
5815 this._cacheDeferred = null;
5816 this._finalized = false;
5817 this._firstPrivilegedProcessCreated = false;
5820 _aboutHomeURI: null,
5822 get aboutHomeURI() {
5823 if (this._aboutHomeURI) {
5824 return this._aboutHomeURI;
5827 this._aboutHomeURI = Services.io.newURI(this.ABOUT_HOME_URI_STRING);
5828 return this._aboutHomeURI;
5831 // For the AsyncShutdown blocker, this is used to populate the progress
5833 _cacheProgress: "Not yet begun",
5836 * Called by the AsyncShutdown blocker on quit-application-granted
5837 * to potentially flush the most recent cache to disk. If one was
5838 * never written during the session, one is generated and written
5839 * before the async function resolves.
5841 * @param withTimeout (boolean)
5842 * Whether or not the timeout mechanism should be used. Defaults
5846 * If a cache has never been written, or a cache write is in
5847 * progress, resolves true when the cache has been written. Also
5848 * resolves to true if a cache didn't need to be written.
5850 * Resolves to false if a cache write unexpectedly timed out.
5852 async onShutdown(withTimeout = true) {
5853 // If we never wrote this session, arm the task so that the next
5854 // step can finalize.
5855 if (!this._hasWrittenThisSession) {
5856 this.log.trace("Never wrote a cache this session. Arming cache task.");
5857 this._cacheTask.arm();
5860 Services.telemetry.scalarSet(
5861 "browser.startup.abouthome_cache_shutdownwrite",
5862 this._cacheTask.isArmed
5865 if (this._cacheTask.isArmed) {
5866 this.log.trace("Finalizing cache task on shutdown");
5867 this._finalized = true;
5869 // To avoid hanging shutdowns, we'll ensure that we wait a maximum of
5870 // SHUTDOWN_CACHE_WRITE_TIMEOUT_MS millseconds before giving up.
5871 const TIMED_OUT = Symbol();
5874 let timeoutPromise = new Promise(resolve => {
5875 timeoutID = lazy.setTimeout(
5876 () => resolve(TIMED_OUT),
5877 this.SHUTDOWN_CACHE_WRITE_TIMEOUT_MS
5881 let promises = [this._cacheTask.finalize()];
5883 this.log.trace("Using timeout mechanism.");
5884 promises.push(timeoutPromise);
5886 this.log.trace("Skipping timeout mechanism.");
5889 let result = await Promise.race(promises);
5890 this.log.trace("Done blocking shutdown.");
5891 lazy.clearTimeout(timeoutID);
5892 if (result === TIMED_OUT) {
5893 this.log.error("Timed out getting cache streams. Skipping cache task.");
5897 this.log.trace("onShutdown is exiting");
5902 * Called by the _cacheTask DeferredTask to actually do the work of
5903 * caching the about:home document.
5906 * @resolves undefined
5907 * Resolves when a fresh version of the cache has been written.
5910 this.log.trace("Caching now.");
5911 this._cacheProgress = "Getting cache streams";
5913 let { pageInputStream, scriptInputStream } = await this.requestCache();
5915 if (!pageInputStream || !scriptInputStream) {
5916 this.log.trace("Failed to get cache streams.");
5917 this._cacheProgress = "Failed to get streams";
5921 this.log.trace("Got cache streams.");
5923 this._cacheProgress = "Writing to cache";
5926 this.log.trace("Populating cache.");
5927 await this.populateCache(pageInputStream, scriptInputStream);
5929 this._cacheProgress = "Failed to populate cache";
5930 this.log.error("Populating the cache failed: ", e);
5934 this._cacheProgress = "Done";
5935 this.log.trace("Done writing to cache.");
5936 this._hasWrittenThisSession = true;
5940 * Requests the cached document streams from the "privileged about content
5945 * Resolves with an Object with the following properties:
5947 * pageInputStream (nsIInputStream)
5948 * The page content to write to the cache, or null if request the streams
5951 * scriptInputStream (nsIInputStream)
5952 * The script content to write to the cache, or null if request the streams
5956 this.log.trace("Parent is requesting Activity Stream state object.");
5957 if (!this._procManager) {
5958 this.log.error("requestCache called with no _procManager!");
5959 return { pageInputStream: null, scriptInputStream: null };
5963 this._procManager.remoteType != lazy.E10SUtils.PRIVILEGEDABOUT_REMOTE_TYPE
5965 this.log.error("Somehow got the wrong process type.");
5966 return { pageInputStream: null, scriptInputStream: null };
5969 let state = lazy.AboutNewTab.activityStream.store.getState();
5970 return new Promise(resolve => {
5971 this._cacheDeferred = resolve;
5972 this.log.trace("Parent is requesting cache streams.");
5973 this._procManager.sendAsyncMessage(this.CACHE_REQUEST_MESSAGE, { state });
5978 * Helper function that returns a newly constructed nsIPipe instance.
5983 let pipe = Cc["@mozilla.org/pipe;1"].createInstance(Ci.nsIPipe);
5985 true /* non-blocking input */,
5986 true /* non-blocking output */,
5987 0 /* segment size */,
5988 0 /* max segments */
5994 return this._pagePipe;
5998 return this._scriptPipe;
6002 * Called when the nsICacheEntry has been accessed. If the nsICacheEntry
6003 * has content that we want to send down to the "privileged about content
6004 * process", then we connect that content to the nsIPipe's that may or
6005 * may not have already been sent down to the process.
6007 * In the event that the nsICacheEntry doesn't contain anything usable,
6008 * the nsInputStreams on the nsIPipe's are closed.
6011 this.log.trace(`Connecting nsICacheEntry to pipes.`);
6013 // If the cache doesn't yet exist, we'll know because the version metadata
6018 version = this._cacheEntry.getMetaDataElement(
6019 this.CACHE_VERSION_META_KEY
6022 if (e.result == Cr.NS_ERROR_NOT_AVAILABLE) {
6023 this.log.debug("Cache meta data does not exist. Closing streams.");
6024 this.pagePipe.outputStream.close();
6025 this.scriptPipe.outputStream.close();
6026 this.setDeferredResult(this.CACHE_RESULT_SCALARS.DOES_NOT_EXIST);
6033 this.log.info("Version retrieved is", version);
6035 if (version != Services.appinfo.appBuildID) {
6036 this.log.info("Version does not match! Dooming and closing streams.\n");
6037 // This cache is no good - doom it, and prepare for a new one.
6039 this.pagePipe.outputStream.close();
6040 this.scriptPipe.outputStream.close();
6041 this.setDeferredResult(this.CACHE_RESULT_SCALARS.INVALIDATED);
6045 let cachePageInputStream;
6048 cachePageInputStream = this._cacheEntry.openInputStream(0);
6050 this.log.error("Failed to open main input stream for cache entry", e);
6051 this.pagePipe.outputStream.close();
6052 this.scriptPipe.outputStream.close();
6053 this.setDeferredResult(this.CACHE_RESULT_SCALARS.CORRUPT_PAGE);
6057 this.log.trace("Connecting page stream to pipe.");
6058 lazy.NetUtil.asyncCopy(
6059 cachePageInputStream,
6060 this.pagePipe.outputStream,
6062 this.log.info("Page stream connected to pipe.");
6066 let cacheScriptInputStream;
6068 this.log.trace("Connecting script stream to pipe.");
6069 cacheScriptInputStream =
6070 this._cacheEntry.openAlternativeInputStream("script");
6071 lazy.NetUtil.asyncCopy(
6072 cacheScriptInputStream,
6073 this.scriptPipe.outputStream,
6075 this.log.info("Script stream connected to pipe.");
6079 if (e.result == Cr.NS_ERROR_NOT_AVAILABLE) {
6080 // For some reason, the script was not available. We'll close the pipe
6081 // without sending anything into it. The privileged about content process
6082 // will notice that there's nothing available in the pipe, and fall back
6083 // to dynamically generating the page.
6084 this.log.error("Script stream not available! Closing pipe.");
6085 this.scriptPipe.outputStream.close();
6086 this.setDeferredResult(this.CACHE_RESULT_SCALARS.CORRUPT_SCRIPT);
6092 this.setDeferredResult(this.CACHE_RESULT_SCALARS.VALID_AND_USED);
6093 this.log.trace("Streams connected to pipes.");
6097 * Called when we have received a the cache values from the "privileged
6098 * about content process". The page and script streams are written to
6099 * the nsICacheEntry.
6101 * This writing is asynchronous, and if a write happens to already be
6102 * underway when this function is called, that latter call will be
6105 * @param pageInputStream (nsIInputStream)
6106 * A stream containing the HTML markup to be saved to the cache.
6107 * @param scriptInputStream (nsIInputStream)
6108 * A stream containing the JS hydration script to be saved to the cache.
6110 * @resolves undefined
6111 * When the cache has been successfully written to.
6113 * Rejects with a JS Error if writing any part of the cache happens to
6116 async populateCache(pageInputStream, scriptInputStream) {
6117 await this.ensureCacheEntry();
6119 await new Promise((resolve, reject) => {
6120 // Doom the old cache entry, so we can start writing to a new one.
6121 this.log.trace("Populating the cache. Dooming old entry.");
6124 this.log.trace("Opening the page output stream.");
6125 let pageOutputStream;
6127 pageOutputStream = this._cacheEntry.openOutputStream(0, -1);
6133 this.log.info("Writing the page cache.");
6134 lazy.NetUtil.asyncCopy(pageInputStream, pageOutputStream, pageResult => {
6135 if (!Components.isSuccessCode(pageResult)) {
6136 this.log.error("Failed to write page. Result: " + pageResult);
6137 reject(new Error(pageResult));
6142 "Writing the page data is complete. Now opening the " +
6143 "script output stream."
6146 let scriptOutputStream;
6148 scriptOutputStream = this._cacheEntry.openAlternativeOutputStream(
6157 this.log.info("Writing the script cache.");
6158 lazy.NetUtil.asyncCopy(
6162 if (!Components.isSuccessCode(scriptResult)) {
6163 this.log.error("Failed to write script. Result: " + scriptResult);
6164 reject(new Error(scriptResult));
6169 "Writing the script cache is done. Setting version."
6172 this._cacheEntry.setMetaDataElement(
6174 Services.appinfo.appBuildID
6177 this.log.error("Failed to write version.");
6181 this.log.trace(`Version is set to ${Services.appinfo.appBuildID}.`);
6182 this.log.info("Caching of page and script is done.");
6189 this.log.trace("populateCache has finished.");
6193 * Returns a Promise that resolves once the nsICacheEntry for the cache
6194 * is available to write to and read from.
6197 * @resolves nsICacheEntry
6198 * Once the cache entry has become available.
6200 * Rejects with an error message if getting the cache entry is attempted
6201 * before the AboutHomeStartupCache component has been initialized.
6203 ensureCacheEntry() {
6204 if (!this._initted) {
6205 return Promise.reject(
6206 "Cannot ensureCacheEntry - AboutHomeStartupCache is not initted"
6210 return this._cacheEntryPromise;
6214 * Clears the contents of the cache.
6217 this.log.trace("Clearing the cache.");
6218 this._cacheEntry = this._cacheEntry.recreate();
6219 this._cacheEntryPromise = new Promise(resolve => {
6220 resolve(this._cacheEntry);
6222 this._hasWrittenThisSession = false;
6226 * Called when a content process is created. If this is the "privileged
6227 * about content process", then the cache streams will be sent to it.
6229 * @param childID (Number)
6230 * The unique ID for the content process that was created, as passed by
6231 * ipc:content-created.
6232 * @param procManager (ProcessMessageManager)
6233 * The ProcessMessageManager for the created content process.
6234 * @param processParent
6235 * The nsIDOMProcessParent for the tab.
6237 onContentProcessCreated(childID, procManager, processParent) {
6238 if (procManager.remoteType == lazy.E10SUtils.PRIVILEGEDABOUT_REMOTE_TYPE) {
6239 if (this._finalized) {
6241 "Ignoring privileged about content process launch after finalization."
6246 if (this._firstPrivilegedProcessCreated) {
6248 "Ignoring non-first privileged about content processes."
6254 `A privileged about content process is launching with ID ${childID}.`
6257 this.log.info("Sending input streams down to content process.");
6258 let actor = processParent.getActor("BrowserProcess");
6259 actor.sendAsyncMessage(this.SEND_STREAMS_MESSAGE, {
6260 pageInputStream: this.pagePipe.inputStream,
6261 scriptInputStream: this.scriptPipe.inputStream,
6264 procManager.addMessageListener(this.CACHE_RESPONSE_MESSAGE, this);
6265 procManager.addMessageListener(this.CACHE_USAGE_RESULT_MESSAGE, this);
6266 this._procManager = procManager;
6267 this._procManagerID = childID;
6268 this._firstPrivilegedProcessCreated = true;
6273 * Called when a content process is destroyed. Either it shut down normally,
6274 * or it crashed. If this is the "privileged about content process", then some
6275 * internal state is cleared.
6277 * @param childID (Number)
6278 * The unique ID for the content process that was created, as passed by
6279 * ipc:content-shutdown.
6281 onContentProcessShutdown(childID) {
6282 this.log.info(`Content process shutdown: ${childID}`);
6283 if (this._procManagerID == childID) {
6284 this.log.info("It was the current privileged about process.");
6285 if (this._cacheDeferred) {
6287 "A privileged about content process shut down while cache streams " +
6288 "were still en route."
6290 // The crash occurred while we were waiting on cache input streams to
6291 // be returned to us. Resolve with null streams instead.
6292 this._cacheDeferred({ pageInputStream: null, scriptInputStream: null });
6293 this._cacheDeferred = null;
6296 this._procManager.removeMessageListener(
6297 this.CACHE_RESPONSE_MESSAGE,
6300 this._procManager.removeMessageListener(
6301 this.CACHE_USAGE_RESULT_MESSAGE,
6304 this._procManager = null;
6305 this._procManagerID = null;
6310 * Called externally by ActivityStreamMessageChannel anytime
6311 * a message is broadcast to all about:newtabs, or sent to the
6312 * preloaded about:newtab. This is used to determine if we need
6313 * to refresh the cache.
6315 onPreloadedNewTabMessage() {
6316 if (!this._initted || !this._enabled) {
6320 if (this._finalized) {
6321 this.log.trace("Ignoring preloaded newtab update after finalization.");
6325 this.log.trace("Preloaded about:newtab was updated.");
6327 this._cacheTask.disarm();
6328 this._cacheTask.arm();
6332 * Stores the CACHE_RESULT_SCALARS value that most accurately represents
6333 * the current notion of how the cache has operated so far. It is stored
6334 * temporarily like this because we need to hear from the privileged
6335 * about content process to hear whether or not retrieving the cache
6336 * actually worked on that end. The success state reported back from
6337 * the privileged about content process will be compared against the
6338 * deferred result scalar to compute what will be recorded to
6341 * Note that this value will only be recorded if its value is GREATER
6342 * than the currently recorded value. This is because it's possible for
6343 * certain functions that record results to re-enter - but we want to record
6344 * the _first_ condition that caused the cache to not be read from.
6346 * @param result (Number)
6347 * One of the CACHE_RESULT_SCALARS values. If this value is less than
6348 * the currently recorded value, it is ignored.
6350 setDeferredResult(result) {
6351 if (this._cacheDeferredResultScalar < result) {
6352 this._cacheDeferredResultScalar = result;
6357 * Records the final result of how the cache operated for the user
6358 * during this session to Telemetry.
6360 recordResult(result) {
6361 // Note: this can be called very early on in the lifetime of
6362 // AboutHomeStartupCache, so things like this.log might not exist yet.
6363 Services.telemetry.scalarSet(
6364 "browser.startup.abouthome_cache_result",
6370 * Called when the parent process receives a message from the privileged
6371 * about content process saying whether or not reading from the cache
6374 * @param success (boolean)
6375 * True if reading from the cache succeeded.
6377 onUsageResult(success) {
6378 this.log.trace(`Received usage result. Success = ${success}`);
6381 this._cacheDeferredResultScalar !=
6382 this.CACHE_RESULT_SCALARS.VALID_AND_USED
6385 "Somehow got a success result despite having never " +
6386 "successfully sent down the cache streams"
6388 this.recordResult(this._cacheDeferredResultScalar);
6390 this.recordResult(this.CACHE_RESULT_SCALARS.VALID_AND_USED);
6397 this._cacheDeferredResultScalar ==
6398 this.CACHE_RESULT_SCALARS.VALID_AND_USED
6400 // We failed to read from the cache despite having successfully
6401 // sent it down to the content process. We presume then that the
6402 // streams just didn't provide any bytes in time.
6403 this.recordResult(this.CACHE_RESULT_SCALARS.LATE);
6405 // We failed to read the cache, but already knew why. We can
6406 // now record that value.
6407 this.recordResult(this._cacheDeferredResultScalar);
6411 QueryInterface: ChromeUtils.generateQI([
6412 "nsICacheEntryOpenallback",
6416 /** MessageListener **/
6418 receiveMessage(message) {
6419 // Only the privileged about content process can write to the cache.
6421 message.target.remoteType != lazy.E10SUtils.PRIVILEGEDABOUT_REMOTE_TYPE
6424 "Received a message from a non-privileged content process!"
6429 switch (message.name) {
6430 case this.CACHE_RESPONSE_MESSAGE: {
6431 this.log.trace("Parent received cache streams.");
6432 if (!this._cacheDeferred) {
6433 this.log.error("Parent doesn't have _cacheDeferred set up!");
6437 this._cacheDeferred(message.data);
6438 this._cacheDeferred = null;
6441 case this.CACHE_USAGE_RESULT_MESSAGE: {
6442 this.onUsageResult(message.data.success);
6450 observe(aSubject, aTopic, aData) {
6452 case "intl:app-locales-changed": {
6456 case "process-type-set":
6457 // Intentional fall-through
6458 case "ipc:content-created": {
6459 let childID = aData;
6460 let procManager = aSubject
6461 .QueryInterface(Ci.nsIInterfaceRequestor)
6462 .getInterface(Ci.nsIMessageSender);
6463 let pp = aSubject.QueryInterface(Ci.nsIDOMProcessParent);
6464 this.onContentProcessCreated(childID, procManager, pp);
6468 case "ipc:content-shutdown": {
6469 let childID = aData;
6470 this.onContentProcessShutdown(childID);
6476 /** nsICacheEntryOpenCallback **/
6478 onCacheEntryCheck() {
6479 return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED;
6482 onCacheEntryAvailable(aEntry) {
6483 this.log.trace("Cache entry is available.");
6485 this._cacheEntry = aEntry;
6486 this.connectToPipes();
6487 this._cacheEntryResolver(this._cacheEntry);