Bug 1068186: Update window.sidebar and window.external APIs to support e10s. r=felipe
authorDave Townsend <dtownsend@oxymoronical.com>
Mon, 02 Feb 2015 12:15:26 -0800
changeset 227881 9ebe4e3c108574196d551662e5c4cddc081dbe07
parent 227880 dee2c81352423dade29b5ef4dcaabab10c4fbdd5
child 227882 342c5706df11325a4f0d7c9a22c4e62ac2be3f65
child 227971 de4682147093de05c0dc76cb9ea66b35ffe77739
push id28245
push userkwierso@gmail.com
push dateFri, 06 Feb 2015 22:40:12 +0000
treeherdermozilla-central@342c5706df11 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersfelipe
bugs1068186, 518929, 530847, 517720
milestone38.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1068186: Update window.sidebar and window.external APIs to support e10s. r=felipe Moves nsSidebar.js to toolkit and makes it just pass messages to chrome for each API call. MainProcessSingleton listens for those messages and passes the call along to the search service. Combines the validation code into the same function and takes the opportunity to support relative URLs too. Adds a bunch of tests for these web APIs. Also fixes: Bug 518929: Implement window.external APIs in core code Bug 530847: Remove Fennec's nsISidebar implementation once that code is moved into the core Bug 517720: Adding a search engine using relative URIs is not supported
browser/components/moz.build
browser/components/search/test/browser.ini
browser/components/search/test/browser_webapi.js
browser/components/search/test/webapi.html
browser/components/sidebar/moz.build
browser/components/sidebar/nsSidebar.js
browser/components/sidebar/nsSidebar.manifest
browser/installer/package-manifest.in
mobile/android/components/MobileComponents.manifest
mobile/android/components/Sidebar.js
mobile/android/components/moz.build
toolkit/components/processsingleton/MainProcessSingleton.js
toolkit/components/search/moz.build
toolkit/components/search/nsSidebar.js
toolkit/components/search/toolkitsearch.manifest
--- a/browser/components/moz.build
+++ b/browser/components/moz.build
@@ -14,17 +14,16 @@ DIRS += [
     'migration',
     'places',
     'preferences',
     'privatebrowsing',
     'search',
     'sessionstore',
     'shell',
     'selfsupport',
-    'sidebar',
     'tabview',
     'uitour',
     'translation',
 ]
 
 DIRS += ['build']
 
 XPIDL_SOURCES += [
--- a/browser/components/search/test/browser.ini
+++ b/browser/components/search/test/browser.ini
@@ -6,16 +6,17 @@ support-files =
   483086-2.xml
   head.js
   opensearch.html
   test.html
   testEngine.src
   testEngine.xml
   testEngine_dupe.xml
   testEngine_mozsearch.xml
+  webapi.html
 
 [browser_405664.js]
 [browser_426329.js]
 skip-if = e10s # Bug ?????? - Test uses load event and checks event.target.
 [browser_483086.js]
 [browser_addEngine.js]
 [browser_amazon.js]
 [browser_amazon_behavior.js]
@@ -38,8 +39,9 @@ skip-if = e10s # Bug ?????? - Test uses 
 [browser_yahoo.js]
 [browser_yahoo_behavior.js]
 skip-if = e10s # Bug ?????? - some issue with progress listeners [JavaScript Error: "req.originalURI is null" {file: "chrome://mochitests/content/browser/browser/components/search/test/browser_bing_behavior.js" line: 127}]
 [browser_abouthome_behavior.js]
 skip-if = e10s || true # Bug ??????, Bug 1100301 - leaks windows until shutdown when --run-by-dir
 [browser_searchbar_openpopup.js]
 skip-if = os == "linux" || e10s # Linux has different focus behaviours and e10s seems to have timing issues.
 [browser_searchbar_keyboard_navigation.js]
+[browser_webapi.js]
new file mode 100644
--- /dev/null
+++ b/browser/components/search/test/browser_webapi.js
@@ -0,0 +1,174 @@
+let ROOT = getRootDirectory(gTestPath).replace("chrome://mochitests/content", "http://example.com");
+
+function AddSearchProvider(...args) {
+  return gBrowser.addTab(ROOT + "webapi.html?AddSearchProvider:" + encodeURIComponent(JSON.stringify(args)));
+}
+
+function addSearchEngine(...args) {
+  return gBrowser.addTab(ROOT + "webapi.html?addSearchEngine:" + encodeURIComponent(JSON.stringify(args)));
+}
+
+function promiseDialogOpened() {
+  return new Promise((resolve, reject) => {
+    Services.wm.addListener({
+      onOpenWindow: function(xulWin) {
+        Services.wm.removeListener(this);
+
+        let win = xulWin.QueryInterface(Ci.nsIInterfaceRequestor)
+                        .getInterface(Ci.nsIDOMWindow);
+        waitForFocus(() => {
+          if (win.location == "chrome://global/content/commonDialog.xul")
+            resolve(win)
+          else
+            reject();
+        }, win);
+      }
+    });
+  });
+}
+
+add_task(function* test_working_AddSearchProvider() {
+  gBrowser.selectedTab = AddSearchProvider(ROOT + "testEngine.xml");
+
+  let dialog = yield promiseDialogOpened();
+  is(dialog.args.promptType, "confirmEx", "Should see the confirmation dialog.");
+  is(dialog.args.text, "Add \"Foo\" to the list of engines available in the search bar?\n\nFrom: example.com",
+     "Should have seen the right install message");
+  dialog.document.documentElement.cancelDialog();
+
+  gBrowser.removeCurrentTab();
+});
+
+add_task(function* test_HTTP_AddSearchProvider() {
+  gBrowser.selectedTab = AddSearchProvider(ROOT.replace("http:", "HTTP:") + "testEngine.xml");
+
+  let dialog = yield promiseDialogOpened();
+  is(dialog.args.promptType, "confirmEx", "Should see the confirmation dialog.");
+  is(dialog.args.text, "Add \"Foo\" to the list of engines available in the search bar?\n\nFrom: example.com",
+     "Should have seen the right install message");
+  dialog.document.documentElement.cancelDialog();
+
+  gBrowser.removeCurrentTab();
+});
+
+add_task(function* test_relative_AddSearchProvider() {
+  gBrowser.selectedTab = AddSearchProvider("testEngine.xml");
+
+  let dialog = yield promiseDialogOpened();
+  is(dialog.args.promptType, "confirmEx", "Should see the confirmation dialog.");
+  is(dialog.args.text, "Add \"Foo\" to the list of engines available in the search bar?\n\nFrom: example.com",
+     "Should have seen the right install message");
+  dialog.document.documentElement.cancelDialog();
+
+  gBrowser.removeCurrentTab();
+});
+
+add_task(function* test_invalid_AddSearchProvider() {
+  gBrowser.selectedTab = AddSearchProvider("z://foobar");
+
+  let dialog = yield promiseDialogOpened();
+  is(dialog.args.promptType, "alert", "Should see the alert dialog.");
+  is(dialog.args.text, "This search engine isn't supported by Nightly and can't be installed.",
+     "Should have seen the right error message")
+  dialog.document.documentElement.acceptDialog();
+
+  gBrowser.removeCurrentTab();
+});
+
+add_task(function* test_missing_AddSearchProvider() {
+  let url = ROOT + "foobar.xml";
+  gBrowser.selectedTab = AddSearchProvider(url);
+
+  let dialog = yield promiseDialogOpened();
+  is(dialog.args.promptType, "alert", "Should see the alert dialog.");
+  is(dialog.args.text, "Nightly could not download the search plugin from:\n" + url,
+     "Should have seen the right error message")
+  dialog.document.documentElement.acceptDialog();
+
+  gBrowser.removeCurrentTab();
+});
+
+add_task(function* test_working_addSearchEngine_xml() {
+  gBrowser.selectedTab = addSearchEngine(ROOT + "testEngine.xml", "", "", "");
+
+  let dialog = yield promiseDialogOpened();
+  is(dialog.args.promptType, "confirmEx", "Should see the confirmation dialog.");
+  is(dialog.args.text, "Add \"Foo\" to the list of engines available in the search bar?\n\nFrom: example.com",
+     "Should have seen the right install message");
+  dialog.document.documentElement.cancelDialog();
+
+  gBrowser.removeCurrentTab();
+});
+
+add_task(function* test_working_addSearchEngine_src() {
+  gBrowser.selectedTab = addSearchEngine(ROOT + "testEngine.src", "", "", "");
+
+  let dialog = yield promiseDialogOpened();
+  is(dialog.args.promptType, "confirmEx", "Should see the confirmation dialog.");
+  is(dialog.args.text, "Add \"Test Sherlock\" to the list of engines available in the search bar?\n\nFrom: example.com",
+     "Should have seen the right install message");
+  dialog.document.documentElement.cancelDialog();
+
+  gBrowser.removeCurrentTab();
+});
+
+add_task(function* test_relative_addSearchEngine_xml() {
+  gBrowser.selectedTab = addSearchEngine("testEngine.xml", "", "", "");
+
+  let dialog = yield promiseDialogOpened();
+  is(dialog.args.promptType, "confirmEx", "Should see the confirmation dialog.");
+  is(dialog.args.text, "Add \"Foo\" to the list of engines available in the search bar?\n\nFrom: example.com",
+     "Should have seen the right install message");
+  dialog.document.documentElement.cancelDialog();
+
+  gBrowser.removeCurrentTab();
+});
+
+add_task(function* test_relative_addSearchEngine_src() {
+  gBrowser.selectedTab = addSearchEngine("testEngine.src", "", "", "");
+
+  let dialog = yield promiseDialogOpened();
+  is(dialog.args.promptType, "confirmEx", "Should see the confirmation dialog.");
+  is(dialog.args.text, "Add \"Test Sherlock\" to the list of engines available in the search bar?\n\nFrom: example.com",
+     "Should have seen the right install message");
+  dialog.document.documentElement.cancelDialog();
+
+  gBrowser.removeCurrentTab();
+});
+
+add_task(function* test_invalid_addSearchEngine() {
+  gBrowser.selectedTab = addSearchEngine("z://foobar", "", "", "");
+
+  let dialog = yield promiseDialogOpened();
+  is(dialog.args.promptType, "alert", "Should see the alert dialog.");
+  is(dialog.args.text, "This search engine isn't supported by Nightly and can't be installed.",
+     "Should have seen the right error message")
+  dialog.document.documentElement.acceptDialog();
+
+  gBrowser.removeCurrentTab();
+});
+
+add_task(function* test_invalid_icon_addSearchEngine() {
+  gBrowser.selectedTab = addSearchEngine(ROOT + "testEngine.src", "z://foobar", "", "");
+
+  let dialog = yield promiseDialogOpened();
+  is(dialog.args.promptType, "alert", "Should see the alert dialog.");
+  is(dialog.args.text, "This search engine isn't supported by Nightly and can't be installed.",
+     "Should have seen the right error message")
+  dialog.document.documentElement.acceptDialog();
+
+  gBrowser.removeCurrentTab();
+});
+
+add_task(function* test_missing_addSearchEngine() {
+  let url = ROOT + "foobar.xml";
+  gBrowser.selectedTab = addSearchEngine(url, "", "", "");
+
+  let dialog = yield promiseDialogOpened();
+  is(dialog.args.promptType, "alert", "Should see the alert dialog.");
+  is(dialog.args.text, "Nightly could not download the search plugin from:\n" + url,
+     "Should have seen the right error message")
+  dialog.document.documentElement.acceptDialog();
+
+  gBrowser.removeCurrentTab();
+});
new file mode 100644
--- /dev/null
+++ b/browser/components/search/test/webapi.html
@@ -0,0 +1,20 @@
+<!DOCTYPE html>
+
+<html>
+<head>
+<script>
+function installEngine() {
+  var query = window.location.search.substring(1).split(":");
+  var func = query[0];
+  var args = JSON.parse(decodeURIComponent(query[1]));
+
+  if (func == "AddSearchProvider")
+    window.external.AddSearchProvider(...args);
+  else if (func == "addSearchEngine")
+    window.sidebar.addSearchEngine(...args);
+}
+</script>
+</head>
+<body onload="installEngine()">
+</body>
+</html>
deleted file mode 100644
--- a/browser/components/sidebar/moz.build
+++ /dev/null
@@ -1,10 +0,0 @@
-# -*- Mode: python; c-basic-offset: 4; 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/.
-
-EXTRA_COMPONENTS += [
-    'nsSidebar.js',
-    'nsSidebar.manifest',
-]
deleted file mode 100644
--- a/browser/components/sidebar/nsSidebar.manifest
+++ /dev/null
@@ -1,2 +0,0 @@
-component {22117140-9c6e-11d3-aaf1-00805f8a4905} nsSidebar.js
-contract @mozilla.org/sidebar;1 {22117140-9c6e-11d3-aaf1-00805f8a4905}
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -395,16 +395,17 @@
 @RESPATH@/components/BrowserPageThumbs.manifest
 @RESPATH@/components/crashmonitor.manifest
 @RESPATH@/components/nsCrashMonitor.js
 @RESPATH@/components/SiteSpecificUserAgent.js
 @RESPATH@/components/SiteSpecificUserAgent.manifest
 @RESPATH@/components/toolkitsearch.manifest
 @RESPATH@/components/nsSearchService.js
 @RESPATH@/components/nsSearchSuggestions.js
+@RESPATH@/components/nsSidebar.js
 @RESPATH@/components/passwordmgr.manifest
 @RESPATH@/components/nsLoginInfo.js
 @RESPATH@/components/nsLoginManager.js
 @RESPATH@/components/nsLoginManagerPrompter.js
 @RESPATH@/components/storage-json.js
 @RESPATH@/components/crypto-SDR.js
 @RESPATH@/components/jsconsole-clhandler.manifest
 @RESPATH@/components/jsconsole-clhandler.js
@@ -414,18 +415,16 @@
 #ifdef MOZ_GTK
 @RESPATH@/components/nsFilePicker.manifest
 @RESPATH@/components/nsFilePicker.js
 #endif
 @RESPATH@/components/nsHelperAppDlg.manifest
 @RESPATH@/components/nsHelperAppDlg.js
 @RESPATH@/components/NetworkGeolocationProvider.manifest
 @RESPATH@/components/NetworkGeolocationProvider.js
-@RESPATH@/browser/components/nsSidebar.manifest
-@RESPATH@/browser/components/nsSidebar.js
 @RESPATH@/components/extensions.manifest
 @RESPATH@/components/addonManager.js
 @RESPATH@/components/amContentHandler.js
 @RESPATH@/components/amInstallTrigger.js
 @RESPATH@/components/amWebInstallListener.js
 @RESPATH@/components/nsBlocklistService.js
 #ifdef MOZ_UPDATER
 @RESPATH@/components/nsUpdateService.manifest
--- a/mobile/android/components/MobileComponents.manifest
+++ b/mobile/android/components/MobileComponents.manifest
@@ -25,21 +25,16 @@ contract @mozilla.org/network/protocol/a
 contract @mozilla.org/network/protocol/about;1?what=passwords {322ba47e-7047-4f71-aebf-cb7d69325cd9}
 #endif
 
 # DirectoryProvider.js
 component {ef0f7a87-c1ee-45a8-8d67-26f586e46a4b} DirectoryProvider.js
 contract @mozilla.org/browser/directory-provider;1 {ef0f7a87-c1ee-45a8-8d67-26f586e46a4b}
 category xpcom-directory-providers browser-directory-provider @mozilla.org/browser/directory-provider;1
 
-# Sidebar.js
-component {22117140-9c6e-11d3-aaf1-00805f8a4905} Sidebar.js
-contract @mozilla.org/sidebar;1 {22117140-9c6e-11d3-aaf1-00805f8a4905}
-category wakeup-request Sidebar @mozilla.org/sidebar;1,nsISidebarExternal,getService,Sidebar:AddSearchProvider
-
 # SessionStore.js
 component {8c1f07d6-cba3-4226-a315-8bd43d67d032} SessionStore.js
 contract @mozilla.org/browser/sessionstore;1 {8c1f07d6-cba3-4226-a315-8bd43d67d032}
 category app-startup SessionStore service,@mozilla.org/browser/sessionstore;1
 
 # stylesheets
 category agent-style-sheets browser-content-stylesheet chrome://browser/skin/content.css
 
deleted file mode 100644
--- a/mobile/android/components/Sidebar.js
+++ /dev/null
@@ -1,130 +0,0 @@
-/* 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 Ci = Components.interfaces;
-const Cc = Components.classes;
-const Cu = Components.utils;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-const SIDEBAR_CID = Components.ID("{22117140-9c6e-11d3-aaf1-00805f8a4905}");
-const SIDEBAR_CONTRACTID = "@mozilla.org/sidebar;1";
-
-function Sidebar() {
-  // Depending on if we are in the parent or child, prepare to remote
-  // certain calls
-  var appInfo = Cc["@mozilla.org/xre/app-info;1"];
-  if (!appInfo || appInfo.getService(Ci.nsIXULRuntime).processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) {
-    // Parent process
-
-    this.inContentProcess = false;
-
-    // Used for wakeups service. FIXME: clean up with bug 593407
-    this.wrappedJSObject = this;
-
-    // Setup listener for child messages. We don't need to call
-    // addMessageListener as the wakeup service will do that for us.
-    this.receiveMessage = function(aMessage) {
-      switch (aMessage.name) {
-        case "Sidebar:AddSearchProvider":
-          this.AddSearchProvider(aMessage.json.descriptionURL);
-      }
-    };
-  } else {
-    // Child process
-
-    this.inContentProcess = true;
-    this.messageManager = Cc["@mozilla.org/childprocessmessagemanager;1"].getService(Ci.nsISyncMessageSender);
-  }
-}
-
-Sidebar.prototype = {
-  // =========================== utility code ===========================
-  _validateSearchEngine: function validateSearchEngine(engineURL, iconURL) {
-    try {
-      // Make sure we're using HTTP, HTTPS, or FTP.
-      if (! /^(https?|ftp):\/\//i.test(engineURL))
-        throw "Unsupported search engine URL";
-    
-      // Make sure we're using HTTP, HTTPS, or FTP and refering to a
-      // .gif/.jpg/.jpeg/.png/.ico file for the icon.
-      if (iconURL &&
-          ! /^(https?|ftp):\/\/.+\.(gif|jpg|jpeg|png|ico)$/i.test(iconURL))
-        throw "Unsupported search icon URL.";
-    } catch(ex) {
-      Cu.reportError("Invalid argument passed to window.sidebar.addSearchEngine: " + ex);
-      
-      var searchBundle = Services.strings.createBundle("chrome://global/locale/search/search.properties");
-      var brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties");
-      var brandName = brandBundle.GetStringFromName("brandShortName");
-      var title = searchBundle.GetStringFromName("error_invalid_engine_title");
-      var msg = searchBundle.formatStringFromName("error_invalid_engine_msg",
-                                                  [brandName], 1);
-      Services.prompt.alert(null, title, msg);
-      return false;
-    }
-    
-    return true;
-  },
-
-  // The suggestedTitle and suggestedCategory parameters are ignored, but remain
-  // for backward compatibility.
-  addSearchEngine: function addSearchEngine(engineURL, iconURL, suggestedTitle,
-                                            suggestedCategory) {
-    if (!this._validateSearchEngine(engineURL, iconURL))
-      return;
-
-    // File extension for Sherlock search plugin description files
-    const SHERLOCK_FILE_EXT_REGEXP = /\.src$/i;
-
-    // OpenSearch files will likely be far more common than Sherlock files, and
-    // have less consistent suffixes, so we assume that ".src" is a Sherlock
-    // (text) file, and anything else is OpenSearch (XML).
-    var dataType;
-    if (SHERLOCK_FILE_EXT_REGEXP.test(engineURL))
-      dataType = Ci.nsISearchEngine.DATA_TEXT;
-    else
-      dataType = Ci.nsISearchEngine.DATA_XML;
-
-    Services.search.addEngine(engineURL, dataType, iconURL, true);
-  },
-
-  // This function exists to implement window.external.AddSearchProvider(),
-  // to match other browsers' APIs.  The capitalization, although nonstandard here,
-  // is therefore important.
-  AddSearchProvider: function AddSearchProvider(aDescriptionURL) {
-    if (!this._validateSearchEngine(aDescriptionURL, ""))
-      return;
-
-    if (this.inContentProcess) {
-      this.messageManager.sendAsyncMessage("Sidebar:AddSearchProvider",
-        { descriptionURL: aDescriptionURL });
-      return;
-    }
-
-    const typeXML = Ci.nsISearchEngine.DATA_XML;
-    Services.search.addEngine(aDescriptionURL, typeXML, "", true);
-  },
-
-  // This function exists to implement window.external.IsSearchProviderInstalled(),
-  // for compatibility with other browsers.  It will return an integer value
-  // indicating whether the given engine is installed for the current user.
-  // However, it is currently stubbed out due to security/privacy concerns
-  // stemming from difficulties in determining what domain issued the request.
-  // See bug 340604 and
-  // http://msdn.microsoft.com/en-us/library/aa342526%28VS.85%29.aspx .
-  // XXX Implement this!
-  IsSearchProviderInstalled: function IsSearchProviderInstalled(aSearchURL) {
-    return 0;
-  },
-
-  // =========================== nsISupports ===========================
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports]),
-
-  // XPCOMUtils stuff
-  classID: SIDEBAR_CID,
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([Sidebar]);
--- a/mobile/android/components/moz.build
+++ b/mobile/android/components/moz.build
@@ -21,17 +21,16 @@ EXTRA_COMPONENTS += [
     'ContentPermissionPrompt.js',
     'DirectoryProvider.js',
     'FilePicker.js',
     'HelperAppDialog.js',
     'LoginManagerPrompter.js',
     'NSSDialogService.js',
     'PromptService.js',
     'SessionStore.js',
-    'Sidebar.js',
     'SiteSpecificUserAgent.js',
     'Snippets.js',
     'TabSource.js',
     'WebappsUpdateTimer.js',
     'XPIDialogService.js',
 ]
 
 if CONFIG['MOZ_PAY']:
--- a/toolkit/components/processsingleton/MainProcessSingleton.js
+++ b/toolkit/components/processsingleton/MainProcessSingleton.js
@@ -1,53 +1,102 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 "use strict";
 
-const Cu = Components.utils;
-const Ci = Components.interfaces;
-const Cc = Components.classes;
+const { utils: Cu, interfaces: Ci, classes: Cc, results: Cr } = Components;
 
 Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 
 XPCOMUtils.defineLazyServiceGetter(this, "ppmm",
                                    "@mozilla.org/parentprocessmessagemanager;1",
                                    "nsIMessageListenerManager");
 
 XPCOMUtils.defineLazyServiceGetter(this, "globalmm",
                                    "@mozilla.org/globalmessagemanager;1",
                                    "nsIMessageBroadcaster");
 
+XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
+                                  "resource://gre/modules/NetUtil.jsm");
+
 function MainProcessSingleton() {}
 MainProcessSingleton.prototype = {
   classID: Components.ID("{0636a680-45cb-11e4-916c-0800200c9a66}"),
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
                                          Ci.nsISupportsWeakReference]),
 
-  receiveMessage: function(message) {
+  logConsoleMessage: function(message) {
     let logMsg = message.data;
     logMsg.wrappedJSObject = logMsg;
     Services.obs.notifyObservers(logMsg, "console-api-log-event", null);
   },
 
+  // Called when a webpage calls either window.external.AddSearchProvider or
+  // window.sidebar.addSearchEngine
+  addSearchEngine: function({ target: browser, data: { pageURL, engineURL, iconURL, type } }) {
+    pageURL = NetUtil.newURI(pageURL);
+    engineURL = NetUtil.newURI(engineURL, null, pageURL);
+
+    if (iconURL) {
+      iconURL = NetUtil.newURI(iconURL, null, pageURL);
+    }
+    else {
+      let tabbrowser = browser.getTabBrowser();
+      if (browser.mIconURL && (!tabbrowser || tabbrowser.shouldLoadFavIcon(pageURL)))
+        iconURL = NetUtil.newURI(browser.mIconURL);
+    }
+
+    try {
+      // Make sure the URLs are HTTP, HTTPS, or FTP.
+      let isWeb = ["https", "http", "ftp"];
+
+      if (isWeb.indexOf(engineURL.scheme) < 0)
+        throw "Unsupported search engine URL: " + engineURL;
+
+      if (iconURL && isWeb.indexOf(iconURL.scheme) < 0)
+        throw "Unsupported search icon URL: " + iconURL;
+    }
+    catch(ex) {
+      Cu.reportError("Invalid argument passed to window.sidebar.addSearchEngine: " + ex);
+
+      var searchBundle = Services.strings.createBundle("chrome://global/locale/search/search.properties");
+      var brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties");
+      var brandName = brandBundle.GetStringFromName("brandShortName");
+      var title = searchBundle.GetStringFromName("error_invalid_engine_title");
+      var msg = searchBundle.formatStringFromName("error_invalid_engine_msg",
+                                                  [brandName], 1);
+      Services.ww.getNewPrompter(browser.ownerDocument.defaultView).alert(title, msg);
+      return;
+    }
+
+    Services.search.init(function(status) {
+      if (status != Cr.NS_OK)
+        return;
+
+      Services.search.addEngine(engineURL.spec, type, iconURL ? iconURL.spec : null, true);
+    })
+  },
+
   observe: function(subject, topic, data) {
     switch (topic) {
     case "app-startup": {
       Services.obs.addObserver(this, "xpcom-shutdown", false);
 
       // Load this script early so that console.* is initialized
       // before other frame scripts.
       globalmm.loadFrameScript("chrome://global/content/browser-content.js", true);
-      ppmm.addMessageListener("Console:Log", this);
+      ppmm.addMessageListener("Console:Log", this.logConsoleMessage);
+      globalmm.addMessageListener("Search:AddEngine", this.addSearchEngine);
       break;
     }
 
     case "xpcom-shutdown":
-      ppmm.removeMessageListener("Console:Log", this);
+      ppmm.removeMessageListener("Console:Log", this.logConsoleMessage);
+      globalmm.removeMessageListener("Search:AddEngine", this.addSearchEngine);
       break;
     }
   },
 };
 
 this.NSGetFactory = XPCOMUtils.generateNSGetFactory([MainProcessSingleton]);
--- a/toolkit/components/search/moz.build
+++ b/toolkit/components/search/moz.build
@@ -3,16 +3,17 @@
 # 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/.
 
 XPCSHELL_TESTS_MANIFESTS += ['tests/xpcshell/xpcshell.ini']
 
 EXTRA_COMPONENTS += [
     'nsSearchSuggestions.js',
+    'nsSidebar.js',
     'toolkitsearch.manifest',
 ]
 
 EXTRA_JS_MODULES += [
     'SearchSuggestionController.jsm',
 ]
 
 EXTRA_PP_COMPONENTS += [
rename from browser/components/sidebar/nsSidebar.js
rename to toolkit/components/search/nsSidebar.js
--- a/browser/components/sidebar/nsSidebar.js
+++ b/toolkit/components/search/nsSidebar.js
@@ -1,127 +1,63 @@
 /* -*- indent-tabs-mode: nil; js-indent-level: 4 -*- */
 /* 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/. */
 
-Components.utils.import("resource://gre/modules/Services.jsm");
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
+const { interfaces: Ci, utils: Cu } = Components;
 
-const DEBUG = false; /* set to false to suppress debug messages */
-
-const SIDEBAR_CONTRACTID        = "@mozilla.org/sidebar;1";
-const SIDEBAR_CID               = Components.ID("{22117140-9c6e-11d3-aaf1-00805f8a4905}");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 
 // File extension for Sherlock search plugin description files
 const SHERLOCK_FILE_EXT_REGEXP = /\.src$/i;
 
-function nsSidebar()
-{
-}
-
-nsSidebar.prototype.classID = SIDEBAR_CID;
-
-nsSidebar.prototype.validateSearchEngine =
-function (engineURL, iconURL)
-{
-  try
-  {
-    // Make sure the URLs are HTTP, HTTPS, or FTP.
-    var isWeb = /^(https?|ftp):\/\//i;
-
-    if (!isWeb.test(engineURL))
-      throw "Unsupported search engine URL";
-
-    if (iconURL && !isWeb.test(iconURL))
-      throw "Unsupported search icon URL.";
-  }
-  catch(ex)
-  {
-    debug(ex);
-    Components.utils.reportError("Invalid argument passed to window.sidebar.addSearchEngine: " + ex);
-
-    var searchBundle = Services.strings.createBundle("chrome://global/locale/search/search.properties");
-    var brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties");
-    var brandName = brandBundle.GetStringFromName("brandShortName");
-    var title = searchBundle.GetStringFromName("error_invalid_engine_title");
-    var msg = searchBundle.formatStringFromName("error_invalid_engine_msg",
-                                                [brandName], 1);
-    Services.ww.getNewPrompter(null).alert(title, msg);
-    return false;
-  }
-
-  return true;
+function nsSidebar() {
 }
 
-// The suggestedTitle and suggestedCategory parameters are ignored, but remain
-// for backward compatibility.
-nsSidebar.prototype.addSearchEngine =
-function (engineURL, iconURL, suggestedTitle, suggestedCategory)
-{
-  debug("addSearchEngine(" + engineURL + ", " + iconURL + ", " +
-        suggestedCategory + ", " + suggestedTitle + ")");
+nsSidebar.prototype = {
+  init: function(window) {
+    this.window = window;
+    this.mm = window.QueryInterface(Ci.nsIInterfaceRequestor)
+                    .getInterface(Ci.nsIDocShell)
+                    .QueryInterface(Ci.nsIInterfaceRequestor)
+                    .getInterface(Ci.nsIContentFrameMessageManager);
+  },
 
-  if (!this.validateSearchEngine(engineURL, iconURL))
-    return;
+  // The suggestedTitle and suggestedCategory parameters are ignored, but remain
+  // for backward compatibility.
+  addSearchEngine: function(engineURL, iconURL, suggestedTitle, suggestedCategory) {
+    let dataType = SHERLOCK_FILE_EXT_REGEXP.test(engineURL) ?
+                   Ci.nsISearchEngine.DATA_TEXT :
+                   Ci.nsISearchEngine.DATA_XML;
 
-  // OpenSearch files will likely be far more common than Sherlock files, and
-  // have less consistent suffixes, so we assume that ".src" is a Sherlock
-  // (text) file, and anything else is OpenSearch (XML).
-  var dataType;
-  if (SHERLOCK_FILE_EXT_REGEXP.test(engineURL))
-    dataType = Components.interfaces.nsISearchEngine.DATA_TEXT;
-  else
-    dataType = Components.interfaces.nsISearchEngine.DATA_XML;
+    this.mm.sendAsyncMessage("Search:AddEngine", {
+      pageURL: this.window.document.documentURIObject.spec,
+      engineURL,
+      type: dataType,
+      iconURL
+    });
+  },
 
-  Services.search.addEngine(engineURL, dataType, iconURL, true);
+  // This function exists largely to implement window.external.AddSearchProvider(),
+  // to match other browsers' APIs.  The capitalization, although nonstandard here,
+  // is therefore important.
+  AddSearchProvider: function(engineURL) {
+    this.mm.sendAsyncMessage("Search:AddEngine", {
+      pageURL: this.window.document.documentURIObject.spec,
+      engineURL,
+      type: Ci.nsISearchEngine.DATA_XML
+    });
+  },
+
+  // This function exists to implement window.external.IsSearchProviderInstalled(),
+  // for compatibility with other browsers.  The function has been deprecated
+  // and so will not be implemented.
+  IsSearchProviderInstalled: function(engineURL) {
+    return 0;
+  },
+
+  classID: Components.ID("{22117140-9c6e-11d3-aaf1-00805f8a4905}"),
+  QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports,
+                                         Ci.nsIDOMGlobalPropertyInitializer])
 }
 
-// This function exists largely to implement window.external.AddSearchProvider(),
-// to match other browsers' APIs.  The capitalization, although nonstandard here,
-// is therefore important.
-nsSidebar.prototype.AddSearchProvider =
-function (aDescriptionURL)
-{
-  // Get the favicon URL for the current page, or our best guess at the current
-  // page since we don't have easy access to the active document.  Most search
-  // engines will override this with an icon specified in the OpenSearch
-  // description anyway.
-  var win = Services.wm.getMostRecentWindow("navigator:browser");
-  var browser = win.gBrowser;
-  var iconURL = "";
-  // Use documentURIObject in the check for shouldLoadFavIcon so that we
-  // do the right thing with about:-style error pages.  Bug 453442
-  if (browser.shouldLoadFavIcon(browser.selectedBrowser
-                                       .contentDocument
-                                       .documentURIObject))
-    iconURL = browser.getIcon();
-
-  if (!this.validateSearchEngine(aDescriptionURL, iconURL))
-    return;
-
-  const typeXML = Components.interfaces.nsISearchEngine.DATA_XML;
-  Services.search.addEngine(aDescriptionURL, typeXML, iconURL, true);
-}
-
-// This function exists to implement window.external.IsSearchProviderInstalled(),
-// for compatibility with other browsers.  It will return an integer value
-// indicating whether the given engine is installed for the current user.
-// However, it is currently stubbed out due to security/privacy concerns
-// stemming from difficulties in determining what domain issued the request.
-// See bug 340604 and
-// http://msdn.microsoft.com/en-us/library/aa342526%28VS.85%29.aspx .
-// XXX Implement this!
-nsSidebar.prototype.IsSearchProviderInstalled =
-function (aSearchURL)
-{
-  return 0;
-}
-
-nsSidebar.prototype.QueryInterface = XPCOMUtils.generateQI([Components.interfaces.nsISupports]);
-
 this.NSGetFactory = XPCOMUtils.generateNSGetFactory([nsSidebar]);
-
-/* static functions */
-if (DEBUG)
-    debug = function (s) { dump("-*- sidebar component: " + s + "\n"); }
-else
-    debug = function (s) {}
--- a/toolkit/components/search/toolkitsearch.manifest
+++ b/toolkit/components/search/toolkitsearch.manifest
@@ -1,6 +1,8 @@
 component {7319788a-fe93-4db3-9f39-818cf08f4256} nsSearchService.js process=main
 contract @mozilla.org/browser/search-service;1 {7319788a-fe93-4db3-9f39-818cf08f4256} process=main
 # 21600 == 6 hours
 category update-timer nsSearchService @mozilla.org/browser/search-service;1,getService,search-engine-update-timer,browser.search.update.interval,21600
 component {aa892eb4-ffbf-477d-9f9a-06c995ae9f27} nsSearchSuggestions.js
 contract @mozilla.org/autocomplete/search;1?name=search-autocomplete {aa892eb4-ffbf-477d-9f9a-06c995ae9f27}
+component {22117140-9c6e-11d3-aaf1-00805f8a4905} nsSidebar.js
+contract @mozilla.org/sidebar;1 {22117140-9c6e-11d3-aaf1-00805f8a4905}