1 /* -*- mode: js; indent-tabs-mode: nil; js-indent-level: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";
8 import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
11 ChromeUtils.defineESModuleGetters(lazy, {
12 ReaderMode: "resource://gre/modules/ReaderMode.sys.mjs",
13 Region: "resource://gre/modules/Region.sys.mjs",
16 XPCOMUtils.defineLazyPreferenceGetter(
18 "INVALID_SHAREABLE_SCHEMES",
19 "services.sync.engine.tabs.filteredSchemes",
23 return new Set(val.split("|"));
27 ChromeUtils.defineLazyGetter(lazy, "gLocalization", () => {
28 return new Localization(["toolkit/global/browser-utils.ftl"], true);
31 function stringPrefToSet(prefVal) {
35 .split(/\s*,\s*/g) // split on commas, ignoring whitespace
36 .filter(v => !!v) // discard any falsey values
40 export var BrowserUtils = {
42 * Return or create a principal with the content of one, and the originAttributes
43 * of an existing principal (e.g. on a docshell, where the originAttributes ought
44 * not to change, that is, we should keep the userContextId, privateBrowsingId,
45 * etc. the same when changing the principal).
48 * The principal whose content/null/system-ness we want.
49 * @param existingPrincipal
50 * The principal whose originAttributes we want, usually the current
51 * principal of a docshell.
52 * @return an nsIPrincipal that matches the content/null/system-ness of the first
53 * param, and the originAttributes of the second.
55 principalWithMatchingOA(principal, existingPrincipal) {
56 // Don't care about system principals:
57 if (principal.isSystemPrincipal) {
61 // If the originAttributes already match, just return the principal as-is.
62 if (existingPrincipal.originSuffix == principal.originSuffix) {
66 let secMan = Services.scriptSecurityManager;
67 if (principal.isContentPrincipal) {
68 return secMan.principalWithOA(
70 existingPrincipal.originAttributes
74 if (principal.isNullPrincipal) {
75 return secMan.createNullPrincipal(existingPrincipal.originAttributes);
78 "Can't change the originAttributes of an expanded principal!"
83 * Returns true if |mimeType| is text-based, or false otherwise.
86 * The MIME type to check.
88 mimeTypeIsTextBased(mimeType) {
90 mimeType.startsWith("text/") ||
91 mimeType.endsWith("+xml") ||
92 mimeType.endsWith("+json") ||
93 mimeType == "application/x-javascript" ||
94 mimeType == "application/javascript" ||
95 mimeType == "application/json" ||
96 mimeType == "application/xml"
101 * Returns true if we can show a find bar, including FAYT, for the specified
102 * document location. The location must not be in a blocklist of specific
103 * "about:" pages for which find is disabled.
105 * This can be called from the parent process or from content processes.
107 canFindInPage(location) {
109 !location.startsWith("about:preferences") &&
110 !location.startsWith("about:settings") &&
111 !location.startsWith("about:logins") &&
112 !location.startsWith("about:firefoxview")
116 isFindbarVisible(docShell) {
117 const FINDER_SYS_MJS = "resource://gre/modules/Finder.sys.mjs";
119 Cu.isESModuleLoaded(FINDER_SYS_MJS) &&
120 ChromeUtils.importESModule(FINDER_SYS_MJS).Finder.isFindbarVisible(
127 * Returns a Promise which resolves when the given observer topic has been
130 * @param {string} topic
131 * The topic to observe.
132 * @param {function(nsISupports, string)} [test]
133 * An optional test function which, when called with the
134 * observer's subject and data, should return true if this is the
135 * expected notification, false otherwise.
136 * @returns {Promise<object>}
138 promiseObserved(topic, test = () => true) {
139 return new Promise(resolve => {
140 let observer = (subject, topic, data) => {
141 if (test(subject, data)) {
142 Services.obs.removeObserver(observer, topic);
143 resolve({ subject, data });
146 Services.obs.addObserver(observer, topic);
150 formatURIStringForDisplay(uriString, options = {}) {
152 return this.formatURIForDisplay(Services.io.newURI(uriString), options);
158 formatURIForDisplay(uri, options = {}) {
159 let { showInsecureHTTP = false } = options;
160 switch (uri.scheme) {
162 let innerURI = uri.spec.substring("view-source:".length);
163 return this.formatURIStringForDisplay(innerURI, options);
167 let host = uri.displayHostPort;
168 if (!showInsecureHTTP && host.startsWith("www.")) {
169 host = Services.eTLD.getSchemelessSite(uri);
171 if (showInsecureHTTP && uri.scheme == "http") {
172 return "http://" + host;
176 return "about:" + uri.filePath;
179 let url = new URL(uri.specIgnoringRef);
180 // _If_ we find a non-null origin, report that.
181 if (url.origin && url.origin != "null") {
182 return this.formatURIStringForDisplay(url.origin, options);
184 // otherwise, fall through...
186 console.error("Invalid blob URI passed to formatURIForDisplay: ", ex);
188 /* For blob URIs without an origin, fall through and use the data URI
189 * logic (shows just "(data)", localized). */
191 return lazy.gLocalization.formatValueSync("browser-utils-url-data");
192 case "moz-extension":
193 let policy = WebExtensionPolicy.getByURI(uri);
194 return lazy.gLocalization.formatValueSync(
195 "browser-utils-url-extension",
196 { extension: policy?.name.trim() || uri.spec }
204 let url = uri.QueryInterface(Ci.nsIURL);
205 // Just the filename if we have one:
209 // We won't get a filename for a path that looks like:
211 // So try the directory name:
213 let parts = url.directory.split("/");
214 // Pop off any empty bits at the end:
216 while (!last && parts.length) {
227 return uri.asciiHost || uri.spec;
230 // Given a URL returns a (possibly transformed) URL suitable for sharing, or null if
231 // no such URL can be obtained.
232 getShareableURL(url) {
237 // Carve out an exception for about:reader.
238 if (url.spec.startsWith("about:reader?")) {
239 url = Services.io.newURI(lazy.ReaderMode.getOriginalUrl(url.spec));
241 // Disallow sharing URLs with more than 65535 characters.
242 if (url.spec.length > 65535) {
245 // Use the same preference as synced tabs to disable what kind
246 // of tabs we can send to another device
247 return lazy.INVALID_SHAREABLE_SCHEMES.has(url.scheme) ? null : url;
251 * Extracts linkNode and href for a click event.
255 * @return [href, linkNode, linkPrincipal].
257 * @note linkNode will be null if the click wasn't on an anchor
258 * element. This includes SVG links, because callers expect |node|
259 * to behave like an <a> element, which SVG links (XLink) don't.
261 hrefAndLinkNodeForClickEvent(event) {
262 // We should get a window off the event, and bail if not:
263 let content = event.view || event.composedTarget?.ownerGlobal;
264 if (!content?.HTMLAnchorElement) {
267 function isHTMLLink(aNode) {
268 // Be consistent with what nsContextMenu.js does.
270 (content.HTMLAnchorElement.isInstance(aNode) && aNode.href) ||
271 (content.HTMLAreaElement.isInstance(aNode) && aNode.href) ||
272 content.HTMLLinkElement.isInstance(aNode)
276 let node = event.composedTarget;
277 while (node && !isHTMLLink(node)) {
278 node = node.flattenedTreeParentNode;
282 return [node.href, node, node.ownerDocument.nodePrincipal];
285 // If there is no linkNode, try simple XLink.
287 node = event.composedTarget;
288 while (node && !href) {
290 node.nodeType == content.Node.ELEMENT_NODE &&
291 (node.localName == "a" ||
292 node.namespaceURI == "http://www.w3.org/1998/Math/MathML")
295 node.getAttribute("href") ||
296 node.getAttributeNS("http://www.w3.org/1999/xlink", "href");
298 baseURI = node.ownerDocument.baseURIObject;
302 node = node.flattenedTreeParentNode;
305 // In case of XLink, we don't return the node we got href from since
306 // callers expect <a>-like elements.
307 // Note: makeURI() will throw if aUri is not a valid URI.
309 href ? Services.io.newURI(href, null, baseURI).spec : null,
311 node && node.ownerDocument.nodePrincipal,
316 * whereToOpenLink() looks at an event to decide where to open a link.
318 * The event may be a mouse event (click, double-click, middle-click) or keypress event (enter).
320 * On Windows, the modifiers are:
321 * Ctrl new tab, selected
323 * Ctrl+Shift new tab, in background
326 * Middle-clicking is the same as Ctrl+clicking (it opens a new tab).
329 * - Alt is ignored for menu items selected using the keyboard so you don't accidentally save stuff.
330 * (Currently, the Alt isn't sent here at all for menu items, but that will change in bug 126189.)
331 * - Alt is hard to use in context menus, because pressing Alt closes the menu.
332 * - Alt can't be used on the bookmarks toolbar because Alt is used for "treat this as something draggable".
333 * - The button is ignored for the middle-click-paste-URL feature, since it's always a middle-click.
335 * @param e {Event|Object} Event or JSON Object
336 * @param ignoreButton {Boolean}
337 * @param ignoreAlt {Boolean}
338 * @returns {"current" | "tabshifted" | "tab" | "save" | "window"}
340 whereToOpenLink(e, ignoreButton, ignoreAlt) {
341 // This method must treat a null event like a left click without modifier keys (i.e.
342 // e = { shiftKey:false, ctrlKey:false, metaKey:false, altKey:false, button:0 })
343 // for compatibility purposes.
348 e = this.getRootEvent(e);
350 var shift = e.shiftKey;
351 var ctrl = e.ctrlKey;
352 var meta = e.metaKey;
353 var alt = e.altKey && !ignoreAlt;
355 // ignoreButton allows "middle-click paste" to use function without always opening in a new window.
356 let middle = !ignoreButton && e.button == 1;
357 let middleUsesTabs = Services.prefs.getBoolPref(
358 "browser.tabs.opentabfor.middleclick",
361 let middleUsesNewWindow = Services.prefs.getBoolPref(
362 "middlemouse.openNewWindow",
366 // Don't do anything special with right-mouse clicks. They're probably clicks on context menu items.
368 // See also nsWindowWatcher::GetWindowOpenLocation in
369 // toolkit/components/windowwatcher/nsWindowWatcher.cpp
371 var metaKey = AppConstants.platform == "macosx" ? meta : ctrl;
372 if (metaKey || (middle && middleUsesTabs)) {
373 return shift ? "tabshifted" : "tab";
376 if (alt && Services.prefs.getBoolPref("browser.altClickSave", false)) {
380 if (shift || (middle && !middleUsesTabs && middleUsesNewWindow)) {
387 // Utility function to check command events for potential middle-click events
388 // from checkForMiddleClick and unwrap them.
389 getRootEvent(aEvent) {
390 // Part of the fix for Bug 1523813.
391 // Middle-click events arrive here wrapped in different numbers (1-2) of
392 // command events, depending on the button originally clicked.
396 let tempEvent = aEvent;
397 while (tempEvent.sourceEvent) {
398 if (tempEvent.sourceEvent.button == 1) {
399 aEvent = tempEvent.sourceEvent;
402 tempEvent = tempEvent.sourceEvent;
408 * An enumeration of the promotion types that can be passed to shouldShowPromo
411 DEFAULT: 0, // invalid
420 * Should a given promo be shown to the user now, based on things including:
424 * where ads for a particular thing are allowed
425 * where they are illegal
426 * in what regions is the thing being promoted supported?
427 * whether there is an active enterprise policy
428 * settings of specific preferences related to this promo
430 * @param {BrowserUtils.PromoType} promoType - What promo are we checking on?
432 * @return {boolean} - should we display this promo now or not?
434 shouldShowPromo(promoType) {
436 case this.PromoType.VPN:
437 case this.PromoType.FOCUS:
438 case this.PromoType.PIN:
439 case this.PromoType.RELAY:
440 case this.PromoType.COOKIE_BANNERS:
443 throw new Error("Unknown promo type: ", promoType);
446 const info = PromoInfo[promoType];
448 !info.enabledPref || Services.prefs.getBoolPref(info.enabledPref, true);
450 const homeRegion = lazy.Region.home || "";
451 const currentRegion = lazy.Region.current || "";
453 let inSupportedRegion = true;
454 if ("supportedRegions" in info.lazyStringSetPrefs) {
455 const supportedRegions =
456 info.lazyStringSetPrefs.supportedRegions.lazyValue;
458 supportedRegions.has(currentRegion.toLowerCase()) ||
459 supportedRegions.has(homeRegion.toLowerCase());
462 const avoidAdsRegions =
463 info.lazyStringSetPrefs.disallowedRegions?.lazyValue;
465 // Don't show promo if there's an active enterprise policy
466 const noActivePolicy =
467 info.showForEnterprise ||
468 !Services.policies ||
469 Services.policies.status !== Services.policies.ACTIVE;
471 // Promos may add custom checks that must pass.
472 const passedExtraCheck = !info.extraCheck || info.extraCheck();
476 !avoidAdsRegions?.has(homeRegion.toLowerCase()) &&
477 !avoidAdsRegions?.has(currentRegion.toLowerCase()) &&
478 !info.illegalRegions.includes(homeRegion.toLowerCase()) &&
479 !info.illegalRegions.includes(currentRegion.toLowerCase()) &&
487 * @deprecated in favor of shouldShowPromo
489 shouldShowVPNPromo() {
490 return this.shouldShowPromo(this.PromoType.VPN);
493 // Return true if Send to Device emails are supported for user's locale
494 sendToDeviceEmailsSupported() {
495 const userLocale = Services.locale.appLocaleAsBCP47.toLowerCase();
496 return this.emailSupportedLocales.has(userLocale);
501 * A table of promos used by shouldShowPromo to decide whether or not to show.
502 * Each entry defines the criteria for a given promo, and also houses lazy
503 * getters for specified string set preferences.
506 [BrowserUtils.PromoType.VPN]: {
507 enabledPref: "browser.vpn_promo.enabled",
508 lazyStringSetPrefs: {
510 name: "browser.contentblocking.report.vpn_regions",
512 "ca,my,nz,sg,gb,gg,im,io,je,uk,vg,as,mp,pr,um,us,vi,de,fr,at,be,ch,es,it,ie,nl,se,fi,bg,cy,cz,dk,ee,hr,hu,lt,lu,lv,mt,pl,pt,ro,si,sk",
515 name: "browser.vpn_promo.disallowed_regions",
516 default: "ae,by,cn,cu,iq,ir,kp,om,ru,sd,sy,tm,tr",
519 //See https://github.com/search?q=repo%3Amozilla%2Fbedrock+VPN_EXCLUDED_COUNTRY_CODES&type=code
536 [BrowserUtils.PromoType.FOCUS]: {
537 enabledPref: "browser.promo.focus.enabled",
538 lazyStringSetPrefs: {
539 // there are no particular limitions to where it is "supported",
540 // so we leave out the supported pref
542 name: "browser.promo.focus.disallowed_regions",
546 illegalRegions: ["cn"],
548 [BrowserUtils.PromoType.PIN]: {
549 enabledPref: "browser.promo.pin.enabled",
550 lazyStringSetPrefs: {},
553 [BrowserUtils.PromoType.RELAY]: {
554 lazyStringSetPrefs: {},
556 // Returns true if user is using the FxA "production" instance, or returns
557 // false for custom FxA instance (such as accounts.firefox.com.cn for the
558 // China repack) which doesn't support authentication for addons like Relay.
560 !Services.prefs.getCharPref("identity.fxaccounts.autoconfig.uri", "") &&
562 "identity.fxaccounts.remote.root",
563 "identity.fxaccounts.auth.uri",
564 "identity.fxaccounts.remote.oauth.uri",
565 "identity.fxaccounts.remote.profile.uri",
566 "identity.fxaccounts.remote.pairing.uri",
567 "identity.sync.tokenserver.uri",
568 ].every(pref => !Services.prefs.prefHasUserValue(pref)),
570 [BrowserUtils.PromoType.COOKIE_BANNERS]: {
571 enabledPref: "browser.promo.cookiebanners.enabled",
572 lazyStringSetPrefs: {},
574 showForEnterprise: true,
579 * Finish setting up the PromoInfo data structure by attaching lazy prefs getters
580 * as specified in the structure. (the object for each pref in the lazyStringSetPrefs
581 * gets a `lazyValue` property attached to it).
583 for (let promo of Object.values(PromoInfo)) {
584 for (let prefObj of Object.values(promo.lazyStringSetPrefs)) {
585 XPCOMUtils.defineLazyPreferenceGetter(
596 XPCOMUtils.defineLazyPreferenceGetter(
598 "navigationRequireUserInteraction",
599 "browser.navigation.requireUserInteraction",
603 XPCOMUtils.defineLazyPreferenceGetter(
605 "emailSupportedLocales",
606 "browser.send_to_device_locales",
607 "de,en-GB,en-US,es-AR,es-CL,es-ES,es-MX,fr,id,pl,pt-BR,ru,zh-TW",