summaryrefslogtreecommitdiffstats
path: root/browser/components/protocolhandler
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-19 00:47:55 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-19 00:47:55 +0000
commit26a029d407be480d791972afb5975cf62c9360a6 (patch)
treef435a8308119effd964b339f76abb83a57c29483 /browser/components/protocolhandler
parentInitial commit. (diff)
downloadfirefox-26a029d407be480d791972afb5975cf62c9360a6.tar.xz
firefox-26a029d407be480d791972afb5975cf62c9360a6.zip
Adding upstream version 124.0.1.upstream/124.0.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'browser/components/protocolhandler')
-rw-r--r--browser/components/protocolhandler/WebProtocolHandlerRegistrar.sys.mjs506
-rw-r--r--browser/components/protocolhandler/components.conf15
-rw-r--r--browser/components/protocolhandler/metrics.yaml55
-rw-r--r--browser/components/protocolhandler/moz.build18
-rw-r--r--browser/components/protocolhandler/test/browser/browser.toml5
-rw-r--r--browser/components/protocolhandler/test/browser/browser_registerProtocolHandler_notification.html15
-rw-r--r--browser/components/protocolhandler/test/browser/browser_registerProtocolHandler_notification.js57
-rw-r--r--browser/components/protocolhandler/test/test_registerHandler.html88
8 files changed, 759 insertions, 0 deletions
diff --git a/browser/components/protocolhandler/WebProtocolHandlerRegistrar.sys.mjs b/browser/components/protocolhandler/WebProtocolHandlerRegistrar.sys.mjs
new file mode 100644
index 0000000000..927685c83c
--- /dev/null
+++ b/browser/components/protocolhandler/WebProtocolHandlerRegistrar.sys.mjs
@@ -0,0 +1,506 @@
+/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const STRING_BUNDLE_URI = "chrome://browser/locale/feeds/subscribe.properties";
+
+export function WebProtocolHandlerRegistrar() {}
+
+const lazy = {};
+
+ChromeUtils.defineESModuleGetters(lazy, {
+ NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
+});
+
+ChromeUtils.defineLazyGetter(lazy, "log", () => {
+ let { ConsoleAPI } = ChromeUtils.importESModule(
+ "resource://gre/modules/Console.sys.mjs"
+ );
+ let consoleOptions = {
+ // tip: set maxLogLevel to "debug" and use lazy.log.debug() to create
+ // detailed messages during development. See LOG_LEVELS in Console.sys.mjs
+ // for details.
+ maxLogLevel: "warning",
+ maxLogLevelPref: "browser.protocolhandler.loglevel",
+ prefix: "WebProtocolHandlerRegistrar.sys.mjs",
+ };
+ return new ConsoleAPI(consoleOptions);
+});
+
+WebProtocolHandlerRegistrar.prototype = {
+ get stringBundle() {
+ let sb = Services.strings.createBundle(STRING_BUNDLE_URI);
+ delete WebProtocolHandlerRegistrar.prototype.stringBundle;
+ return (WebProtocolHandlerRegistrar.prototype.stringBundle = sb);
+ },
+
+ _getFormattedString(key, params) {
+ return this.stringBundle.formatStringFromName(key, params);
+ },
+
+ _getString(key) {
+ return this.stringBundle.GetStringFromName(key);
+ },
+
+ /**
+ * See nsIWebProtocolHandlerRegistrar
+ */
+ removeProtocolHandler(aProtocol, aURITemplate) {
+ let eps = Cc[
+ "@mozilla.org/uriloader/external-protocol-service;1"
+ ].getService(Ci.nsIExternalProtocolService);
+ let handlerInfo = eps.getProtocolHandlerInfo(aProtocol);
+ let handlers = handlerInfo.possibleApplicationHandlers;
+ for (let i = 0; i < handlers.length; i++) {
+ try {
+ // We only want to test web handlers
+ let handler = handlers.queryElementAt(i, Ci.nsIWebHandlerApp);
+ if (handler.uriTemplate == aURITemplate) {
+ handlers.removeElementAt(i);
+ let hs = Cc["@mozilla.org/uriloader/handler-service;1"].getService(
+ Ci.nsIHandlerService
+ );
+ hs.store(handlerInfo);
+ return;
+ }
+ } catch (e) {
+ /* it wasn't a web handler */
+ }
+ }
+ },
+
+ /**
+ * Determines if a web handler is already registered.
+ *
+ * @param {string} aProtocol
+ * The scheme of the web handler we are checking for.
+ * @param {string} aURITemplate
+ * The URI template that the handler uses to handle the protocol.
+ * @returns {boolean} true if it is already registered, false otherwise.
+ */
+ _protocolHandlerRegistered(aProtocol, aURITemplate) {
+ let eps = Cc[
+ "@mozilla.org/uriloader/external-protocol-service;1"
+ ].getService(Ci.nsIExternalProtocolService);
+ let handlerInfo = eps.getProtocolHandlerInfo(aProtocol);
+ let handlers = handlerInfo.possibleApplicationHandlers;
+ for (let i = 0; i < handlers.length; i++) {
+ try {
+ // We only want to test web handlers
+ let handler = handlers.queryElementAt(i, Ci.nsIWebHandlerApp);
+ if (handler.uriTemplate == aURITemplate) {
+ return true;
+ }
+ } catch (e) {
+ /* it wasn't a web handler */
+ lazy.log.debug("No protocolHandler registered, because: " + e.message);
+ }
+ }
+ return false;
+ },
+
+ /**
+ * Private method to return the installHash, which is important for app
+ * registration on OS level. Without it apps cannot be default/handler apps
+ * under Windows. Because this value is used to check if its possible to reset
+ * the default and to actually set it as well, this function puts the
+ * acquisition of the installHash in one place in the hopes that check and set
+ * conditions will never deviate.
+ *
+ * @returns {string} installHash
+ */
+ _getInstallHash() {
+ const xreDirProvider = Cc[
+ "@mozilla.org/xre/directory-provider;1"
+ ].getService(Ci.nsIXREDirProvider);
+ return xreDirProvider.getInstallHash();
+ },
+
+ /**
+ * Private method to determine if we can set a new OS default for a certain
+ * protocol.
+ *
+ * @param {string} protocol name, e.g. mailto (without ://)
+ * @returns {boolean}
+ */
+ _canSetOSDefault(protocol) {
+ // can be toggled off individually if necessary...
+ if (!lazy.NimbusFeatures.mailto.getVariable("dualPrompt.os")) {
+ lazy.log.debug("_canSetOSDefault: false: mailto rollout deactivated.");
+ return false;
+ }
+
+ // this preferences saves that the user has dismissed the bar before...
+ if (!Services.prefs.getBoolPref("browser.mailto.prompt.os", true)) {
+ lazy.log.debug("_canSetOSDefault: false: prompt dismissed before.");
+ return false;
+ }
+
+ // an installHash is required for the association with a scheme handler
+ if ("" == this._getInstallHash()) {
+ lazy.log.debug("_canSetOSDefault: false: no installation hash.");
+ return false;
+ }
+
+ // check if we are already the protocolhandler...
+ let shellService = Cc[
+ "@mozilla.org/browser/shell-service;1"
+ ].createInstance(Ci.nsIWindowsShellService);
+
+ if (shellService.isDefaultHandlerFor(protocol)) {
+ lazy.log.debug("_canSetOSDefault: false: is already default handler.");
+ return false;
+ }
+
+ return true;
+ },
+
+ /**
+ * Private method to reset the OS default for a certain protocol/uri scheme.
+ * We basically ignore, that setDefaultExtensionHandlersUserChoice can fail
+ * when the installHash is wrong or cannot be determined.
+ *
+ * @param {string} protocol name, e.g. mailto (without ://)
+ * @returns {boolean}
+ */
+ _setOSDefault(protocol) {
+ try {
+ let defaultAgent = Cc["@mozilla.org/default-agent;1"].createInstance(
+ Ci.nsIDefaultAgent
+ );
+ defaultAgent.setDefaultExtensionHandlersUserChoice(
+ this._getInstallHash(),
+ [protocol, "FirefoxURL"]
+ );
+ return true;
+ } catch (e) {
+ // TODO: why could not we just add the installHash and promote the running
+ // install to be a properly installed one?
+ lazy.log.debug(
+ "Could not set Firefox as default application for " +
+ protocol +
+ ", because: " +
+ e.message
+ );
+ }
+ return false;
+ },
+
+ /**
+ * Private method to set the default uri to handle a certain protocol. This
+ * automates in a way what a user can do in settings under applications,
+ * where different 'actions' can be chosen for different 'content types'.
+ *
+ * @param {string} protocol
+ * @param {handler} handler
+ */
+ _setLocalDefault(protocol, handler) {
+ let eps = Cc[
+ "@mozilla.org/uriloader/external-protocol-service;1"
+ ].getService(Ci.nsIExternalProtocolService);
+
+ let handlerInfo = eps.getProtocolHandlerInfo(protocol);
+ handlerInfo.preferredAction = Ci.nsIHandlerInfo.useHelperApp; // this is IMPORTANT!
+ handlerInfo.preferredApplicationHandler = handler;
+ handlerInfo.alwaysAskBeforeHandling = false;
+ let hs = Cc["@mozilla.org/uriloader/handler-service;1"].getService(
+ Ci.nsIHandlerService
+ );
+ hs.store(handlerInfo);
+ },
+
+ /**
+ * Private method to set the default uri to handle a certain protocol. This
+ * automates in a way what a user can do in settings under applications,
+ * where different 'actions' can be chosen for different 'content types'.
+ *
+ * @param {string} protocol - e.g. 'mailto', so again without ://
+ * @param {string} name - the protocol associated 'Action'
+ * @param {string} uri - the uri (compare 'use other...' in the preferences)
+ * @returns {handler} handler - either the existing one or a newly created
+ */
+ _addLocal(protocol, name, uri) {
+ let eps = Cc[
+ "@mozilla.org/uriloader/external-protocol-service;1"
+ ].getService(Ci.nsIExternalProtocolService);
+
+ let phi = eps.getProtocolHandlerInfo(protocol);
+ // not adding duplicates and bail out with the existing entry
+ for (let h of phi.possibleApplicationHandlers.enumerate()) {
+ if (h.uriTemplate == uri) {
+ return h;
+ }
+ }
+
+ let handler = Cc["@mozilla.org/uriloader/web-handler-app;1"].createInstance(
+ Ci.nsIWebHandlerApp
+ );
+ handler.name = name;
+ handler.uriTemplate = uri;
+
+ let handlerInfo = eps.getProtocolHandlerInfo(protocol);
+ handlerInfo.possibleApplicationHandlers.appendElement(handler);
+
+ // Since the user has agreed to add a new handler, chances are good
+ // that the next time they see a handler of this type, they're going
+ // to want to use it. Reset the handlerInfo to ask before the next
+ // use.
+ handlerInfo.alwaysAskBeforeHandling = true;
+
+ let hs = Cc["@mozilla.org/uriloader/handler-service;1"].getService(
+ Ci.nsIHandlerService
+ );
+ hs.store(handlerInfo);
+
+ return handler;
+ },
+
+ /**
+ * See nsIWebProtocolHandlerRegistrar
+ */
+ registerProtocolHandler(
+ aProtocol,
+ aURI,
+ aTitle,
+ aDocumentURI,
+ aBrowserOrWindow
+ ) {
+ // first mitigation: check if the API call comes from another domain
+ aProtocol = (aProtocol || "").toLowerCase();
+ if (!aURI || !aDocumentURI) {
+ return;
+ }
+
+ let browser = aBrowserOrWindow; // This is the e10s case.
+ if (aBrowserOrWindow instanceof Ci.nsIDOMWindow) {
+ // In the non-e10s case, grab the browser off the same-process window.
+ let rootDocShell = aBrowserOrWindow.docShell.sameTypeRootTreeItem;
+ browser = rootDocShell.QueryInterface(Ci.nsIDocShell).chromeEventHandler;
+ }
+
+ let browserWindow = browser.ownerGlobal;
+ try {
+ browserWindow.navigator.checkProtocolHandlerAllowed(
+ aProtocol,
+ aURI,
+ aDocumentURI
+ );
+ } catch (ex) {
+ // We should have already shown the user an error.
+ return;
+ }
+ if (lazy.NimbusFeatures.mailto.getVariable("dualPrompt")) {
+ if ("mailto" === aProtocol) {
+ this._askUserToSetMailtoHandler(browser, aProtocol, aURI, aTitle);
+ return;
+ }
+ }
+
+ // If the protocol handler is already registered, just return early.
+ if (this._protocolHandlerRegistered(aProtocol, aURI.spec)) {
+ return;
+ }
+
+ // Now Ask the user and provide the proper callback
+ let message = this._getFormattedString("addProtocolHandlerMessage", [
+ aURI.host,
+ aProtocol,
+ ]);
+
+ let notificationIcon = aURI.prePath + "/favicon.ico";
+ let notificationValue = "Protocol Registration: " + aProtocol;
+ let addButton = {
+ label: this._getString("addProtocolHandlerAddButton"),
+ accessKey: this._getString("addProtocolHandlerAddButtonAccesskey"),
+ protocolInfo: { protocol: aProtocol, uri: aURI.spec, name: aTitle },
+
+ callback(aNotification, aButtonInfo) {
+ let protocol = aButtonInfo.protocolInfo.protocol;
+ let name = aButtonInfo.protocolInfo.name;
+
+ let handler = Cc[
+ "@mozilla.org/uriloader/web-handler-app;1"
+ ].createInstance(Ci.nsIWebHandlerApp);
+ handler.name = name;
+ handler.uriTemplate = aButtonInfo.protocolInfo.uri;
+
+ let eps = Cc[
+ "@mozilla.org/uriloader/external-protocol-service;1"
+ ].getService(Ci.nsIExternalProtocolService);
+ let handlerInfo = eps.getProtocolHandlerInfo(protocol);
+ handlerInfo.possibleApplicationHandlers.appendElement(handler);
+
+ // Since the user has agreed to add a new handler, chances are good
+ // that the next time they see a handler of this type, they're going
+ // to want to use it. Reset the handlerInfo to ask before the next
+ // use.
+ handlerInfo.alwaysAskBeforeHandling = true;
+
+ let hs = Cc["@mozilla.org/uriloader/handler-service;1"].getService(
+ Ci.nsIHandlerService
+ );
+ hs.store(handlerInfo);
+ },
+ };
+
+ let notificationBox = browser.getTabBrowser().getNotificationBox(browser);
+
+ // check if the notification box is already shown
+ if (notificationBox.getNotificationWithValue(notificationValue)) {
+ return;
+ }
+
+ notificationBox.appendNotification(
+ notificationValue,
+ {
+ label: message,
+ image: notificationIcon,
+ priority: notificationBox.PRIORITY_INFO_LOW,
+ },
+ [addButton]
+ );
+ },
+
+ /*
+ * Special implementation for mailto
+ *
+ * @param {string} browser
+ * @param {string} aProtocol
+ * @param {string} aURI
+ * @param {string} aTitle
+ */
+ async _askUserToSetMailtoHandler(browser, aProtocol, aURI, aTitle) {
+ // shortcut for Localization
+ let l10n = new Localization([
+ "branding/brand.ftl",
+ "browser/webProtocolHandler.ftl",
+ ]);
+ let [
+ msg_os_box,
+ msg_os_yes_confirm,
+ msg_os_yes,
+ msg_os_no,
+ msg_box,
+ msg_yes_confirm,
+ msg_yes,
+ msg_no,
+ ] = await l10n.formatValues([
+ { id: "protocolhandler-mailto-os-handler-notificationbox" },
+ { id: "protocolhandler-mailto-os-handler-yes-confirm" },
+ { id: "protocolhandler-mailto-os-handler-yes-button" },
+ { id: "protocolhandler-mailto-os-handler-no-button" },
+ {
+ id: "protocolhandler-mailto-handler-notificationbox-always",
+ args: { url: aURI.prePath },
+ },
+ {
+ id: "protocolhandler-mailto-handler-yes-confirm",
+ args: { url: aURI.prePath },
+ },
+ { id: "protocolhandler-mailto-handler-yes-button" },
+ { id: "protocolhandler-mailto-handler-no-button" },
+ ]);
+
+ // First prompt:
+ // Only shown if there is a realistic chance that we can really set the OS
+ // default and can also be disabled with a preference or experiement
+ if (this._canSetOSDefault(aProtocol)) {
+ // Only show if not already set and if we have been properly installed
+ let notificationId = "OS Protocol Registration: " + aProtocol;
+ let osDefaultNotificationBox = browser
+ .getTabBrowser()
+ .getNotificationBox(browser);
+ if (!osDefaultNotificationBox.getNotificationWithValue(notificationId)) {
+ osDefaultNotificationBox.appendNotification(
+ notificationId,
+ {
+ label: msg_os_box,
+ priority: osDefaultNotificationBox.PRIORITY_INFO_LOW,
+ },
+ [
+ {
+ label: msg_os_yes,
+ callback: () => {
+ this._setOSDefault(aProtocol);
+ Glean.protocolhandlerMailto.promptClicked.set_os_default.add();
+ osDefaultNotificationBox.appendNotification(
+ notificationId,
+ {
+ label: msg_os_yes_confirm,
+ priority: osDefaultNotificationBox.PRIORITY_INFO_LOW,
+ },
+ []
+ );
+ return false;
+ },
+ },
+ {
+ label: msg_os_no,
+ callback: () => {
+ Services.prefs.setBoolPref("browser.mailto.prompt.os", false);
+ Glean.protocolhandlerMailto.promptClicked.dismiss_os_default.add();
+ return false;
+ },
+ },
+ ]
+ );
+
+ Glean.protocolhandlerMailto.handlerPromptShown.os_default.add();
+ }
+ }
+
+ // Second prompt:
+ // Only shown if the protocol handler is not already registered
+ if (!this._protocolHandlerRegistered(aProtocol, aURI.spec)) {
+ let notificationId = "Protocol Registration: " + aProtocol;
+ let FxDefaultNotificationBox = browser
+ .getTabBrowser()
+ .getNotificationBox(browser);
+ if (!FxDefaultNotificationBox.getNotificationWithValue(notificationId)) {
+ FxDefaultNotificationBox.appendNotification(
+ notificationId,
+ {
+ label: msg_box,
+ priority: FxDefaultNotificationBox.PRIORITY_INFO_LOW,
+ },
+ [
+ {
+ label: msg_yes,
+ callback: () => {
+ this._setLocalDefault(
+ aProtocol,
+ this._addLocal(aProtocol, aTitle, aURI.spec)
+ );
+ Glean.protocolhandlerMailto.promptClicked.set_local_default.add();
+ FxDefaultNotificationBox.appendNotification(
+ notificationId,
+ {
+ label: msg_yes_confirm,
+ priority: FxDefaultNotificationBox.PRIORITY_INFO_LOW,
+ },
+ []
+ );
+ return false;
+ },
+ },
+ {
+ label: msg_no,
+ callback: () => {
+ Glean.protocolhandlerMailto.promptClicked.dismiss_local_default.add();
+ return false;
+ },
+ },
+ ]
+ );
+
+ Glean.protocolhandlerMailto.handlerPromptShown.fx_default.add();
+ }
+ }
+ },
+
+ /**
+ * See nsISupports
+ */
+ QueryInterface: ChromeUtils.generateQI(["nsIWebProtocolHandlerRegistrar"]),
+};
diff --git a/browser/components/protocolhandler/components.conf b/browser/components/protocolhandler/components.conf
new file mode 100644
index 0000000000..6fd4f03595
--- /dev/null
+++ b/browser/components/protocolhandler/components.conf
@@ -0,0 +1,15 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+Classes = [
+ {
+ 'cid': '{efbd7b87-9b15-4684-abf0-dc2679daadb1}',
+ 'contract_ids': ['@mozilla.org/embeddor.implemented/web-protocol-handler-registrar;1'],
+ 'esModule': 'resource:///modules/WebProtocolHandlerRegistrar.sys.mjs',
+ 'constructor': 'WebProtocolHandlerRegistrar',
+ 'processes': ProcessSelector.MAIN_PROCESS_ONLY,
+ },
+]
diff --git a/browser/components/protocolhandler/metrics.yaml b/browser/components/protocolhandler/metrics.yaml
new file mode 100644
index 0000000000..43a2898175
--- /dev/null
+++ b/browser/components/protocolhandler/metrics.yaml
@@ -0,0 +1,55 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+# Adding a new metric? We have docs for that!
+
+# https://firefox-source-docs.mozilla.org/toolkit/components/glean/user/new_definitions_file.html
+
+---
+$schema: moz://mozilla.org/schemas/glean/metrics/2-0-0
+$tags:
+ - 'Firefox :: General'
+
+protocolhandler.mailto:
+ prompt_clicked:
+ type: labeled_counter
+ description: >
+ User clicked on a button to approve setting the current site as default
+ web mail site. The sum of all counters is the total amount of user
+ interactions and dismissing the same dialog often could be a sign of
+ a bug.
+ bugs:
+ - https://bugzilla.mozilla.org/1864216
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1864216#c8
+ notification_emails:
+ - install-update@mozilla.com
+ expires: never
+ labels:
+ - set_os_default
+ - dismiss_os_default
+ - set_local_default
+ - dismiss_local_default
+ send_in_pings:
+ - active
+ - metrics
+
+ handler_prompt_shown:
+ type: labeled_counter
+ description: >
+ A website was visited, which called registerProtocolHandler
+ for mailto://
+ bugs:
+ - https://bugzilla.mozilla.org/1864216
+ data_reviews:
+ - https://bugzilla.mozilla.org/show_bug.cgi?id=1864216#c8
+ notification_emails:
+ - install-update@mozilla.com
+ expires: never
+ labels:
+ - os_default
+ - fx_default
+ send_in_pings:
+ - active
+ - metrics
diff --git a/browser/components/protocolhandler/moz.build b/browser/components/protocolhandler/moz.build
new file mode 100644
index 0000000000..0bd67ba621
--- /dev/null
+++ b/browser/components/protocolhandler/moz.build
@@ -0,0 +1,18 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+BROWSER_CHROME_MANIFESTS += ["test/browser/browser.toml"]
+
+EXTRA_JS_MODULES += [
+ "WebProtocolHandlerRegistrar.sys.mjs",
+]
+
+XPCOM_MANIFESTS += [
+ "components.conf",
+]
+
+with Files("**"):
+ BUG_COMPONENT = ("Firefox", "General")
diff --git a/browser/components/protocolhandler/test/browser/browser.toml b/browser/components/protocolhandler/test/browser/browser.toml
new file mode 100644
index 0000000000..73a0ad72d2
--- /dev/null
+++ b/browser/components/protocolhandler/test/browser/browser.toml
@@ -0,0 +1,5 @@
+[DEFAULT]
+
+["browser_registerProtocolHandler_notification.js"]
+support-files = ["browser_registerProtocolHandler_notification.html"]
+skip-if = ["verify"]
diff --git a/browser/components/protocolhandler/test/browser/browser_registerProtocolHandler_notification.html b/browser/components/protocolhandler/test/browser/browser_registerProtocolHandler_notification.html
new file mode 100644
index 0000000000..6ffacd2e85
--- /dev/null
+++ b/browser/components/protocolhandler/test/browser/browser_registerProtocolHandler_notification.html
@@ -0,0 +1,15 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<html>
+ <head>
+ <title>Protocol registrar page</title>
+ <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
+ <meta content="utf-8" http-equiv="encoding">
+ </head>
+ <body>
+ <script type="text/javascript">
+ navigator.registerProtocolHandler("web+testprotocol",
+ "https://example.com/foobar?uri=%s",
+ "Test Protocol");
+ </script>
+ </body>
+</html>
diff --git a/browser/components/protocolhandler/test/browser/browser_registerProtocolHandler_notification.js b/browser/components/protocolhandler/test/browser/browser_registerProtocolHandler_notification.js
new file mode 100644
index 0000000000..e2598ae281
--- /dev/null
+++ b/browser/components/protocolhandler/test/browser/browser_registerProtocolHandler_notification.js
@@ -0,0 +1,57 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const TEST_PATH = getRootDirectory(gTestPath).replace(
+ "chrome://mochitests/content",
+ "https://example.com"
+);
+add_task(async function () {
+ let notificationValue = "Protocol Registration: web+testprotocol";
+ let testURI = TEST_PATH + "browser_registerProtocolHandler_notification.html";
+
+ BrowserTestUtils.startLoadingURIString(
+ window.gBrowser.selectedBrowser,
+ testURI
+ );
+ await TestUtils.waitForCondition(
+ function () {
+ // Do not start until the notification is up
+ let notificationBox = window.gBrowser.getNotificationBox();
+ let notification =
+ notificationBox.getNotificationWithValue(notificationValue);
+ return notification;
+ },
+ "Still can not get notification after retrying 100 times.",
+ 100,
+ 100
+ );
+
+ let notificationBox = window.gBrowser.getNotificationBox();
+ let notification =
+ notificationBox.getNotificationWithValue(notificationValue);
+ ok(notification, "Notification box should be displayed");
+ if (notification == null) {
+ finish();
+ return;
+ }
+ is(
+ notification.getAttribute("type"),
+ "info",
+ "We expect this notification to have the type of 'info'."
+ );
+ is(
+ notification.messageImage.getAttribute("src"),
+ "chrome://global/skin/icons/info-filled.svg",
+ "We expect this notification to have an icon."
+ );
+
+ let buttons = notification.buttonContainer.getElementsByClassName(
+ "notification-button"
+ );
+ is(buttons.length, 1, "We expect see one button.");
+
+ let button = buttons[0];
+ isnot(button.label, null, "We expect the add button to have a label.");
+ todo(button.accesskey, "We expect the add button to have a accesskey.");
+});
diff --git a/browser/components/protocolhandler/test/test_registerHandler.html b/browser/components/protocolhandler/test/test_registerHandler.html
new file mode 100644
index 0000000000..2eb4f7dbdc
--- /dev/null
+++ b/browser/components/protocolhandler/test/test_registerHandler.html
@@ -0,0 +1,88 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=402788
+-->
+<head>
+ <title>Test for Bug 402788</title>
+ <script src="/tests/SimpleTest/SimpleTest.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=402788">Mozilla Bug 402788</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+
+</div>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+
+/** Test for Bug 402788 */
+ SimpleTest.waitForExplicitFinish();
+
+ // return false if an exception has been catched, true otherwise
+ function testRegisterHandler(aIsProtocol, aTxt, aUri, aTitle) {
+ try {
+ navigator.registerProtocolHandler(aTxt, aUri, aTitle);
+ } catch (e) {
+ return false;
+ }
+
+ return true;
+ }
+
+ // helper function to build URLs since hostname differs
+ // based on whether the test is running in a cross-origin iframe
+ function buildUrl(protocol="http", addFormat=true) {
+ return `${protocol}://${window.location.hostname}:${window.location.port}${addFormat ? "/%s" : "/"}`;
+ }
+
+ async function tests() {
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ ["dom.registerProtocolHandler.insecure.enabled", true],
+ ],
+ });
+
+ // testing a generic case
+ is(testRegisterHandler(true, "web+foo", buildUrl(), "Foo handler"), true, "registering a web+foo protocol handler should work");
+
+ // testing with wrong uris
+ is(testRegisterHandler(true, "web+foo", buildUrl("http", false), "Foo handler"), false, "a protocol handler uri should contain %s");
+
+ // the spec explicitly allows relative urls to be passed
+ is(testRegisterHandler(true, "web+foo", "foo/%s", "Foo handler"), true, "a protocol handler uri should be valid");
+
+ // we should only accept to register when the handler has the same host as the current page (bug 402287)
+ is(testRegisterHandler(true, "fweb+oo", "http://remotehost:8888/%s", "Foo handler"), false, "registering a web+foo protocol handler with a different host should not work");
+
+ // restriction to http(s) for the uri of the handler (bug 401343)
+ // http is already tested in the generic case
+ // ftp should not work
+ is(testRegisterHandler(true, "web+foo", buildUrl("ftp"), "Foo handler"), false, "registering a web+foo protocol handler with ftp scheme should not work");
+ // chrome should not work
+ is(testRegisterHandler(true, "web+foo", buildUrl("chrome"), "Foo handler"), false, "registering a web+foo protocol handler with chrome scheme should not work");
+ // foo should not work
+ is(testRegisterHandler(true, "web+foo", buildUrl("foo"), "Foo handler"), false, "registering a web+foo protocol handler with foo scheme should not work");
+
+ // for security reasons, protocol handlers should never be registered for some schemes (chrome, vbscript, ...) (bug 402788)
+ is(testRegisterHandler(true, "chrome", buildUrl(), "chrome handler"), false, "registering a chrome protocol handler should not work");
+ is(testRegisterHandler(true, "vbscript", buildUrl(), "vbscript handler"), false, "registering a vbscript protocol handler should not work");
+ is(testRegisterHandler(true, "javascript", buildUrl(), "javascript handler"), false, "registering a javascript protocol handler should not work");
+ is(testRegisterHandler(true, "moz-icon", buildUrl(), "moz-icon handler"), false, "registering a moz-icon protocol handler should not work");
+
+ // registering anything not on the list of safe schemes and unprefixed by web+ shouldn't work
+ is(testRegisterHandler(true, "foo", buildUrl(), "chrome handler"), false, "registering a foo protocol handler should not work");
+ is(testRegisterHandler(true, "web+", buildUrl(), "chrome handler"), false, "registering a 'web+' protocol handler should not work");
+ is(testRegisterHandler(true, "web+1", buildUrl(), "chrome handler"), false, "registering a 'web+1' protocol handler should not work");
+
+
+ SimpleTest.finish();
+ }
+
+ tests();
+
+</script>
+</pre>
+</body>
+</html>