Backed out 6 changesets (bug 1504756) for wpt failures on webdriver/tests/execute_script/promise.py
authorCosmin Sabou <csabou@mozilla.com>
Wed, 05 Dec 2018 08:33:46 +0200
changeset 508592 49bd1dd914a4a9d8c8b546dc503b6ae715d6e98c
parent 508591 38b4e8f428f7f41feca673ee8833733f27a37460
child 508593 f1f136ea674c759c22ad7c13b547ca08bd25b147
push id1905
push userffxbld-merge
push dateMon, 21 Jan 2019 12:33:13 +0000
treeherdermozilla-release@c2fca1944d8c [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
bugs1504756
milestone65.0a1
backs outd808b528532ac7ccb48bbcb7447f194a822381e5
30d345cce5be1236aed9380e7c4d121a99800d70
a8ea6d01fbe1de92009842a4028c9179646a88f5
ba627a1b61dcebdd2cde178567fd800e0cbe8208
c90e4b2e1b2848756daa201bd2d667c3557edadb
04da1f01afba4940e1fa94585e046c7d1103ddd6
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
Backed out 6 changesets (bug 1504756) for wpt failures on webdriver/tests/execute_script/promise.py Backed out changeset d808b528532a (bug 1504756) Backed out changeset 30d345cce5be (bug 1504756) Backed out changeset a8ea6d01fbe1 (bug 1504756) Backed out changeset ba627a1b61dc (bug 1504756) Backed out changeset c90e4b2e1b28 (bug 1504756) Backed out changeset 04da1f01afba (bug 1504756)
testing/marionette/browser.js
testing/marionette/client/marionette_driver/marionette.py
testing/marionette/doc/internals/sync.rst
testing/marionette/driver.js
testing/marionette/harness/marionette_harness/runner/mixins/window_manager.py
testing/marionette/harness/marionette_harness/tests/unit/test_chrome.py
testing/marionette/harness/marionette_harness/tests/unit/test_click.py
testing/marionette/harness/marionette_harness/tests/unit/test_key_actions.py
testing/marionette/harness/marionette_harness/tests/unit/test_navigation.py
testing/marionette/harness/marionette_harness/tests/unit/test_screenshot.py
testing/marionette/harness/marionette_harness/tests/unit/test_switch_window_chrome.py
testing/marionette/harness/marionette_harness/tests/unit/test_switch_window_content.py
testing/marionette/harness/marionette_harness/tests/unit/test_window_close_chrome.py
testing/marionette/harness/marionette_harness/tests/unit/test_window_close_content.py
testing/marionette/harness/marionette_harness/tests/unit/test_window_handles_chrome.py
testing/marionette/harness/marionette_harness/tests/unit/test_window_handles_content.py
testing/marionette/harness/marionette_harness/tests/unit/test_window_management.py
testing/marionette/harness/marionette_harness/tests/unit/test_window_status_content.py
testing/marionette/proxy.js
testing/marionette/server.js
testing/marionette/sync.js
testing/marionette/test/unit/test_sync.js
testing/marionette/transport.js
--- a/testing/marionette/browser.js
+++ b/testing/marionette/browser.js
@@ -7,18 +7,17 @@
 
 const {WebElementEventTarget} = ChromeUtils.import("chrome://marionette/content/dom.js", {});
 ChromeUtils.import("chrome://marionette/content/element.js");
 const {
   NoSuchWindowError,
   UnsupportedOperationError,
 } = ChromeUtils.import("chrome://marionette/content/error.js", {});
 const {
-  waitForEvent,
-  waitForObserverTopic,
+  MessageManagerDestroyedPromise,
 } = ChromeUtils.import("chrome://marionette/content/sync.js", {});
 
 this.EXPORTED_SYMBOLS = ["browser", "Context", "WindowState"];
 
 /** @namespace */
 this.browser = {};
 
 const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
@@ -66,21 +65,21 @@ this.Context = Context;
  * @param {Tab} tab
  *     The tab whose browser needs to be returned.
  *
  * @return {Browser}
  *     The linked browser for the tab or null if no browser can be found.
  */
 browser.getBrowserForTab = function(tab) {
   // Fennec
-  if (tab && "browser" in tab) {
+  if ("browser" in tab) {
     return tab.browser;
 
   // Firefox
-  } else if (tab && "linkedBrowser" in tab) {
+  } else if ("linkedBrowser" in tab) {
     return tab.linkedBrowser;
   }
 
   return null;
 };
 
 /**
  * Return the tab browser for the specified chrome window.
@@ -283,69 +282,27 @@ browser.Context = class {
 
   /**
    * Close the current window.
    *
    * @return {Promise}
    *     A promise which is resolved when the current window has been closed.
    */
   closeWindow() {
-    // Create a copy of the messageManager before it is disconnected
-    let messageManager = this.window.messageManager;
-    let disconnected = waitForObserverTopic("message-manager-disconnect",
-        subject => subject === messageManager);
-    let unloaded = waitForEvent(this.window, "unload");
-
-    this.window.close();
-
-    return Promise.all([disconnected, unloaded]);
-  }
-
-  /**
-   * Open a new browser window.
-   *
-   * @return {Promise}
-   *     A promise resolving to the newly created chrome window.
-   */
-  async openBrowserWindow(focus = false) {
-    switch (this.driver.appName) {
-      case "firefox":
-        // Open new browser window, and wait until it is fully loaded.
-        // Also wait for the window to be focused and activated to prevent a
-        // race condition when promptly focusing to the original window again.
-        let win = this.window.OpenBrowserWindow();
+    return new Promise(resolve => {
+      // Wait for the window message manager to be destroyed
+      let destroyed = new MessageManagerDestroyedPromise(
+          this.window.messageManager);
 
-        // Bug 1509380 - Missing focus/activate event when Firefox is not
-        // the top-most application. As such wait for the next tick, and
-        // manually focus the newly opened window.
-        win.setTimeout(() => win.focus(), 0);
-
-        let activated = waitForEvent(win, "activate");
-        let focused = waitForEvent(win, "focus", {capture: true});
-        let startup = waitForObserverTopic("browser-delayed-startup-finished",
-            subject => subject == win);
-        await Promise.all([activated, focused, startup]);
-
-        if (!focus) {
-          // The new window shouldn't get focused. As such set the
-          // focus back to the currently selected window.
-          activated = waitForEvent(this.window, "activate");
-          focused = waitForEvent(this.window, "focus", {capture: true});
-
-          this.window.focus();
-
-          await Promise.all([activated, focused]);
-        }
-
-        return win;
-
-      default:
-        throw new UnsupportedOperationError(
-            `openWindow() not supported in ${this.driver.appName}`);
-    }
+      this.window.addEventListener("unload", async () => {
+        await destroyed;
+        resolve();
+      }, {once: true});
+      this.window.close();
+    });
   }
 
   /**
    * Close the current tab.
    *
    * @return {Promise}
    *     A promise which is resolved when the current tab has been closed.
    *
@@ -357,75 +314,50 @@ browser.Context = class {
     // same if only one remaining tab is open, or no tab selected at all.
     if (!this.tabBrowser ||
         !this.tabBrowser.tabs ||
         this.tabBrowser.tabs.length === 1 ||
         !this.tab) {
       return this.closeWindow();
     }
 
-    // Create a copy of the messageManager before it is disconnected
-    let messageManager = this.messageManager;
-    let disconnected = waitForObserverTopic("message-manager-disconnect",
-        subject => subject === messageManager);
+    return new Promise((resolve, reject) => {
+      // Wait for the browser message manager to be destroyed
+      let browserDetached = async () => {
+        await new MessageManagerDestroyedPromise(this.messageManager);
+        resolve();
+      };
 
-    let tabClosed;
-
-    switch (this.driver.appName) {
-      case "fennec":
+      if (this.tabBrowser.closeTab) {
         // Fennec
-        tabClosed = waitForEvent(this.tabBrowser.deck, "TabClose");
+        this.tabBrowser.deck.addEventListener(
+            "TabClose", browserDetached, {once: true});
         this.tabBrowser.closeTab(this.tab);
-        break;
-
-      case "firefox":
-        tabClosed = waitForEvent(this.tab, "TabClose");
-        this.tabBrowser.removeTab(this.tab);
-        break;
 
-      default:
-        throw new UnsupportedOperationError(
-          `closeTab() not supported in ${this.driver.appName}`);
-    }
+      } else if (this.tabBrowser.removeTab) {
+        // Firefox
+        this.tab.addEventListener(
+            "TabClose", browserDetached, {once: true});
+        this.tabBrowser.removeTab(this.tab);
 
-    return Promise.all([disconnected, tabClosed]);
+      } else {
+        reject(new UnsupportedOperationError(
+            `closeTab() not supported in ${this.driver.appName}`));
+      }
+    });
   }
 
   /**
-   * Open a new tab in the currently selected chrome window.
+   * Opens a tab with given URI.
+   *
+   * @param {string} uri
+   *      URI to open.
    */
-  async openTab(focus = false) {
-    let tab = null;
-    let tabOpened = waitForEvent(this.window, "TabOpen");
-
-    switch (this.driver.appName) {
-      case "fennec":
-        tab = this.tabBrowser.addTab(null, {selected: focus});
-        break;
-
-      case "firefox":
-        this.window.BrowserOpenTab();
-        tab = this.tabBrowser.selectedTab;
-
-        // The new tab is always selected by default. If focus is not wanted,
-        // the previously tab needs to be selected again.
-        if (!focus) {
-          this.tabBrowser.selectedTab = this.tab;
-        }
-
-        break;
-
-      default:
-        throw new UnsupportedOperationError(
-          `openTab() not supported in ${this.driver.appName}`);
-    }
-
-    await tabOpened;
-
-    return tab;
+  addTab(uri) {
+    return this.tabBrowser.addTab(uri, true);
   }
 
   /**
    * Set the current tab.
    *
    * @param {number=} index
    *     Tab index to switch to. If the parameter is undefined,
    *     the currently selected tab will be used.
@@ -449,28 +381,26 @@ browser.Context = class {
     }
 
     if (typeof index == "undefined") {
       this.tab = this.tabBrowser.selectedTab;
     } else {
       this.tab = this.tabBrowser.tabs[index];
 
       if (focus) {
-        switch (this.driver.appName) {
-          case "fennec":
-            this.tabBrowser.selectTab(this.tab);
-            break;
+        if (this.tabBrowser.selectTab) {
+          // Fennec
+          this.tabBrowser.selectTab(this.tab);
 
-          case "firefox":
-            this.tabBrowser.selectedTab = this.tab;
-            break;
+        } else if ("selectedTab" in this.tabBrowser) {
+          // Firefox
+          this.tabBrowser.selectedTab = this.tab;
 
-          default:
-            throw new UnsupportedOperationError(
-              `switchToTab() not supported in ${this.driver.appName}`);
+        } else {
+          throw new UnsupportedOperationError("switchToTab() not supported");
         }
       }
     }
 
     // TODO(ato): Currently tied to curBrowser, but should be moved to
     // WebElement when introduced by https://bugzil.la/1400256.
     this.eventObserver = new WebElementEventTarget(this.messageManager);
   }
--- a/testing/marionette/client/marionette_driver/marionette.py
+++ b/testing/marionette/client/marionette_driver/marionette.py
@@ -1423,30 +1423,16 @@ class Marionette(object):
         return self._send_message("WebDriver:GetChromeWindowHandles")
 
     @property
     def page_source(self):
         """A string representation of the DOM."""
         return self._send_message("WebDriver:GetPageSource",
                                   key="value")
 
-    def open(self, type=None, focus=False):
-        """Open a new window, or tab based on the specified context type.
-
-        If no context type is given the application will choose the best
-        option based on tab and window support.
-
-        :param type: Type of window to be opened. Can be one of "tab" or "window"
-        :param focus: If true, the opened window will be focused
-
-        :returns: Dict with new window handle, and type of opened window
-        """
-        body = {"type": type, "focus": focus}
-        return self._send_message("WebDriver:NewWindow", body)
-
     def close(self):
         """Close the current window, ending the session if it's the last
         window currently open.
 
         :returns: Unordered list of remaining unique window handles as strings
         """
         return self._send_message("WebDriver:CloseWindow")
 
--- a/testing/marionette/doc/internals/sync.rst
+++ b/testing/marionette/doc/internals/sync.rst
@@ -1,21 +1,16 @@
 sync module
 ===========
 
 Provides an assortment of synchronisation primitives.
 
-.. js:autofunction:: executeSoon
+.. js:autoclass:: MessageManagerDestroyedPromise
+  :members:
 
 .. js:autoclass:: PollPromise
   :members:
 
 .. js:autoclass:: Sleep
   :members:
 
 .. js:autoclass:: TimedPromise
   :members:
-
-.. js:autofunction:: waitForEvent
-
-.. js:autofunction:: waitForMessage
-
-.. js:autofunction:: waitForObserverTopic
--- a/testing/marionette/driver.js
+++ b/testing/marionette/driver.js
@@ -57,18 +57,16 @@ ChromeUtils.import("chrome://marionette/
 const {MarionettePrefs} = ChromeUtils.import("chrome://marionette/content/prefs.js", {});
 ChromeUtils.import("chrome://marionette/content/proxy.js");
 ChromeUtils.import("chrome://marionette/content/reftest.js");
 const {
   DebounceCallback,
   IdlePromise,
   PollPromise,
   TimedPromise,
-  waitForEvent,
-  waitForObserverTopic,
 } = ChromeUtils.import("chrome://marionette/content/sync.js", {});
 
 XPCOMUtils.defineLazyGetter(this, "logger", Log.get);
 XPCOMUtils.defineLazyGlobalGetters(this, ["URL"]);
 
 this.EXPORTED_SYMBOLS = ["GeckoDriver"];
 
 const APP_ID_FIREFOX = "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}";
@@ -103,22 +101,23 @@ const globalMessageManager = Services.mm
  * browsing context's content frame message listener via ListenerProxy.
  *
  * Throughout this prototype, functions with the argument <var>cmd</var>'s
  * documentation refers to the contents of the <code>cmd.parameter</code>
  * object.
  *
  * @class GeckoDriver
  *
+ * @param {string} appId
+ *     Unique identifier of the application.
  * @param {MarionetteServer} server
  *     The instance of Marionette server.
  */
-this.GeckoDriver = function(server) {
-  this.appId = Services.appinfo.ID;
-  this.appName = Services.appinfo.name.toLowerCase();
+this.GeckoDriver = function(appId, server) {
+  this.appId = appId;
   this._server = server;
 
   this.sessionID = null;
   this.wins = new browser.Windows();
   this.browsers = {};
   // points to current browser
   this.curBrowser = null;
   // top-most chrome window
@@ -1303,17 +1302,16 @@ GeckoDriver.prototype.updateIdForBrowser
  * Retrieves a listener id for the given xul browser element. In case
  * the browser is not known, an attempt is made to retrieve the id from
  * a CPOW, and null is returned if this fails.
  */
 GeckoDriver.prototype.getIdForBrowser = function(browser) {
   if (browser === null) {
     return null;
   }
-
   let permKey = browser.permanentKey;
   if (this._browserIds.has(permKey)) {
     return this._browserIds.get(permKey);
   }
 
   let winId = browser.outerWindowID;
   if (winId) {
     this._browserIds.set(permKey, winId);
@@ -2720,83 +2718,16 @@ GeckoDriver.prototype.deleteCookie = asy
   for (let c of cookie.iter(hostname, pathname)) {
     if (c.name === name) {
       cookie.remove(c);
     }
   }
 };
 
 /**
- * Open a new top-level browsing context.
- *
- * @param {string=} type
- *     Optional type of the new top-level browsing context. Can be one of
- *     `tab` or `window`.
- * @param {boolean=} focus
- *     Optional flag if the new top-level browsing context should be opened
- *     in foreground (focused) or background (not focused).
- *
- * @return {Object.<string, string>}
- *     Handle and type of the new browsing context.
- */
-GeckoDriver.prototype.newWindow = async function(cmd) {
-  assert.open(this.getCurrentWindow(Context.Content));
-  await this._handleUserPrompts();
-
-  let focus = false;
-  if (typeof cmd.parameters.focus != "undefined") {
-    focus = assert.boolean(cmd.parameters.focus,
-        pprint`Expected "focus" to be a boolean, got ${cmd.parameters.focus}`);
-  }
-
-  let type;
-  if (typeof cmd.parameters.type != "undefined") {
-    type = assert.string(cmd.parameters.type,
-        pprint`Expected "type" to be a string, got ${cmd.parameters.type}`);
-  }
-
-  let types = ["tab", "window"];
-  switch (this.appName) {
-    case "firefox":
-      if (typeof type == "undefined" || !types.includes(type)) {
-        type = "window";
-      }
-      break;
-    case "fennec":
-      if (typeof type == "undefined" || !types.includes(type)) {
-        type = "tab";
-      }
-      break;
-  }
-
-  let contentBrowser;
-
-  switch (type) {
-    case "tab":
-      let tab = await this.curBrowser.openTab(focus);
-      contentBrowser = browser.getBrowserForTab(tab);
-      break;
-
-    default:
-      let win = await this.curBrowser.openBrowserWindow(focus);
-      contentBrowser = browser.getTabBrowser(win).selectedBrowser;
-  }
-
-  // Even with the framescript registered, the browser might not be known to
-  // the parent process yet. Wait until it is available.
-  // TODO: Fix by using `Browser:Init` or equivalent on bug 1311041
-  let windowId = await new PollPromise((resolve, reject) => {
-    let id = this.getIdForBrowser(contentBrowser);
-    this.windowHandles.includes(id) ? resolve(id) : reject();
-  });
-
-  return {"handle": windowId.toString(), type};
-};
-
-/**
  * Close the currently selected tab/window.
  *
  * With multiple open tabs present the currently selected tab will
  * be closed.  Otherwise the window itself will be closed. If it is the
  * last window currently open, the window will not be closed to prevent
  * a shutdown of the application. Instead the returned list of window
  * handles is empty.
  *
@@ -3165,42 +3096,46 @@ GeckoDriver.prototype.fullscreenWindow =
 /**
  * Dismisses a currently displayed tab modal, or returns no such alert if
  * no modal is displayed.
  */
 GeckoDriver.prototype.dismissDialog = async function() {
   let win = assert.open(this.getCurrentWindow());
   this._checkIfAlertIsPresent();
 
-  let dialogClosed = waitForEvent(win, "DOMModalDialogClosed");
-
-  let {button0, button1} = this.dialog.ui;
-  (button1 ? button1 : button0).click();
-
-  await dialogClosed;
-
-  this.dialog = null;
+  await new Promise(resolve => {
+    win.addEventListener("DOMModalDialogClosed", async () => {
+      await new IdlePromise(win);
+      this.dialog = null;
+      resolve();
+    }, {once: true});
+
+    let {button0, button1} = this.dialog.ui;
+    (button1 ? button1 : button0).click();
+  });
 };
 
 /**
  * Accepts a currently displayed tab modal, or returns no such alert if
  * no modal is displayed.
  */
 GeckoDriver.prototype.acceptDialog = async function() {
   let win = assert.open(this.getCurrentWindow());
   this._checkIfAlertIsPresent();
 
-  let dialogClosed = waitForEvent(win, "DOMModalDialogClosed");
-
-  let {button0} = this.dialog.ui;
-  button0.click();
-
-  await dialogClosed;
-
-  this.dialog = null;
+  await new Promise(resolve => {
+    win.addEventListener("DOMModalDialogClosed", async () => {
+      await new IdlePromise(win);
+      this.dialog = null;
+      resolve();
+    }, {once: true});
+
+    let {button0} = this.dialog.ui;
+    button0.click();
+  });
 };
 
 /**
  * Returns the message shown in a currently displayed modal, or returns
  * a no such alert error if no modal is currently displayed.
  */
 GeckoDriver.prototype.getTextFromDialog = function() {
   assert.open(this.getCurrentWindow());
@@ -3361,20 +3296,25 @@ GeckoDriver.prototype.quit = async funct
   } else {
     mode = Ci.nsIAppStartup.eAttemptQuit;
   }
 
   this._server.acceptConnections = false;
   this.deleteSession();
 
   // delay response until the application is about to quit
-  let quitApplication = waitForObserverTopic("quit-application");
+  let quitApplication = new Promise(resolve => {
+    Services.obs.addObserver(
+        (subject, topic, data) => resolve(data),
+        "quit-application");
+  });
+
   Services.startup.quit(mode);
 
-  return {cause: (await quitApplication).data};
+  return {cause: await quitApplication};
 };
 
 GeckoDriver.prototype.installAddon = function(cmd) {
   assert.desktop();
 
   let path = cmd.parameters.path;
   let temp = cmd.parameters.temporary || false;
   if (typeof path == "undefined" || typeof path != "string" ||
@@ -3626,17 +3566,16 @@ GeckoDriver.prototype.commands = {
   "WebDriver:GetWindowRect": GeckoDriver.prototype.getWindowRect,
   "WebDriver:IsElementDisplayed": GeckoDriver.prototype.isElementDisplayed,
   "WebDriver:IsElementEnabled": GeckoDriver.prototype.isElementEnabled,
   "WebDriver:IsElementSelected": GeckoDriver.prototype.isElementSelected,
   "WebDriver:MinimizeWindow": GeckoDriver.prototype.minimizeWindow,
   "WebDriver:MaximizeWindow": GeckoDriver.prototype.maximizeWindow,
   "WebDriver:Navigate": GeckoDriver.prototype.get,
   "WebDriver:NewSession": GeckoDriver.prototype.newSession,
-  "WebDriver:NewWindow": GeckoDriver.prototype.newWindow,
   "WebDriver:PerformActions": GeckoDriver.prototype.performActions,
   "WebDriver:Refresh":  GeckoDriver.prototype.refresh,
   "WebDriver:ReleaseActions": GeckoDriver.prototype.releaseActions,
   "WebDriver:SendAlertText": GeckoDriver.prototype.sendKeysToDialog,
   "WebDriver:SetTimeouts": GeckoDriver.prototype.setTimeouts,
   "WebDriver:SetWindowRect": GeckoDriver.prototype.setWindowRect,
   "WebDriver:SwitchToFrame": GeckoDriver.prototype.switchToFrame,
   "WebDriver:SwitchToParentFrame": GeckoDriver.prototype.switchToParentFrame,
--- a/testing/marionette/harness/marionette_harness/runner/mixins/window_manager.py
+++ b/testing/marionette/harness/marionette_harness/runner/mixins/window_manager.py
@@ -1,22 +1,24 @@
 # 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/.
 
 from __future__ import absolute_import
 
 import sys
 
-from marionette_driver import Wait
+from marionette_driver import By, Wait
 from six import reraise
 
 
 class WindowManagerMixin(object):
 
+    _menu_item_new_tab = (By.ID, "menu_newNavigatorTab")
+
     def setUp(self):
         super(WindowManagerMixin, self).setUp()
 
         self.start_window = self.marionette.current_chrome_window_handle
         self.start_windows = self.marionette.chrome_window_handles
 
         self.start_tab = self.marionette.current_window_handle
         self.start_tabs = self.marionette.window_handles
@@ -53,89 +55,75 @@ class WindowManagerMixin(object):
         current_chrome_window_handles.remove(self.start_window)
 
         for handle in current_chrome_window_handles:
             self.marionette.switch_to_window(handle)
             self.marionette.close_chrome_window()
 
         self.marionette.switch_to_window(self.start_window)
 
-    def open_tab(self, callback=None, focus=False):
+    def open_tab(self, trigger="menu"):
         current_tabs = self.marionette.window_handles
 
         try:
-            if callable(callback):
-                callback()
-            else:
-                result = self.marionette.open(type="tab", focus=focus)
-                if result["type"] != "tab":
-                    raise Exception(
-                        "Newly opened browsing context is of type {} and not tab.".format(
-                            result["type"]))
+            if callable(trigger):
+                trigger()
+            elif trigger == 'menu':
+                with self.marionette.using_context("chrome"):
+                    self.marionette.find_element(*self._menu_item_new_tab).click()
         except Exception:
             exc, val, tb = sys.exc_info()
             reraise(exc, 'Failed to trigger opening a new tab: {}'.format(val), tb)
         else:
             Wait(self.marionette).until(
                 lambda mn: len(mn.window_handles) == len(current_tabs) + 1,
                 message="No new tab has been opened"
             )
 
             [new_tab] = list(set(self.marionette.window_handles) - set(current_tabs))
 
             return new_tab
 
-    def open_window(self, callback=None, focus=False):
+    def open_window(self, trigger=None):
         current_windows = self.marionette.chrome_window_handles
-        current_tabs = self.marionette.window_handles
 
         def loaded(handle):
             with self.marionette.using_context("chrome"):
                 return self.marionette.execute_script("""
                   Components.utils.import("resource://gre/modules/Services.jsm");
 
                   let win = Services.wm.getOuterWindowWithId(Number(arguments[0]));
                   return win.document.readyState == "complete";
                 """, script_args=[handle])
 
         try:
-            if callable(callback):
-                callback()
+            if callable(trigger):
+                trigger()
             else:
-                result = self.marionette.open(type="window", focus=focus)
-                if result["type"] != "window":
-                    raise Exception(
-                        "Newly opened browsing context is of type {} and not window.".format(
-                            result["type"]))
+                with self.marionette.using_context("chrome"):
+                    self.marionette.execute_script("OpenBrowserWindow();")
         except Exception:
             exc, val, tb = sys.exc_info()
             reraise(exc, 'Failed to trigger opening a new window: {}'.format(val), tb)
         else:
             Wait(self.marionette).until(
                 lambda mn: len(mn.chrome_window_handles) == len(current_windows) + 1,
                 message="No new window has been opened"
             )
 
             [new_window] = list(set(self.marionette.chrome_window_handles) - set(current_windows))
 
             # Before continuing ensure the window has been completed loading
             Wait(self.marionette).until(
                 lambda _: loaded(new_window),
                 message="Window with handle '{}'' did not finish loading".format(new_window))
 
-            # Bug 1507771 - Return the correct handle based on the currently selected context
-            # as long as "WebDriver:NewWindow" is not handled separtely in chrome context
-            context = self.marionette._send_message("Marionette:GetContext", key="value")
-            if context == "chrome":
-                return new_window
-            elif context == "content":
-                [new_tab] = list(set(self.marionette.window_handles) - set(current_tabs))
-                return new_tab
+            return new_window
 
-    def open_chrome_window(self, url, focus=False):
+    def open_chrome_window(self, url):
         """Open a new chrome window with the specified chrome URL.
 
         Can be replaced with "WebDriver:NewWindow" once the command
         supports opening generic chrome windows beside browsers (bug 1507771).
         """
         def open_with_js():
             with self.marionette.using_context("chrome"):
                 self.marionette.execute_async_script("""
@@ -173,10 +161,9 @@ class WindowManagerMixin(object):
                     let focused = waitForFocus(window);
                     window.focus();
                     await focused;
 
                     resolve();
                   })();
                 """, script_args=(url,))
 
-        with self.marionette.using_context("chrome"):
-            return self.open_window(callback=open_with_js, focus=focus)
+        return self.open_window(trigger=open_with_js)
--- a/testing/marionette/harness/marionette_harness/tests/unit/test_chrome.py
+++ b/testing/marionette/harness/marionette_harness/tests/unit/test_chrome.py
@@ -1,32 +1,53 @@
+#Copyright 2007-2009 WebDriver committers
+#Copyright 2007-2009 Google Inc.
+#
+#Licensed under the Apache License, Version 2.0 (the "License");
+#you may not use this file except in compliance with the License.
+#You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+#Unless required by applicable law or agreed to in writing, software
+#distributed under the License is distributed on an "AS IS" BASIS,
+#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#See the License for the specific language governing permissions and
+#limitations under the License.
+
 from __future__ import absolute_import
 
+from marionette_driver import By
+
 from marionette_harness import MarionetteTestCase, WindowManagerMixin
 
 
 class ChromeTests(WindowManagerMixin, MarionetteTestCase):
 
     def setUp(self):
         super(ChromeTests, self).setUp()
 
+        self.marionette.set_context('chrome')
+
     def tearDown(self):
         self.close_all_windows()
         super(ChromeTests, self).tearDown()
 
     def test_hang_until_timeout(self):
-        with self.marionette.using_context("chrome"):
-            new_window = self.open_window()
+        def open_with_menu():
+            menu = self.marionette.find_element(By.ID, 'aboutName')
+            menu.click()
+
+        new_window = self.open_window(trigger=open_with_menu)
         self.marionette.switch_to_window(new_window)
 
         try:
             try:
                 # Raise an exception type which should not be thrown by Marionette
                 # while running this test. Otherwise it would mask eg. IOError as
                 # thrown for a socket timeout.
                 raise NotImplementedError('Exception should not cause a hang when '
-                                          'closing the chrome window in content '
-                                          'context')
+                                          'closing the chrome window')
             finally:
                 self.marionette.close_chrome_window()
                 self.marionette.switch_to_window(self.start_window)
         except NotImplementedError:
             pass
--- a/testing/marionette/harness/marionette_harness/tests/unit/test_click.py
+++ b/testing/marionette/harness/marionette_harness/tests/unit/test_click.py
@@ -444,21 +444,25 @@ class TestClickCloseContext(WindowManage
         self.test_page = self.marionette.absolute_url("clicks.html")
 
     def tearDown(self):
         self.close_all_tabs()
 
         super(TestClickCloseContext, self).tearDown()
 
     def test_click_close_tab(self):
-        new_tab = self.open_tab()
-        self.marionette.switch_to_window(new_tab)
+        self.marionette.navigate(self.marionette.absolute_url("windowHandles.html"))
+        tab = self.open_tab(
+            lambda: self.marionette.find_element(By.ID, "new-tab").click())
+        self.marionette.switch_to_window(tab)
 
         self.marionette.navigate(self.test_page)
         self.marionette.find_element(By.ID, "close-window").click()
 
     @skip_if_mobile("Fennec doesn't support other chrome windows")
     def test_click_close_window(self):
-        new_tab = self.open_window()
-        self.marionette.switch_to_window(new_tab)
+        self.marionette.navigate(self.marionette.absolute_url("windowHandles.html"))
+        win = self.open_window(
+            lambda: self.marionette.find_element(By.ID, "new-window").click())
+        self.marionette.switch_to_window(win)
 
         self.marionette.navigate(self.test_page)
         self.marionette.find_element(By.ID, "close-window").click()
--- a/testing/marionette/harness/marionette_harness/tests/unit/test_key_actions.py
+++ b/testing/marionette/harness/marionette_harness/tests/unit/test_key_actions.py
@@ -72,8 +72,27 @@ class TestKeyActions(WindowManagerMixin,
     def test_input_with_wait(self):
         self.key_action.key_down("a").key_down("b").key_down("c").perform()
         (self.key_action.key_down(self.mod_key)
                         .key_down("a")
                         .wait(.5)
                         .key_down("x")
                         .perform())
         self.assertEqual(self.key_reporter_value, "")
+
+    @skip_if_mobile("Interacting with chrome windows not available for Fennec")
+    def test_open_in_new_window_shortcut(self):
+
+        def open_window_with_action():
+            el = self.marionette.find_element(By.TAG_NAME, "a")
+            (self.key_action.key_down(Keys.SHIFT)
+                            .press(el)
+                            .release()
+                            .key_up(Keys.SHIFT)
+                            .perform())
+
+        self.marionette.navigate(inline("<a href='#'>Click</a>"))
+        new_window = self.open_window(trigger=open_window_with_action)
+
+        self.marionette.switch_to_window(new_window)
+        self.marionette.close_chrome_window()
+
+        self.marionette.switch_to_window(self.start_window)
--- a/testing/marionette/harness/marionette_harness/tests/unit/test_navigation.py
+++ b/testing/marionette/harness/marionette_harness/tests/unit/test_navigation.py
@@ -50,18 +50,23 @@ class BaseNavigationTestCase(WindowManag
         self.test_page_remote = self.marionette.absolute_url("test.html")
         self.test_page_slow_resource = self.marionette.absolute_url("slow_resource.html")
 
         if self.marionette.session_capabilities["platformName"] == "mac":
             self.mod_key = Keys.META
         else:
             self.mod_key = Keys.CONTROL
 
+        def open_with_link():
+            link = self.marionette.find_element(By.ID, "new-blank-tab")
+            link.click()
+
         # Always use a blank new tab for an empty history
-        self.new_tab = self.open_tab()
+        self.marionette.navigate(self.marionette.absolute_url("windowHandles.html"))
+        self.new_tab = self.open_tab(open_with_link)
         self.marionette.switch_to_window(self.new_tab)
         Wait(self.marionette, timeout=self.marionette.timeout.page_load).until(
             lambda _: self.history_length == 1,
             message="The newly opened tab doesn't have a browser history length of 1")
 
     def tearDown(self):
         self.marionette.timeout.reset()
         self.marionette.switch_to_parent_frame()
@@ -288,16 +293,17 @@ class TestNavigate(BaseNavigationTestCas
     @skip_if_mobile("Bug 1322993 - Missing temporary folder")
     def test_focus_after_navigation(self):
         self.marionette.restart()
 
         self.marionette.navigate(inline("<input autofocus>"))
         focus_el = self.marionette.find_element(By.CSS_SELECTOR, ":focus")
         self.assertEqual(self.marionette.get_active_element(), focus_el)
 
+    @skip_if_mobile("Needs application independent method to open a new tab")
     def test_no_hang_when_navigating_after_closing_original_tab(self):
         # Close the start tab
         self.marionette.switch_to_window(self.start_tab)
         self.marionette.close()
 
         self.marionette.switch_to_window(self.new_tab)
         self.marionette.navigate(self.test_page_remote)
 
@@ -329,16 +335,32 @@ class TestNavigate(BaseNavigationTestCas
             urlbar.send_keys(self.mod_key + "x")
             urlbar.send_keys(self.test_page_remote + Keys.ENTER)
 
         Wait(self.marionette, timeout=self.marionette.timeout.page_load).until(
             lambda mn: mn.get_url() == self.test_page_remote,
             message="'{}' hasn't been loaded".format(self.test_page_remote))
         self.assertTrue(self.is_remote_tab)
 
+    @skip_if_mobile("On Android no shortcuts are available")
+    def test_navigate_shortcut_key(self):
+
+        def open_with_shortcut():
+            self.marionette.navigate(self.test_page_remote)
+            with self.marionette.using_context("chrome"):
+                main_win = self.marionette.find_element(By.ID, "main-window")
+                main_win.send_keys(self.mod_key, Keys.SHIFT, "a")
+
+        new_tab = self.open_tab(trigger=open_with_shortcut)
+        self.marionette.switch_to_window(new_tab)
+
+        Wait(self.marionette, timeout=self.marionette.timeout.page_load).until(
+            lambda mn: mn.get_url() == "about:addons",
+            message="'about:addons' hasn't been loaded")
+
 
 class TestBackForwardNavigation(BaseNavigationTestCase):
 
     def run_bfcache_test(self, test_pages):
         # Helper method to run simple back and forward testcases.
 
         def check_page_status(page, expected_history_length):
             if "alert_text" in page:
@@ -796,17 +818,17 @@ class TestPageLoadStrategy(BaseNavigatio
         self.marionette.navigate(self.test_page_slow_resource)
         self.assertEqual(self.test_page_slow_resource, self.marionette.get_url())
         self.assertEqual("complete", self.ready_state)
         self.marionette.find_element(By.ID, "slow")
 
     @skip("Bug 1422741 - Causes following tests to fail in loading remote browser")
     @run_if_e10s("Requires e10s mode enabled")
     def test_strategy_after_remoteness_change(self):
-        """Bug 1378191 - Reset of capabilities after listener reload."""
+        """Bug 1378191 - Reset of capabilities after listener reload"""
         self.marionette.delete_session()
         self.marionette.start_session({"pageLoadStrategy": "eager"})
 
         # Trigger a remoteness change which will reload the listener script
         self.assertTrue(self.is_remote_tab, "Initial tab doesn't have remoteness flag set")
         self.marionette.navigate("about:robots")
         self.assertFalse(self.is_remote_tab, "Tab has remoteness flag set")
         self.marionette.navigate(self.test_page_slow_resource)
--- a/testing/marionette/harness/marionette_harness/tests/unit/test_screenshot.py
+++ b/testing/marionette/harness/marionette_harness/tests/unit/test_screenshot.py
@@ -248,18 +248,17 @@ class TestScreenCaptureChrome(WindowMana
             self.marionette.navigate(box)
             content_element = self.marionette.find_element(By.ID, "green")
 
         self.assertRaisesRegexp(NoSuchElementException, "Web element reference not seen before",
                                 self.marionette.screenshot, highlights=[content_element])
 
         chrome_document_element = self.document_element
         with self.marionette.using_context('content'):
-            self.assertRaisesRegexp(NoSuchElementException,
-                                    "Web element reference not seen before",
+            self.assertRaisesRegexp(NoSuchElementException, "Web element reference not seen before",
                                     self.marionette.screenshot,
                                     highlights=[chrome_document_element])
 
 
 class TestScreenCaptureContent(WindowManagerMixin, ScreenCaptureTestCase):
 
     def setUp(self):
         super(TestScreenCaptureContent, self).setUp()
@@ -270,19 +269,20 @@ class TestScreenCaptureContent(WindowMan
         super(TestScreenCaptureContent, self).tearDown()
 
     @property
     def scroll_dimensions(self):
         return tuple(self.marionette.execute_script("""
             return [document.body.scrollWidth, document.body.scrollHeight]
             """))
 
+    @skip_if_mobile("Needs application independent method to open a new tab")
     def test_capture_tab_already_closed(self):
-        new_tab = self.open_tab()
-        self.marionette.switch_to_window(new_tab)
+        tab = self.open_tab()
+        self.marionette.switch_to_window(tab)
         self.marionette.close()
 
         self.assertRaises(NoSuchWindowException, self.marionette.screenshot)
         self.marionette.switch_to_window(self.start_tab)
 
     @skip_if_mobile("Bug 1487124 - Android need its own maximum allowed dimensions")
     def test_capture_vertical_bounds(self):
         self.marionette.navigate(inline("<body style='margin-top: 32768px'>foo"))
--- a/testing/marionette/harness/marionette_harness/tests/unit/test_switch_window_chrome.py
+++ b/testing/marionette/harness/marionette_harness/tests/unit/test_switch_window_chrome.py
@@ -1,18 +1,19 @@
 # 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/.
 
 from __future__ import absolute_import
 
 import os
 import sys
+from unittest import skipIf
 
-from unittest import skipIf
+from marionette_driver import By
 
 # add this directory to the path
 sys.path.append(os.path.dirname(__file__))
 
 from test_switch_window_content import TestSwitchToWindowContent
 
 
 class TestSwitchWindowChrome(TestSwitchToWindowContent):
@@ -22,75 +23,124 @@ class TestSwitchWindowChrome(TestSwitchT
 
         self.marionette.set_context("chrome")
 
     def tearDown(self):
         self.close_all_windows()
 
         super(TestSwitchWindowChrome, self).tearDown()
 
-    @skipIf(sys.platform.startswith("linux"),
-            "Bug 1511970 - New window isn't moved to the background on Linux")
+    def open_window_in_background(self):
+        with self.marionette.using_context("chrome"):
+            self.marionette.execute_async_script("""
+              let callback = arguments[0];
+              (async function() {
+                function promiseEvent(target, type, args) {
+                  return new Promise(r => {
+                    let params = Object.assign({once: true}, args);
+                    target.addEventListener(type, r, params);
+                  });
+                }
+                function promiseWindowFocus(w) {
+                  return Promise.all([
+                    promiseEvent(w, "focus", {capture: true}),
+                    promiseEvent(w, "activate"),
+                  ]);
+                }
+                // Open a window, wait for it to receive focus
+                let win = OpenBrowserWindow();
+                await promiseWindowFocus(win);
+
+                // Now refocus our original window and wait for that to happen.
+                let windowFocusPromise = promiseWindowFocus(window);
+                window.focus();
+                return windowFocusPromise;
+              })().then(() => {
+                // can't just pass `callback`, as we can't JSON-ify the events it'd get passed.
+                callback()
+              });
+            """)
+
+    def open_window_in_foreground(self):
+        with self.marionette.using_context("content"):
+            self.marionette.navigate(self.test_page)
+            link = self.marionette.find_element(By.ID, "new-window")
+            link.click()
+
     def test_switch_tabs_for_new_background_window_without_focus_change(self):
-        # Open an additional tab in the original window so we can better check
+        # Open an addition tab in the original window so we can better check
         # the selected index in thew new window to be opened.
-        second_tab = self.open_tab(focus=True)
+        second_tab = self.open_tab(trigger=self.open_tab_in_foreground)
         self.marionette.switch_to_window(second_tab, focus=True)
         second_tab_index = self.get_selected_tab_index()
         self.assertNotEqual(second_tab_index, self.selected_tab_index)
 
-        # Open a new background window, but we are interested in the tab
-        with self.marionette.using_context("content"):
-            tab_in_new_window = self.open_window()
+        # Opens a new background window, but we are interested in the tab
+        tab_in_new_window = self.open_tab(trigger=self.open_window_in_background)
         self.assertEqual(self.marionette.current_window_handle, second_tab)
         self.assertEqual(self.marionette.current_chrome_window_handle, self.start_window)
         self.assertEqual(self.get_selected_tab_index(), second_tab_index)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.empty_page)
 
         # Switch to the tab in the new window but don't focus it
         self.marionette.switch_to_window(tab_in_new_window, focus=False)
         self.assertEqual(self.marionette.current_window_handle, tab_in_new_window)
         self.assertNotEqual(self.marionette.current_chrome_window_handle, self.start_window)
         self.assertEqual(self.get_selected_tab_index(), second_tab_index)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), "about:blank")
 
     def test_switch_tabs_for_new_foreground_window_with_focus_change(self):
         # Open an addition tab in the original window so we can better check
         # the selected index in thew new window to be opened.
-        second_tab = self.open_tab()
+        second_tab = self.open_tab(trigger=self.open_tab_in_foreground)
         self.marionette.switch_to_window(second_tab, focus=True)
         second_tab_index = self.get_selected_tab_index()
         self.assertNotEqual(second_tab_index, self.selected_tab_index)
 
         # Opens a new window, but we are interested in the tab
-        with self.marionette.using_context("content"):
-            tab_in_new_window = self.open_window(focus=True)
+        tab_in_new_window = self.open_tab(trigger=self.open_window_in_foreground)
         self.assertEqual(self.marionette.current_window_handle, second_tab)
         self.assertEqual(self.marionette.current_chrome_window_handle, self.start_window)
         self.assertNotEqual(self.get_selected_tab_index(), second_tab_index)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.test_page)
 
         self.marionette.switch_to_window(tab_in_new_window)
         self.assertEqual(self.marionette.current_window_handle, tab_in_new_window)
         self.assertNotEqual(self.marionette.current_chrome_window_handle, self.start_window)
         self.assertNotEqual(self.get_selected_tab_index(), second_tab_index)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.empty_page)
 
         self.marionette.switch_to_window(second_tab, focus=True)
         self.assertEqual(self.marionette.current_window_handle, second_tab)
         self.assertEqual(self.marionette.current_chrome_window_handle, self.start_window)
         # Bug 1335085 - The focus doesn't change even as requested so.
         # self.assertEqual(self.get_selected_tab_index(), second_tab_index)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.test_page)
 
     def test_switch_tabs_for_new_foreground_window_without_focus_change(self):
         # Open an addition tab in the original window so we can better check
         # the selected index in thew new window to be opened.
-        second_tab = self.open_tab()
+        second_tab = self.open_tab(trigger=self.open_tab_in_foreground)
         self.marionette.switch_to_window(second_tab, focus=True)
         second_tab_index = self.get_selected_tab_index()
         self.assertNotEqual(second_tab_index, self.selected_tab_index)
 
-        self.open_window(focus=True)
+        # Opens a new window, but we are interested in the tab which automatically
+        # gets the focus.
+        self.open_tab(trigger=self.open_window_in_foreground)
         self.assertEqual(self.marionette.current_window_handle, second_tab)
         self.assertEqual(self.marionette.current_chrome_window_handle, self.start_window)
         self.assertNotEqual(self.get_selected_tab_index(), second_tab_index)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.test_page)
 
         # Switch to the second tab in the first window, but don't focus it.
         self.marionette.switch_to_window(second_tab, focus=False)
         self.assertEqual(self.marionette.current_window_handle, second_tab)
         self.assertEqual(self.marionette.current_chrome_window_handle, self.start_window)
         self.assertNotEqual(self.get_selected_tab_index(), second_tab_index)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.test_page)
--- a/testing/marionette/harness/marionette_harness/tests/unit/test_switch_window_content.py
+++ b/testing/marionette/harness/marionette_harness/tests/unit/test_switch_window_content.py
@@ -1,32 +1,38 @@
 # This Source Code Form is subject to the terms of the Mozilla ublic
 # 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/.
 
 from __future__ import absolute_import
 
-from marionette_driver import By
+from marionette_driver import Actions, By, Wait
 from marionette_driver.keys import Keys
 
-from marionette_harness import MarionetteTestCase, WindowManagerMixin
+from marionette_harness import MarionetteTestCase, skip_if_mobile, WindowManagerMixin
 
 
 class TestSwitchToWindowContent(WindowManagerMixin, MarionetteTestCase):
 
     def setUp(self):
         super(TestSwitchToWindowContent, self).setUp()
 
         if self.marionette.session_capabilities["platformName"] == "mac":
             self.mod_key = Keys.META
         else:
             self.mod_key = Keys.CONTROL
 
+        self.empty_page = self.marionette.absolute_url("empty.html")
+        self.test_page = self.marionette.absolute_url("windowHandles.html")
+
         self.selected_tab_index = self.get_selected_tab_index()
 
+        with self.marionette.using_context("content"):
+            self.marionette.navigate(self.test_page)
+
     def tearDown(self):
         self.close_all_tabs()
 
         super(TestSwitchToWindowContent, self).tearDown()
 
     def get_selected_tab_index(self):
         with self.marionette.using_context("chrome"):
             return self.marionette.execute_script("""
@@ -58,90 +64,110 @@ class TestSwitchToWindowContent(WindowMa
 
                 for (let i = 0; i < tabBrowser.tabs.length; i++) {
                   if (tabBrowser.tabs[i] == tabBrowser.selectedTab) {
                     return i;
                   }
                 }
             """)
 
+    def open_tab_in_background(self):
+        with self.marionette.using_context("content"):
+            link = self.marionette.find_element(By.ID, "new-tab")
+
+            action = Actions(self.marionette)
+            action.key_down(self.mod_key).click(link).perform()
+
+    def open_tab_in_foreground(self):
+        with self.marionette.using_context("content"):
+            link = self.marionette.find_element(By.ID, "new-tab")
+            link.click()
+
     def test_switch_tabs_with_focus_change(self):
-        new_tab = self.open_tab(focus=True)
+        new_tab = self.open_tab(self.open_tab_in_foreground)
         self.assertEqual(self.marionette.current_window_handle, self.start_tab)
         self.assertNotEqual(self.get_selected_tab_index(), self.selected_tab_index)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.test_page)
+
+        self.marionette.switch_to_window(new_tab)
+        self.assertEqual(self.marionette.current_window_handle, new_tab)
+        self.assertNotEqual(self.get_selected_tab_index(), self.selected_tab_index)
+
+        with self.marionette.using_context("content"):
+            Wait(self.marionette, timeout=self.marionette.timeout.page_load).until(
+                lambda _: self.marionette.get_url() == self.empty_page,
+                message="{} has been loaded in the newly opened tab.".format(self.empty_page))
+
+        self.marionette.switch_to_window(self.start_tab, focus=True)
+        self.assertEqual(self.marionette.current_window_handle, self.start_tab)
+        self.assertEqual(self.get_selected_tab_index(), self.selected_tab_index)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.test_page)
+
+        self.marionette.switch_to_window(new_tab)
+        self.marionette.close()
+        self.marionette.switch_to_window(self.start_tab)
+
+        self.assertEqual(self.marionette.current_window_handle, self.start_tab)
+        self.assertEqual(self.get_selected_tab_index(), self.selected_tab_index)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.test_page)
+
+    def test_switch_tabs_without_focus_change(self):
+        new_tab = self.open_tab(self.open_tab_in_foreground)
+        self.assertEqual(self.marionette.current_window_handle, self.start_tab)
+        self.assertNotEqual(self.get_selected_tab_index(), self.selected_tab_index)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.test_page)
 
         # Switch to new tab first because it is already selected
         self.marionette.switch_to_window(new_tab)
         self.assertEqual(self.marionette.current_window_handle, new_tab)
+
+        self.marionette.switch_to_window(self.start_tab, focus=False)
+        self.assertEqual(self.marionette.current_window_handle, self.start_tab)
         self.assertNotEqual(self.get_selected_tab_index(), self.selected_tab_index)
 
-        # Switch to original tab by explicitely setting the focus
-        self.marionette.switch_to_window(self.start_tab, focus=True)
-        self.assertEqual(self.marionette.current_window_handle, self.start_tab)
-        self.assertEqual(self.get_selected_tab_index(), self.selected_tab_index)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.test_page)
 
         self.marionette.switch_to_window(new_tab)
         self.marionette.close()
 
         self.marionette.switch_to_window(self.start_tab)
         self.assertEqual(self.marionette.current_window_handle, self.start_tab)
         self.assertEqual(self.get_selected_tab_index(), self.selected_tab_index)
-
-    def test_switch_tabs_without_focus_change(self):
-        new_tab = self.open_tab(focus=True)
-        self.assertEqual(self.marionette.current_window_handle, self.start_tab)
-        self.assertNotEqual(self.get_selected_tab_index(), self.selected_tab_index)
-
-        # Switch to new tab first because it is already selected
-        self.marionette.switch_to_window(new_tab)
-        self.assertEqual(self.marionette.current_window_handle, new_tab)
-
-        # Switch to original tab by explicitely not setting the focus
-        self.marionette.switch_to_window(self.start_tab, focus=False)
-        self.assertEqual(self.marionette.current_window_handle, self.start_tab)
-        self.assertNotEqual(self.get_selected_tab_index(), self.selected_tab_index)
-
-        self.marionette.switch_to_window(new_tab)
-        self.marionette.close()
-
-        self.marionette.switch_to_window(self.start_tab)
-        self.assertEqual(self.marionette.current_window_handle, self.start_tab)
-        self.assertEqual(self.get_selected_tab_index(), self.selected_tab_index)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.test_page)
 
     def test_switch_from_content_to_chrome_window_should_not_change_selected_tab(self):
-        new_tab = self.open_tab(focus=True)
+        new_tab = self.open_tab(self.open_tab_in_foreground)
 
         self.marionette.switch_to_window(new_tab)
         self.assertEqual(self.marionette.current_window_handle, new_tab)
         new_tab_index = self.get_selected_tab_index()
 
         self.marionette.switch_to_window(self.start_window)
         self.assertEqual(self.marionette.current_window_handle, new_tab)
         self.assertEqual(self.get_selected_tab_index(), new_tab_index)
 
-    def test_switch_to_new_private_browsing_tab(self):
+    @skip_if_mobile("New windows not supported in Fennec")
+    def test_switch_to_new_private_browsing_window_has_to_register_browsers(self):
         # Test that tabs (browsers) are correctly registered for a newly opened
-        # private browsing window/tab. This has to also happen without explicitely
+        # private browsing window. This has to also happen without explicitely
         # switching to the tab itself before using any commands in content scope.
         #
         # Note: Not sure why this only affects private browsing windows only.
-        new_tab = self.open_tab(focus=True)
-        self.marionette.switch_to_window(new_tab)
 
-        def open_private_browsing_window_firefox():
+        def open_private_browsing_window():
             with self.marionette.using_context("content"):
-                self.marionette.find_element(By.ID, "startPrivateBrowsing").click()
+                self.marionette.navigate("about:privatebrowsing")
+                button = self.marionette.find_element(By.ID, "startPrivateBrowsing")
+                button.click()
 
-        def open_private_browsing_tab_fennec():
-            with self.marionette.using_context("content"):
-                self.marionette.find_element(By.ID, "newPrivateTabLink").click()
+        new_window = self.open_window(open_private_browsing_window)
+        self.marionette.switch_to_window(new_window)
+        self.assertEqual(self.marionette.current_chrome_window_handle, new_window)
+        self.assertNotEqual(self.marionette.current_window_handle, self.start_tab)
 
         with self.marionette.using_context("content"):
-            self.marionette.navigate("about:privatebrowsing")
-            if self.marionette.session_capabilities["browserName"] == "fennec":
-                new_pb_tab = self.open_tab(open_private_browsing_tab_fennec)
-            else:
-                new_pb_tab = self.open_tab(open_private_browsing_window_firefox)
-
-        self.marionette.switch_to_window(new_pb_tab)
-        self.assertEqual(self.marionette.current_window_handle, new_pb_tab)
-
-        self.marionette.execute_script(" return true; ")
+            self.marionette.execute_script(" return true; ")
--- a/testing/marionette/harness/marionette_harness/tests/unit/test_window_close_chrome.py
+++ b/testing/marionette/harness/marionette_harness/tests/unit/test_window_close_chrome.py
@@ -16,24 +16,24 @@ class TestCloseWindow(WindowManagerMixin
 
     def tearDown(self):
         self.close_all_windows()
         self.close_all_tabs()
 
         super(TestCloseWindow, self).tearDown()
 
     def test_close_chrome_window_for_browser_window(self):
-        new_window = self.open_window()
-        self.marionette.switch_to_window(new_window)
+        win = self.open_window()
+        self.marionette.switch_to_window(win)
 
-        self.assertNotIn(new_window, self.marionette.window_handles)
+        self.assertNotIn(win, self.marionette.window_handles)
         chrome_window_handles = self.marionette.close_chrome_window()
-        self.assertNotIn(new_window, chrome_window_handles)
+        self.assertNotIn(win, chrome_window_handles)
         self.assertListEqual(self.start_windows, chrome_window_handles)
-        self.assertNotIn(new_window, self.marionette.window_handles)
+        self.assertNotIn(win, self.marionette.window_handles)
 
     def test_close_chrome_window_for_non_browser_window(self):
         win = self.open_chrome_window("chrome://marionette/content/test.xul")
         self.marionette.switch_to_window(win)
 
         self.assertIn(win, self.marionette.chrome_window_handles)
         self.assertNotIn(win, self.marionette.window_handles)
         chrome_window_handles = self.marionette.close_chrome_window()
@@ -45,30 +45,30 @@ class TestCloseWindow(WindowManagerMixin
         self.close_all_windows()
 
         self.assertListEqual([], self.marionette.close_chrome_window())
         self.assertListEqual([self.start_tab], self.marionette.window_handles)
         self.assertListEqual([self.start_window], self.marionette.chrome_window_handles)
         self.assertIsNotNone(self.marionette.session)
 
     def test_close_window_for_browser_tab(self):
-        new_tab = self.open_tab()
-        self.marionette.switch_to_window(new_tab)
+        tab = self.open_tab()
+        self.marionette.switch_to_window(tab)
 
         window_handles = self.marionette.close()
-        self.assertNotIn(new_tab, window_handles)
+        self.assertNotIn(tab, window_handles)
         self.assertListEqual(self.start_tabs, window_handles)
 
     def test_close_window_for_browser_window_with_single_tab(self):
-        new_window = self.open_window()
-        self.marionette.switch_to_window(new_window)
+        win = self.open_window()
+        self.marionette.switch_to_window(win)
 
         self.assertEqual(len(self.start_tabs) + 1, len(self.marionette.window_handles))
         window_handles = self.marionette.close()
-        self.assertNotIn(new_window, window_handles)
+        self.assertNotIn(win, window_handles)
         self.assertListEqual(self.start_tabs, window_handles)
         self.assertListEqual(self.start_windows, self.marionette.chrome_window_handles)
 
     def test_close_window_for_last_open_tab(self):
         self.close_all_tabs()
 
         self.assertListEqual([], self.marionette.close())
         self.assertListEqual([self.start_tab], self.marionette.window_handles)
--- a/testing/marionette/harness/marionette_harness/tests/unit/test_window_close_content.py
+++ b/testing/marionette/harness/marionette_harness/tests/unit/test_window_close_content.py
@@ -19,97 +19,98 @@ class TestCloseWindow(WindowManagerMixin
     def tearDown(self):
         self.close_all_windows()
         self.close_all_tabs()
 
         super(TestCloseWindow, self).tearDown()
 
     @skip_if_mobile("Interacting with chrome windows not available for Fennec")
     def test_close_chrome_window_for_browser_window(self):
-        with self.marionette.using_context("chrome"):
-            new_window = self.open_window()
-        self.marionette.switch_to_window(new_window)
+        win = self.open_window()
+        self.marionette.switch_to_window(win)
 
-        self.assertIn(new_window, self.marionette.chrome_window_handles)
+        self.assertNotIn(win, self.marionette.window_handles)
         chrome_window_handles = self.marionette.close_chrome_window()
-        self.assertNotIn(new_window, chrome_window_handles)
+        self.assertNotIn(win, chrome_window_handles)
         self.assertListEqual(self.start_windows, chrome_window_handles)
-        self.assertNotIn(new_window, self.marionette.window_handles)
+        self.assertNotIn(win, self.marionette.window_handles)
 
     @skip_if_mobile("Interacting with chrome windows not available for Fennec")
     def test_close_chrome_window_for_non_browser_window(self):
-        new_window = self.open_chrome_window("chrome://marionette/content/test.xul")
-        self.marionette.switch_to_window(new_window)
+        win = self.open_chrome_window("chrome://marionette/content/test.xul")
+        self.marionette.switch_to_window(win)
 
-        self.assertIn(new_window, self.marionette.chrome_window_handles)
-        self.assertNotIn(new_window, self.marionette.window_handles)
+        self.assertIn(win, self.marionette.chrome_window_handles)
+        self.assertNotIn(win, self.marionette.window_handles)
         chrome_window_handles = self.marionette.close_chrome_window()
-        self.assertNotIn(new_window, chrome_window_handles)
+        self.assertNotIn(win, chrome_window_handles)
         self.assertListEqual(self.start_windows, chrome_window_handles)
-        self.assertNotIn(new_window, self.marionette.window_handles)
+        self.assertNotIn(win, self.marionette.window_handles)
 
     @skip_if_mobile("Interacting with chrome windows not available for Fennec")
     def test_close_chrome_window_for_last_open_window(self):
         self.close_all_windows()
 
         self.assertListEqual([], self.marionette.close_chrome_window())
         self.assertListEqual([self.start_tab], self.marionette.window_handles)
         self.assertListEqual([self.start_window], self.marionette.chrome_window_handles)
         self.assertIsNotNone(self.marionette.session)
 
+    @skip_if_mobile("Needs application independent method to open a new tab")
     def test_close_window_for_browser_tab(self):
-        new_tab = self.open_tab()
-        self.marionette.switch_to_window(new_tab)
+        tab = self.open_tab()
+        self.marionette.switch_to_window(tab)
 
         window_handles = self.marionette.close()
-        self.assertNotIn(new_tab, window_handles)
+        self.assertNotIn(tab, window_handles)
         self.assertListEqual(self.start_tabs, window_handles)
 
+    @skip_if_mobile("Needs application independent method to open a new tab")
     def test_close_window_with_dismissed_beforeunload_prompt(self):
-        new_tab = self.open_tab()
-        self.marionette.switch_to_window(new_tab)
+        tab = self.open_tab()
+        self.marionette.switch_to_window(tab)
 
         self.marionette.navigate(inline("""
           <input type="text">
           <script>
             window.addEventListener("beforeunload", function (event) {
               event.preventDefault();
             });
           </script>
         """))
 
         self.marionette.find_element(By.TAG_NAME, "input").send_keys("foo")
         self.marionette.close()
 
     @skip_if_mobile("Interacting with chrome windows not available for Fennec")
     def test_close_window_for_browser_window_with_single_tab(self):
-        new_tab = self.open_window()
-        self.marionette.switch_to_window(new_tab)
+        win = self.open_window()
+        self.marionette.switch_to_window(win)
 
-        self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs) + 1)
+        self.assertEqual(len(self.start_tabs) + 1, len(self.marionette.window_handles))
         window_handles = self.marionette.close()
-        self.assertNotIn(new_tab, window_handles)
+        self.assertNotIn(win, window_handles)
         self.assertListEqual(self.start_tabs, window_handles)
         self.assertListEqual(self.start_windows, self.marionette.chrome_window_handles)
 
     def test_close_window_for_last_open_tab(self):
         self.close_all_tabs()
 
         self.assertListEqual([], self.marionette.close())
         self.assertListEqual([self.start_tab], self.marionette.window_handles)
         self.assertListEqual([self.start_window], self.marionette.chrome_window_handles)
         self.assertIsNotNone(self.marionette.session)
 
     @skip_if_mobile("discardBrowser is only available in Firefox")
     def test_close_browserless_tab(self):
         self.close_all_tabs()
 
         test_page = self.marionette.absolute_url("windowHandles.html")
-        new_tab = self.open_tab()
-        self.marionette.switch_to_window(new_tab)
+        tab = self.open_tab()
+        self.marionette.switch_to_window(tab)
         self.marionette.navigate(test_page)
         self.marionette.switch_to_window(self.start_tab)
 
         with self.marionette.using_context("chrome"):
             self.marionette.execute_async_script("""
               Components.utils.import("resource:///modules/BrowserWindowTracker.jsm");
 
               let win = BrowserWindowTracker.getTopWindow();
--- a/testing/marionette/harness/marionette_harness/tests/unit/test_window_handles_chrome.py
+++ b/testing/marionette/harness/marionette_harness/tests/unit/test_window_handles_chrome.py
@@ -1,27 +1,29 @@
 # 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/.
 
 from __future__ import absolute_import
 
 import types
 
-from marionette_driver import errors
+from marionette_driver import By, errors, Wait
 
 from marionette_harness import MarionetteTestCase, WindowManagerMixin
 
 
 class TestWindowHandles(WindowManagerMixin, MarionetteTestCase):
 
     def setUp(self):
         super(TestWindowHandles, self).setUp()
 
-        self.xul_dialog = "chrome://marionette/content/test_dialog.xul"
+        self.empty_page = self.marionette.absolute_url("empty.html")
+        self.test_page = self.marionette.absolute_url("windowHandles.html")
+        self.marionette.navigate(self.test_page)
 
         self.marionette.set_context("chrome")
 
     def tearDown(self):
         self.close_all_windows()
         self.close_all_tabs()
 
         super(TestWindowHandles, self).tearDown()
@@ -35,171 +37,265 @@ class TestWindowHandles(WindowManagerMix
 
         for handle in self.marionette.chrome_window_handles:
             self.assertIsInstance(handle, types.StringTypes)
 
         for handle in self.marionette.window_handles:
             self.assertIsInstance(handle, types.StringTypes)
 
     def test_chrome_window_handles_with_scopes(self):
-        new_browser = self.open_window()
+        # Open a browser and a non-browser (about window) chrome window
+        self.open_window(
+            trigger=lambda: self.marionette.execute_script("OpenBrowserWindow();"))
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.chrome_window_handles), len(self.start_windows) + 1)
-        self.assertIn(new_browser, self.marionette.chrome_window_handles)
         self.assertEqual(self.marionette.current_chrome_window_handle, self.start_window)
 
-        new_dialog = self.open_chrome_window(self.xul_dialog)
+        self.open_window(
+            trigger=lambda: self.marionette.find_element(By.ID, "aboutName").click())
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.chrome_window_handles), len(self.start_windows) + 2)
-        self.assertIn(new_dialog, self.marionette.chrome_window_handles)
         self.assertEqual(self.marionette.current_chrome_window_handle, self.start_window)
 
         chrome_window_handles_in_chrome_scope = self.marionette.chrome_window_handles
         window_handles_in_chrome_scope = self.marionette.window_handles
 
         with self.marionette.using_context("content"):
             self.assertEqual(self.marionette.chrome_window_handles,
                              chrome_window_handles_in_chrome_scope)
             self.assertEqual(self.marionette.window_handles,
                              window_handles_in_chrome_scope)
 
-    def test_chrome_window_handles_after_opening_new_chrome_window(self):
-        new_window = self.open_chrome_window(self.xul_dialog)
+    def test_chrome_window_handles_after_opening_new_dialog(self):
+        xul_dialog = "chrome://marionette/content/test_dialog.xul"
+        new_win = self.open_chrome_window(xul_dialog)
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.chrome_window_handles), len(self.start_windows) + 1)
-        self.assertIn(new_window, self.marionette.chrome_window_handles)
         self.assertEqual(self.marionette.current_chrome_window_handle, self.start_window)
 
-        # Check that the new chrome window has the correct URL loaded
-        self.marionette.switch_to_window(new_window)
+        # Check that the new tab has the correct page loaded
+        self.marionette.switch_to_window(new_win)
         self.assert_window_handles()
-        self.assertEqual(self.marionette.current_chrome_window_handle, new_window)
-        self.assertEqual(self.marionette.get_url(), self.xul_dialog)
+        self.assertEqual(self.marionette.current_chrome_window_handle, new_win)
+        self.assertEqual(self.marionette.get_url(), xul_dialog)
 
-        # Close the chrome window, and carry on in our original window.
+        # Close the opened dialog and carry on in our original tab.
         self.marionette.close_chrome_window()
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.chrome_window_handles), len(self.start_windows))
-        self.assertNotIn(new_window, self.marionette.chrome_window_handles)
 
         self.marionette.switch_to_window(self.start_window)
         self.assert_window_handles()
         self.assertEqual(self.marionette.current_chrome_window_handle, self.start_window)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.test_page)
 
     def test_chrome_window_handles_after_opening_new_window(self):
-        new_window = self.open_window()
+        def open_with_link():
+            with self.marionette.using_context("content"):
+                link = self.marionette.find_element(By.ID, "new-window")
+                link.click()
+
+        # We open a new window but are actually interested in the new tab
+        new_win = self.open_window(trigger=open_with_link)
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.chrome_window_handles), len(self.start_windows) + 1)
-        self.assertIn(new_window, self.marionette.chrome_window_handles)
         self.assertEqual(self.marionette.current_chrome_window_handle, self.start_window)
 
-        self.marionette.switch_to_window(new_window)
+        # Check that the new tab has the correct page loaded
+        self.marionette.switch_to_window(new_win)
         self.assert_window_handles()
-        self.assertEqual(self.marionette.current_chrome_window_handle, new_window)
+        self.assertEqual(self.marionette.current_chrome_window_handle, new_win)
+        with self.marionette.using_context("content"):
+            Wait(self.marionette, timeout=self.marionette.timeout.page_load).until(
+                lambda mn: mn.get_url() == self.empty_page,
+                message="{} did not load after opening a new tab".format(self.empty_page))
 
-        # Close the opened window and carry on in our original window.
+        # Ensure navigate works in our current window
+        other_page = self.marionette.absolute_url("test.html")
+        with self.marionette.using_context("content"):
+            self.marionette.navigate(other_page)
+            self.assertEqual(self.marionette.get_url(), other_page)
+
+        # Close the opened window and carry on in our original tab.
         self.marionette.close()
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.chrome_window_handles), len(self.start_windows))
-        self.assertNotIn(new_window, self.marionette.chrome_window_handles)
 
         self.marionette.switch_to_window(self.start_window)
         self.assert_window_handles()
         self.assertEqual(self.marionette.current_chrome_window_handle, self.start_window)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.test_page)
 
     def test_window_handles_after_opening_new_tab(self):
-        with self.marionette.using_context("content"):
-            new_tab = self.open_tab()
+        def open_with_link():
+            with self.marionette.using_context("content"):
+                link = self.marionette.find_element(By.ID, "new-tab")
+                link.click()
+
+        new_tab = self.open_tab(trigger=open_with_link)
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs) + 1)
-        self.assertIn(new_tab, self.marionette.window_handles)
         self.assertEqual(self.marionette.current_window_handle, self.start_tab)
 
         self.marionette.switch_to_window(new_tab)
         self.assert_window_handles()
         self.assertEqual(self.marionette.current_window_handle, new_tab)
+        with self.marionette.using_context("content"):
+            Wait(self.marionette, timeout=self.marionette.timeout.page_load).until(
+                lambda mn: mn.get_url() == self.empty_page,
+                message="{} did not load after opening a new tab".format(self.empty_page))
+
+        # Ensure navigate works in our current tab
+        other_page = self.marionette.absolute_url("test.html")
+        with self.marionette.using_context("content"):
+            self.marionette.navigate(other_page)
+            self.assertEqual(self.marionette.get_url(), other_page)
 
         self.marionette.switch_to_window(self.start_tab)
         self.assert_window_handles()
         self.assertEqual(self.marionette.current_window_handle, self.start_tab)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.test_page)
 
         self.marionette.switch_to_window(new_tab)
         self.marionette.close()
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs))
-        self.assertNotIn(new_tab, self.marionette.window_handles)
 
         self.marionette.switch_to_window(self.start_tab)
-        self.assert_window_handles()
-        self.assertEqual(self.marionette.current_window_handle, self.start_tab)
-
-    def test_window_handles_after_opening_new_foreground_tab(self):
-        with self.marionette.using_context("content"):
-            new_tab = self.open_tab(focus=True)
-        self.assert_window_handles()
-        self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs) + 1)
-        self.assertIn(new_tab, self.marionette.window_handles)
         self.assertEqual(self.marionette.current_window_handle, self.start_tab)
 
-        # We still have the default tab set as our window handle. This
-        # get_url command should be sent immediately, and not be forever-queued.
-        with self.marionette.using_context("content"):
-            self.marionette.get_url()
-
-        self.marionette.switch_to_window(new_tab)
-        self.assert_window_handles()
-        self.assertEqual(self.marionette.current_window_handle, new_tab)
-
-        self.marionette.close()
+    def test_window_handles_after_opening_new_dialog(self):
+        xul_dialog = "chrome://marionette/content/test_dialog.xul"
+        new_win = self.open_chrome_window(xul_dialog)
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs))
-        self.assertNotIn(new_tab, self.marionette.window_handles)
-
-        self.marionette.switch_to_window(self.start_tab)
-        self.assert_window_handles()
         self.assertEqual(self.marionette.current_window_handle, self.start_tab)
 
-    def test_window_handles_after_opening_new_chrome_window(self):
-        new_window = self.open_chrome_window(self.xul_dialog)
+        self.marionette.switch_to_window(new_win)
         self.assert_window_handles()
-        self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs))
-        self.assertNotIn(new_window, self.marionette.window_handles)
-        self.assertEqual(self.marionette.current_window_handle, self.start_tab)
-
-        self.marionette.switch_to_window(new_window)
-        self.assert_window_handles()
-        self.assertEqual(self.marionette.get_url(), self.xul_dialog)
+        self.assertEqual(self.marionette.get_url(), xul_dialog)
 
         # Check that the opened dialog is not accessible via window handles
         with self.assertRaises(errors.NoSuchWindowException):
             self.marionette.current_window_handle
         with self.assertRaises(errors.NoSuchWindowException):
             self.marionette.close()
 
         # Close the dialog and carry on in our original tab.
         self.marionette.close_chrome_window()
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs))
 
         self.marionette.switch_to_window(self.start_tab)
         self.assert_window_handles()
         self.assertEqual(self.marionette.current_window_handle, self.start_tab)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.test_page)
+
+    def test_window_handles_after_opening_new_window(self):
+        def open_with_link():
+            with self.marionette.using_context("content"):
+                link = self.marionette.find_element(By.ID, "new-window")
+                link.click()
+
+        # We open a new window but are actually interested in the new tab
+        new_tab = self.open_tab(trigger=open_with_link)
+        self.assert_window_handles()
+        self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs) + 1)
+        self.assertEqual(self.marionette.current_window_handle, self.start_tab)
+
+        # Check that the new tab has the correct page loaded
+        self.marionette.switch_to_window(new_tab)
+        self.assert_window_handles()
+        self.assertEqual(self.marionette.current_window_handle, new_tab)
+        with self.marionette.using_context("content"):
+            Wait(self.marionette, timeout=self.marionette.timeout.page_load).until(
+                lambda mn: mn.get_url() == self.empty_page,
+                message="{} did not load after opening a new tab".format(self.empty_page))
+
+        # Ensure navigate works in our current window
+        other_page = self.marionette.absolute_url("test.html")
+        with self.marionette.using_context("content"):
+            self.marionette.navigate(other_page)
+            self.assertEqual(self.marionette.get_url(), other_page)
+
+        # Close the opened window and carry on in our original tab.
+        self.marionette.close()
+        self.assert_window_handles()
+        self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs))
+
+        self.marionette.switch_to_window(self.start_tab)
+        self.assert_window_handles()
+        self.assertEqual(self.marionette.current_window_handle, self.start_tab)
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.test_page)
 
     def test_window_handles_after_closing_original_tab(self):
-        with self.marionette.using_context("content"):
-            new_tab = self.open_tab()
+        def open_with_link():
+            with self.marionette.using_context("content"):
+                link = self.marionette.find_element(By.ID, "new-tab")
+                link.click()
+
+        new_tab = self.open_tab(trigger=open_with_link)
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs) + 1)
-        self.assertIn(new_tab, self.marionette.window_handles)
         self.assertEqual(self.marionette.current_window_handle, self.start_tab)
 
         self.marionette.close()
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs))
-        self.assertIn(new_tab, self.marionette.window_handles)
+
+        self.marionette.switch_to_window(new_tab)
+        self.assert_window_handles()
+        self.assertEqual(self.marionette.current_window_handle, new_tab)
+        with self.marionette.using_context("content"):
+            Wait(self.marionette, timeout=self.marionette.timeout.page_load).until(
+                lambda mn: mn.get_url() == self.empty_page,
+                message="{} did not load after opening a new tab".format(self.empty_page))
+
+    def test_window_handles_no_switch(self):
+        """Regression test for bug 1294456.
+        This test is testing the case where Marionette attempts to send a
+        command to a window handle when the browser has opened and selected
+        a new tab. Before bug 1294456 landed, the Marionette driver was getting
+        confused about which window handle the client cared about, and assumed
+        it was the window handle for the newly opened and selected tab.
+
+        This caused Marionette to think that the browser needed to do a remoteness
+        flip in the e10s case, since the tab opened by menu_newNavigatorTab is
+        about:newtab (which is currently non-remote). This meant that commands
+        sent to what should have been the original window handle would be
+        queued and never sent, since the remoteness flip in the new tab was
+        never going to happen.
+        """
+        def open_with_menu():
+            menu_new_tab = self.marionette.find_element(By.ID, 'menu_newNavigatorTab')
+            menu_new_tab.click()
+
+        new_tab = self.open_tab(trigger=open_with_menu)
+        self.assert_window_handles()
+
+        # We still have the default tab set as our window handle. This
+        # get_url command should be sent immediately, and not be forever-queued.
+        with self.marionette.using_context("content"):
+            self.assertEqual(self.marionette.get_url(), self.test_page)
+
+        self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs) + 1)
+        self.assertEqual(self.marionette.current_window_handle, self.start_tab)
 
         self.marionette.switch_to_window(new_tab)
         self.assert_window_handles()
         self.assertEqual(self.marionette.current_window_handle, new_tab)
 
+        self.marionette.close()
+        self.assert_window_handles()
+        self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs))
+
+        self.marionette.switch_to_window(self.start_tab)
+        self.assert_window_handles()
+        self.assertEqual(self.marionette.current_window_handle, self.start_tab)
+
     def test_window_handles_after_closing_last_window(self):
         self.close_all_windows()
         self.assertEqual(self.marionette.close_chrome_window(), [])
--- a/testing/marionette/harness/marionette_harness/tests/unit/test_window_handles_content.py
+++ b/testing/marionette/harness/marionette_harness/tests/unit/test_window_handles_content.py
@@ -2,96 +2,135 @@
 # 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/.
 
 from __future__ import absolute_import
 
 import types
 import urllib
 
-from marionette_driver import errors
+from marionette_driver import By, errors, Wait
 
 from marionette_harness import MarionetteTestCase, skip_if_mobile, WindowManagerMixin
 
 
 def inline(doc):
     return "data:text/html;charset=utf-8,{}".format(urllib.quote(doc))
 
 
 class TestWindowHandles(WindowManagerMixin, MarionetteTestCase):
 
     def setUp(self):
         super(TestWindowHandles, self).setUp()
 
-        self.xul_dialog = "chrome://marionette/content/test_dialog.xul"
+        self.empty_page = self.marionette.absolute_url("empty.html")
+        self.test_page = self.marionette.absolute_url("windowHandles.html")
+        self.marionette.navigate(self.test_page)
 
     def tearDown(self):
         self.close_all_tabs()
 
         super(TestWindowHandles, self).tearDown()
 
     def assert_window_handles(self):
         try:
             self.assertIsInstance(self.marionette.current_window_handle, types.StringTypes)
         except errors.NoSuchWindowException:
             pass
 
         for handle in self.marionette.window_handles:
             self.assertIsInstance(handle, types.StringTypes)
 
-    def tst_window_handles_after_opening_new_tab(self):
-        new_tab = self.open_tab()
+    def test_window_handles_after_opening_new_tab(self):
+        def open_with_link():
+            link = self.marionette.find_element(By.ID, "new-tab")
+            link.click()
+
+        new_tab = self.open_tab(trigger=open_with_link)
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs) + 1)
         self.assertEqual(self.marionette.current_window_handle, self.start_tab)
 
         self.marionette.switch_to_window(new_tab)
         self.assert_window_handles()
         self.assertEqual(self.marionette.current_window_handle, new_tab)
+        Wait(self.marionette, timeout=self.marionette.timeout.page_load).until(
+            lambda mn: mn.get_url() == self.empty_page,
+            message="{} did not load after opening a new tab".format(self.empty_page))
 
         self.marionette.switch_to_window(self.start_tab)
         self.assertEqual(self.marionette.current_window_handle, self.start_tab)
+        self.assertEqual(self.marionette.get_url(), self.test_page)
 
         self.marionette.switch_to_window(new_tab)
         self.marionette.close()
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs))
 
         self.marionette.switch_to_window(self.start_tab)
         self.assert_window_handles()
         self.assertEqual(self.marionette.current_window_handle, self.start_tab)
 
-    def tst_window_handles_after_opening_new_browser_window(self):
-        new_tab = self.open_window()
+    def test_window_handles_after_opening_new_browser_window(self):
+        def open_with_link():
+            link = self.marionette.find_element(By.ID, "new-window")
+            link.click()
+
+        # We open a new window but are actually interested in the new tab
+        new_tab = self.open_tab(trigger=open_with_link)
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs) + 1)
         self.assertEqual(self.marionette.current_window_handle, self.start_tab)
 
+        # Check that the new tab has the correct page loaded
         self.marionette.switch_to_window(new_tab)
         self.assert_window_handles()
         self.assertEqual(self.marionette.current_window_handle, new_tab)
+        Wait(self.marionette, self.marionette.timeout.page_load).until(
+            lambda _: self.marionette.get_url() == self.empty_page,
+            message="The expected page '{}' has not been loaded".format(self.empty_page))
+
+        # Ensure navigate works in our current window
+        other_page = self.marionette.absolute_url("test.html")
+        self.marionette.navigate(other_page)
+        self.assertEqual(self.marionette.get_url(), other_page)
 
         # Close the opened window and carry on in our original tab.
         self.marionette.close()
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs))
 
         self.marionette.switch_to_window(self.start_tab)
         self.assert_window_handles()
         self.assertEqual(self.marionette.current_window_handle, self.start_tab)
+        self.assertEqual(self.marionette.get_url(), self.test_page)
 
     @skip_if_mobile("Fennec doesn't support other chrome windows")
-    def tst_window_handles_after_opening_new_non_browser_window(self):
-        new_window = self.open_chrome_window(self.xul_dialog)
+    def test_window_handles_after_opening_new_non_browser_window(self):
+        def open_with_link():
+            self.marionette.navigate(inline("""
+              <a id="blob-download" download="foo.html">Download</a>
+
+              <script>
+                const string = "test";
+                const blob = new Blob([string], { type: "text/html" });
+
+                const link = document.getElementById("blob-download");
+                link.href = URL.createObjectURL(blob);
+              </script>
+            """))
+            link = self.marionette.find_element(By.ID, "blob-download")
+            link.click()
+
+        new_win = self.open_window(trigger=open_with_link)
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs))
         self.assertEqual(self.marionette.current_window_handle, self.start_tab)
-        self.assertNotIn(new_window, self.marionette.window_handles)
 
-        self.marionette.switch_to_window(new_window)
+        self.marionette.switch_to_window(new_win)
         self.assert_window_handles()
 
         # Check that the opened window is not accessible via window handles
         with self.assertRaises(errors.NoSuchWindowException):
             self.marionette.current_window_handle
         with self.assertRaises(errors.NoSuchWindowException):
             self.marionette.close()
 
@@ -100,26 +139,31 @@ class TestWindowHandles(WindowManagerMix
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs))
 
         self.marionette.switch_to_window(self.start_tab)
         self.assert_window_handles()
         self.assertEqual(self.marionette.current_window_handle, self.start_tab)
 
     def test_window_handles_after_closing_original_tab(self):
-        new_tab = self.open_tab()
+        def open_with_link():
+            link = self.marionette.find_element(By.ID, "new-tab")
+            link.click()
+
+        new_tab = self.open_tab(trigger=open_with_link)
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs) + 1)
         self.assertEqual(self.marionette.current_window_handle, self.start_tab)
-        self.assertIn(new_tab, self.marionette.window_handles)
 
         self.marionette.close()
         self.assert_window_handles()
         self.assertEqual(len(self.marionette.window_handles), len(self.start_tabs))
-        self.assertNotIn(self.start_tab, self.marionette.window_handles)
 
         self.marionette.switch_to_window(new_tab)
         self.assert_window_handles()
         self.assertEqual(self.marionette.current_window_handle, new_tab)
+        Wait(self.marionette, self.marionette.timeout.page_load).until(
+            lambda _: self.marionette.get_url() == self.empty_page,
+            message="The expected page '{}' has not been loaded".format(self.empty_page))
 
-    def tst_window_handles_after_closing_last_tab(self):
+    def test_window_handles_after_closing_last_tab(self):
         self.close_all_tabs()
         self.assertEqual(self.marionette.close(), [])
--- a/testing/marionette/harness/marionette_harness/tests/unit/test_window_management.py
+++ b/testing/marionette/harness/marionette_harness/tests/unit/test_window_management.py
@@ -16,87 +16,93 @@ class TestNoSuchWindowContent(WindowMana
         super(TestNoSuchWindowContent, self).setUp()
 
     def tearDown(self):
         self.close_all_tabs()
         super(TestNoSuchWindowContent, self).tearDown()
 
     @skip_if_mobile("Fennec doesn't support other chrome windows")
     def test_closed_chrome_window(self):
-        with self.marionette.using_context("chrome"):
-            new_window = self.open_window()
-        self.marionette.switch_to_window(new_window)
+
+        def open_with_link():
+            with self.marionette.using_context("content"):
+                test_page = self.marionette.absolute_url("windowHandles.html")
+                self.marionette.navigate(test_page)
+                self.marionette.find_element(By.ID, "new-window").click()
+
+        win = self.open_window(open_with_link)
+        self.marionette.switch_to_window(win)
         self.marionette.close_chrome_window()
 
         # When closing a browser window both handles are not available
         for context in ("chrome", "content"):
             with self.marionette.using_context(context):
                 with self.assertRaises(NoSuchWindowException):
                     self.marionette.current_chrome_window_handle
                 with self.assertRaises(NoSuchWindowException):
                     self.marionette.current_window_handle
 
         self.marionette.switch_to_window(self.start_window)
 
         with self.assertRaises(NoSuchWindowException):
-            self.marionette.switch_to_window(new_window)
+            self.marionette.switch_to_window(win)
 
     @skip_if_mobile("Fennec doesn't support other chrome windows")
     def test_closed_chrome_window_while_in_frame(self):
-        new_window = self.open_chrome_window("chrome://marionette/content/test.xul")
-        self.marionette.switch_to_window(new_window)
+        win = self.open_chrome_window("chrome://marionette/content/test.xul")
+        self.marionette.switch_to_window(win)
         with self.marionette.using_context("chrome"):
             self.marionette.switch_to_frame("iframe")
         self.marionette.close_chrome_window()
 
         with self.assertRaises(NoSuchWindowException):
             self.marionette.current_window_handle
         with self.assertRaises(NoSuchWindowException):
             self.marionette.current_chrome_window_handle
 
         self.marionette.switch_to_window(self.start_window)
 
         with self.assertRaises(NoSuchWindowException):
-            self.marionette.switch_to_window(new_window)
+            self.marionette.switch_to_window(win)
 
     def test_closed_tab(self):
-        new_tab = self.open_tab()
-        self.marionette.switch_to_window(new_tab)
-        self.marionette.close()
+        with self.marionette.using_context("content"):
+            tab = self.open_tab()
+            self.marionette.switch_to_window(tab)
+            self.marionette.close()
 
         # Check that only the content window is not available in both contexts
         for context in ("chrome", "content"):
             with self.marionette.using_context(context):
                 with self.assertRaises(NoSuchWindowException):
                     self.marionette.current_window_handle
                 self.marionette.current_chrome_window_handle
 
         self.marionette.switch_to_window(self.start_tab)
 
         with self.assertRaises(NoSuchWindowException):
-            self.marionette.switch_to_window(new_tab)
+            self.marionette.switch_to_window(tab)
 
     def test_closed_tab_while_in_frame(self):
-        new_tab = self.open_tab()
-        self.marionette.switch_to_window(new_tab)
-
         with self.marionette.using_context("content"):
+            tab = self.open_tab()
+            self.marionette.switch_to_window(tab)
             self.marionette.navigate(self.marionette.absolute_url("test_iframe.html"))
             frame = self.marionette.find_element(By.ID, "test_iframe")
             self.marionette.switch_to_frame(frame)
-        self.marionette.close()
+            self.marionette.close()
 
-        with self.assertRaises(NoSuchWindowException):
-            self.marionette.current_window_handle
-        self.marionette.current_chrome_window_handle
+            with self.assertRaises(NoSuchWindowException):
+                self.marionette.current_window_handle
+            self.marionette.current_chrome_window_handle
 
         self.marionette.switch_to_window(self.start_tab)
 
         with self.assertRaises(NoSuchWindowException):
-            self.marionette.switch_to_window(new_tab)
+            self.marionette.switch_to_window(tab)
 
 
 class TestNoSuchWindowChrome(TestNoSuchWindowContent):
 
     def setUp(self):
         super(TestNoSuchWindowChrome, self).setUp()
         self.marionette.set_context("chrome")
 
@@ -110,27 +116,47 @@ class TestSwitchWindow(WindowManagerMixi
     def setUp(self):
         super(TestSwitchWindow, self).setUp()
         self.marionette.set_context("chrome")
 
     def tearDown(self):
         self.close_all_windows()
         super(TestSwitchWindow, self).tearDown()
 
-    def test_switch_window_after_open_and_close(self):
-        with self.marionette.using_context("chrome"):
-            new_window = self.open_window()
-        self.assertEqual(len(self.marionette.chrome_window_handles), len(self.start_windows) + 1)
-        self.assertIn(new_window, self.marionette.chrome_window_handles)
+    def test_windows(self):
+        def open_browser_with_js():
+            self.marionette.execute_script(" window.open(); ")
+
+        new_window = self.open_window(trigger=open_browser_with_js)
         self.assertEqual(self.marionette.current_chrome_window_handle, self.start_window)
 
-        # switch to the new chrome window and close it
+        # switch to the other window
         self.marionette.switch_to_window(new_window)
         self.assertEqual(self.marionette.current_chrome_window_handle, new_window)
         self.assertNotEqual(self.marionette.current_chrome_window_handle, self.start_window)
 
-        self.marionette.close_chrome_window()
-        self.assertEqual(len(self.marionette.chrome_window_handles), len(self.start_windows))
-        self.assertNotIn(new_window, self.marionette.chrome_window_handles)
-
-        # switch back to the original chrome window
+        # switch back and close original window
         self.marionette.switch_to_window(self.start_window)
         self.assertEqual(self.marionette.current_chrome_window_handle, self.start_window)
+        self.marionette.close_chrome_window()
+
+        self.assertNotIn(self.start_window, self.marionette.chrome_window_handles)
+        self.assertEqual(len(self.marionette.chrome_window_handles), len(self.start_windows))
+
+    def test_should_load_and_close_a_window(self):
+        def open_window_with_link():
+            test_html = self.marionette.absolute_url("test_windows.html")
+            with self.marionette.using_context("content"):
+                self.marionette.navigate(test_html)
+                self.marionette.find_element(By.LINK_TEXT, "Open new window").click()
+
+        new_window = self.open_window(trigger=open_window_with_link)
+        self.marionette.switch_to_window(new_window)
+        self.assertEqual(self.marionette.current_chrome_window_handle, new_window)
+        self.assertEqual(len(self.marionette.chrome_window_handles), 2)
+
+        with self.marionette.using_context('content'):
+            self.assertEqual(self.marionette.title, "We Arrive Here")
+
+        # Let's close and check
+        self.marionette.close_chrome_window()
+        self.marionette.switch_to_window(self.start_window)
+        self.assertEqual(len(self.marionette.chrome_window_handles), 1)
--- a/testing/marionette/harness/marionette_harness/tests/unit/test_window_status_content.py
+++ b/testing/marionette/harness/marionette_harness/tests/unit/test_window_status_content.py
@@ -10,87 +10,100 @@ from marionette_driver.errors import NoS
 from marionette_harness import MarionetteTestCase, WindowManagerMixin, skip_if_mobile
 
 
 class TestNoSuchWindowContent(WindowManagerMixin, MarionetteTestCase):
 
     def setUp(self):
         super(TestNoSuchWindowContent, self).setUp()
 
+        self.test_page = self.marionette.absolute_url("windowHandles.html")
+        with self.marionette.using_context("content"):
+            self.marionette.navigate(self.test_page)
+
     def tearDown(self):
         self.close_all_windows()
         super(TestNoSuchWindowContent, self).tearDown()
 
+    def open_tab_in_foreground(self):
+        with self.marionette.using_context("content"):
+            link = self.marionette.find_element(By.ID, "new-tab")
+            link.click()
+
     @skip_if_mobile("Fennec doesn't support other chrome windows")
     def test_closed_chrome_window(self):
-        with self.marionette.using_context("chrome"):
-            new_window = self.open_window()
-        self.marionette.switch_to_window(new_window)
+
+        def open_with_link():
+            with self.marionette.using_context("content"):
+                test_page = self.marionette.absolute_url("windowHandles.html")
+                self.marionette.navigate(test_page)
+                self.marionette.find_element(By.ID, "new-window").click()
+
+        win = self.open_window(open_with_link)
+        self.marionette.switch_to_window(win)
         self.marionette.close_chrome_window()
 
         # When closing a browser window both handles are not available
         for context in ("chrome", "content"):
             with self.marionette.using_context(context):
                 with self.assertRaises(NoSuchWindowException):
                     self.marionette.current_chrome_window_handle
                 with self.assertRaises(NoSuchWindowException):
                     self.marionette.current_window_handle
 
         self.marionette.switch_to_window(self.start_window)
 
         with self.assertRaises(NoSuchWindowException):
-            self.marionette.switch_to_window(new_window)
+            self.marionette.switch_to_window(win)
 
     @skip_if_mobile("Fennec doesn't support other chrome windows")
     def test_closed_chrome_window_while_in_frame(self):
-        new_window = self.open_chrome_window("chrome://marionette/content/test.xul")
-        self.marionette.switch_to_window(new_window)
-
+        win = self.open_chrome_window("chrome://marionette/content/test.xul")
+        self.marionette.switch_to_window(win)
         with self.marionette.using_context("chrome"):
             self.marionette.switch_to_frame("iframe")
         self.marionette.close_chrome_window()
 
         with self.assertRaises(NoSuchWindowException):
             self.marionette.current_window_handle
         with self.assertRaises(NoSuchWindowException):
             self.marionette.current_chrome_window_handle
 
         self.marionette.switch_to_window(self.start_window)
 
         with self.assertRaises(NoSuchWindowException):
-            self.marionette.switch_to_window(new_window)
+            self.marionette.switch_to_window(win)
 
     def test_closed_tab(self):
-        new_tab = self.open_tab(focus=True)
-        self.marionette.switch_to_window(new_tab)
-        self.marionette.close()
+        with self.marionette.using_context("content"):
+            tab = self.open_tab(self.open_tab_in_foreground)
+            self.marionette.switch_to_window(tab)
+            self.marionette.close()
 
         # Check that only the content window is not available in both contexts
         for context in ("chrome", "content"):
             with self.marionette.using_context(context):
                 with self.assertRaises(NoSuchWindowException):
                     self.marionette.current_window_handle
                 self.marionette.current_chrome_window_handle
 
         self.marionette.switch_to_window(self.start_tab)
 
         with self.assertRaises(NoSuchWindowException):
-            self.marionette.switch_to_window(new_tab)
+            self.marionette.switch_to_window(tab)
 
     def test_closed_tab_while_in_frame(self):
-        new_tab = self.open_tab()
-        self.marionette.switch_to_window(new_tab)
-
         with self.marionette.using_context("content"):
+            tab = self.open_tab(self.open_tab_in_foreground)
+            self.marionette.switch_to_window(tab)
             self.marionette.navigate(self.marionette.absolute_url("test_iframe.html"))
             frame = self.marionette.find_element(By.ID, "test_iframe")
             self.marionette.switch_to_frame(frame)
-
-        self.marionette.close()
+            self.marionette.close()
 
-        with self.assertRaises(NoSuchWindowException):
-            self.marionette.current_window_handle
-        self.marionette.current_chrome_window_handle
+            with self.assertRaises(NoSuchWindowException):
+                self.marionette.current_window_handle
+            self.marionette.current_chrome_window_handle
 
         self.marionette.switch_to_window(self.start_tab)
 
         with self.assertRaises(NoSuchWindowException):
-            self.marionette.switch_to_window(new_tab)
+            self.marionette.switch_to_window(tab)
--- a/testing/marionette/proxy.js
+++ b/testing/marionette/proxy.js
@@ -10,17 +10,17 @@ ChromeUtils.import("resource://gre/modul
 const {
   error,
   WebDriverError,
 } = ChromeUtils.import("chrome://marionette/content/error.js", {});
 ChromeUtils.import("chrome://marionette/content/evaluate.js");
 const {Log} = ChromeUtils.import("chrome://marionette/content/log.js", {});
 ChromeUtils.import("chrome://marionette/content/modal.js");
 const {
-  waitForObserverTopic,
+  MessageManagerDestroyedPromise,
 } = ChromeUtils.import("chrome://marionette/content/sync.js", {});
 
 this.EXPORTED_SYMBOLS = ["proxy"];
 
 XPCOMUtils.defineLazyGetter(this, "log", Log.get);
 XPCOMUtils.defineLazyServiceGetter(
     this, "uuidgen", "@mozilla.org/uuid-generator;1", "nsIUUIDGenerator");
 
@@ -151,19 +151,17 @@ proxy.AsyncMessageChannel = class {
           case "unload":
             messageManager = this.browser.window.messageManager;
             break;
           case "TabClose":
             messageManager = this.browser.messageManager;
             break;
         }
 
-        await waitForObserverTopic("message-manager-disconnect",
-            subject => subject === messageManager);
-
+        await new MessageManagerDestroyedPromise(messageManager);
         this.removeHandlers();
         resolve();
       };
 
       // A modal or tab modal dialog has been opened. To be able to handle it,
       // the active command has to be aborted. Therefore remove all handlers,
       // and cancel any ongoing requests in the listener.
       this.dialogueObserver_ = (subject, topic) => {
--- a/testing/marionette/server.js
+++ b/testing/marionette/server.js
@@ -6,16 +6,17 @@
 
 const CC = Components.Constructor;
 
 const ServerSocket = CC(
     "@mozilla.org/network/server-socket;1",
     "nsIServerSocket",
     "initSpecialConnection");
 
+ChromeUtils.import("resource://gre/modules/Services.jsm");
 ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 
 ChromeUtils.import("chrome://marionette/content/assert.js");
 const {GeckoDriver} = ChromeUtils.import("chrome://marionette/content/driver.js", {});
 const {WebElement} = ChromeUtils.import("chrome://marionette/content/element.js", {});
 const {
   error,
   UnknownCommandError,
@@ -68,17 +69,17 @@ class TCPListener {
    *
    * Determines the application to initialise the driver with.
    *
    * @return {GeckoDriver}
    *     A driver instance.
    */
   driverFactory() {
     MarionettePrefs.contentListener = false;
-    return new GeckoDriver(this);
+    return new GeckoDriver(Services.appinfo.ID, this);
   }
 
   set acceptConnections(value) {
     if (value) {
       if (!this.socket) {
         try {
           const flags = KeepWhenOffline | LoopbackOnly;
           const backlog = 1;
--- a/testing/marionette/sync.js
+++ b/testing/marionette/sync.js
@@ -8,52 +8,33 @@ ChromeUtils.import("resource://gre/modul
 ChromeUtils.import("resource://gre/modules/Services.jsm");
 ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 
 const {
   error,
   stack,
   TimeoutError,
 } = ChromeUtils.import("chrome://marionette/content/error.js", {});
-const {truncate} = ChromeUtils.import("chrome://marionette/content/format.js", {});
 const {Log} = ChromeUtils.import("chrome://marionette/content/log.js", {});
 
 XPCOMUtils.defineLazyGetter(this, "log", Log.get);
 
 this.EXPORTED_SYMBOLS = [
-  "executeSoon",
   "DebounceCallback",
   "IdlePromise",
+  "MessageManagerDestroyedPromise",
   "PollPromise",
   "Sleep",
   "TimedPromise",
-  "waitForEvent",
-  "waitForMessage",
-  "waitForObserverTopic",
 ];
 
 const {TYPE_ONE_SHOT, TYPE_REPEATING_SLACK} = Ci.nsITimer;
 
 const PROMISE_TIMEOUT = AppConstants.DEBUG ? 4500 : 1500;
 
-
-/**
- * Dispatch a function to be executed on the main thread.
- *
- * @param {function} func
- *     Function to be executed.
- */
-function executeSoon(func) {
-  if (typeof func != "function") {
-    throw new TypeError();
-  }
-
-  Services.tm.dispatchToMainThread(func);
-}
-
 /**
  * @callback Condition
  *
  * @param {function(*)} resolve
  *     To be called when the condition has been met.  Will return the
  *     resolved value.
  * @param {function} reject
  *     To be called when the condition has not been met.  Will cause
@@ -251,16 +232,56 @@ function TimedPromise(fn,
 function Sleep(timeout) {
   if (typeof timeout != "number") {
     throw new TypeError();
   }
   return new TimedPromise(() => {}, {timeout, throws: null});
 }
 
 /**
+ * Detects when the specified message manager has been destroyed.
+ *
+ * One can observe the removal and detachment of a content browser
+ * (`<xul:browser>`) or a chrome window by its message manager
+ * disconnecting.
+ *
+ * When a browser is associated with a tab, this is safer than only
+ * relying on the event `TabClose` which signalises the _intent to_
+ * remove a tab and consequently would lead to the destruction of
+ * the content browser and its browser message manager.
+ *
+ * When closing a chrome window it is safer than only relying on
+ * the event 'unload' which signalises the _intent to_ close the
+ * chrome window and consequently would lead to the destruction of
+ * the window and its window message manager.
+ *
+ * @param {MessageListenerManager} messageManager
+ *     The message manager to observe for its disconnect state.
+ *     Use the browser message manager when closing a content browser,
+ *     and the window message manager when closing a chrome window.
+ *
+ * @return {Promise}
+ *     A promise that resolves when the message manager has been destroyed.
+ */
+function MessageManagerDestroyedPromise(messageManager) {
+  return new Promise(resolve => {
+    function observe(subject, topic) {
+      log.trace(`Received observer notification ${topic}`);
+
+      if (subject == messageManager) {
+        Services.obs.removeObserver(this, "message-manager-disconnect");
+        resolve();
+      }
+    }
+
+    Services.obs.addObserver(observe, "message-manager-disconnect");
+  });
+}
+
+/**
  * Throttle until the main thread is idle and `window` has performed
  * an animation frame (in that order).
  *
  * @param {ChromeWindow} win
  *     Window to request the animation frame from.
  *
  * @return Promise
  */
@@ -325,197 +346,8 @@ class DebounceCallback {
     this.timer.cancel();
     this.timer.initWithCallback(() => {
       this.timer.cancel();
       this.fn(ev);
     }, this.timeout, TYPE_ONE_SHOT);
   }
 }
 this.DebounceCallback = DebounceCallback;
-
-/**
- * Wait for an event to be fired on a specified element.
- *
- * This method has been duplicated from BrowserTestUtils.jsm.
- *
- * Because this function is intended for testing, any error in checkFn
- * will cause the returned promise to be rejected instead of waiting for
- * the next event, since this is probably a bug in the test.
- *
- * Usage::
- *
- *    let promiseEvent = waitForEvent(element, "eventName");
- *    // Do some processing here that will cause the event to be fired
- *    // ...
- *    // Now wait until the Promise is fulfilled
- *    let receivedEvent = await promiseEvent;
- *
- * The promise resolution/rejection handler for the returned promise is
- * guaranteed not to be called until the next event tick after the event
- * listener gets called, so that all other event listeners for the element
- * are executed before the handler is executed::
- *
- *    let promiseEvent = waitForEvent(element, "eventName");
- *    // Same event tick here.
- *    await promiseEvent;
- *    // Next event tick here.
- *
- * If some code, such like adding yet another event listener, needs to be
- * executed in the same event tick, use raw addEventListener instead and
- * place the code inside the event listener::
- *
- *    element.addEventListener("load", () => {
- *      // Add yet another event listener in the same event tick as the load
- *      // event listener.
- *      p = waitForEvent(element, "ready");
- *    }, { once: true });
- *
- * @param {Element} subject
- *     The element that should receive the event.
- * @param {string} eventName
- *     Name of the event to listen to.
- * @param {Object=} options
- *     Extra options.
- * @param {boolean=} options.capture
- *     True to use a capturing listener.
- * @param {function(Event)=} options.checkFn
- *     Called with the ``Event`` object as argument, should return ``true``
- *     if the event is the expected one, or ``false`` if it should be
- *     ignored and listening should continue. If not specified, the first
- *     event with the specified name resolves the returned promise.
- * @param {boolean=} options.wantsUntrusted
- *     True to receive synthetic events dispatched by web content.
- *
- * @return {Promise.<Event>}
- *     Promise which resolves to the received ``Event`` object, or rejects
- *     in case of a failure.
- */
-function waitForEvent(subject, eventName,
-    {capture = false, checkFn = null, wantsUntrusted = false} = {}) {
-  if (subject == null || !("addEventListener" in subject)) {
-    throw new TypeError();
-  }
-  if (typeof eventName != "string") {
-    throw new TypeError();
-  }
-  if (capture != null && typeof capture != "boolean") {
-    throw new TypeError();
-  }
-  if (checkFn != null && typeof checkFn != "function") {
-    throw new TypeError();
-  }
-  if (wantsUntrusted != null && typeof wantsUntrusted != "boolean") {
-    throw new TypeError();
-  }
-
-  return new Promise((resolve, reject) => {
-    subject.addEventListener(eventName, function listener(event) {
-      log.trace(`Received DOM event ${event.type} for ${event.target}`);
-      try {
-        if (checkFn && !checkFn(event)) {
-          return;
-        }
-        subject.removeEventListener(eventName, listener, capture);
-        executeSoon(() => resolve(event));
-      } catch (ex) {
-        try {
-          subject.removeEventListener(eventName, listener, capture);
-        } catch (ex2) {
-          // Maybe the provided object does not support removeEventListener.
-        }
-        executeSoon(() => reject(ex));
-      }
-    }, capture, wantsUntrusted);
-  });
-}
-
-/**
- * Wait for a message to be fired from a particular message manager.
- *
- * This method has been duplicated from BrowserTestUtils.jsm.
- *
- * @param {nsIMessageManager} messageManager
- *     The message manager that should be used.
- * @param {string} messageName
- *     The message to wait for.
- * @param {Object=} options
- *     Extra options.
- * @param {function(Message)=} options.checkFn
- *     Called with the ``Message`` object as argument, should return ``true``
- *     if the message is the expected one, or ``false`` if it should be
- *     ignored and listening should continue. If not specified, the first
- *     message with the specified name resolves the returned promise.
- *
- * @return {Promise.<Object>}
- *     Promise which resolves to the data property of the received
- *     ``Message``.
- */
-function waitForMessage(messageManager, messageName,
-    {checkFn = undefined} = {}) {
-  if (messageManager == null || !("addMessageListener" in messageManager)) {
-    throw new TypeError();
-  }
-  if (typeof messageName != "string") {
-    throw new TypeError();
-  }
-  if (checkFn && typeof checkFn != "function") {
-    throw new TypeError();
-  }
-
-  return new Promise(resolve => {
-    messageManager.addMessageListener(messageName, function onMessage(msg) {
-      log.trace(`Received ${messageName} for ${msg.target}`);
-      if (checkFn && !checkFn(msg)) {
-        return;
-      }
-      messageManager.removeMessageListener(messageName, onMessage);
-      resolve(msg.data);
-    });
-  });
-}
-
-/**
- * Wait for the specified observer topic to be observed.
- *
- * This method has been duplicated from TestUtils.jsm.
- *
- * Because this function is intended for testing, any error in checkFn
- * will cause the returned promise to be rejected instead of waiting for
- * the next notification, since this is probably a bug in the test.
- *
- * @param {string} topic
- *     The topic to observe.
- * @param {Object=} options
- *     Extra options.
- * @param {function(String,Object)=} options.checkFn
- *     Called with ``subject``, and ``data`` as arguments, should return true
- *     if the notification is the expected one, or false if it should be
- *     ignored and listening should continue. If not specified, the first
- *     notification for the specified topic resolves the returned promise.
- *
- * @return {Promise.<Array<String, Object>>}
- *     Promise which resolves to an array of ``subject``, and ``data`` from
- *     the observed notification.
- */
-function waitForObserverTopic(topic, {checkFn = null} = {}) {
-  if (typeof topic != "string") {
-    throw new TypeError();
-  }
-  if (checkFn != null && typeof checkFn != "function") {
-    throw new TypeError();
-  }
-
-  return new Promise((resolve, reject) => {
-    Services.obs.addObserver(function observer(subject, topic, data) {
-      log.trace(`Received observer notification ${topic}`);
-      try {
-        if (checkFn && !checkFn(subject, data)) {
-          return;
-        }
-        Services.obs.removeObserver(observer, topic);
-        resolve({subject, data});
-      } catch (ex) {
-        Services.obs.removeObserver(observer, topic);
-        reject(ex);
-      }
-    }, topic);
-  });
-}
--- a/testing/marionette/test/unit/test_sync.js
+++ b/testing/marionette/test/unit/test_sync.js
@@ -1,100 +1,23 @@
 /* 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/. */
 
-ChromeUtils.import("resource://gre/modules/Services.jsm");
-
 const {
   DebounceCallback,
   IdlePromise,
   PollPromise,
   Sleep,
   TimedPromise,
-  waitForEvent,
-  waitForMessage,
-  waitForObserverTopic,
 } = ChromeUtils.import("chrome://marionette/content/sync.js", {});
 
 const DEFAULT_TIMEOUT = 2000;
 
 /**
- * Mimic a DOM node for listening for events.
- */
-class MockElement {
-  constructor() {
-    this.capture = false;
-    this.func = null;
-    this.eventName = null;
-    this.untrusted = false;
-  }
-
-  addEventListener(name, func, capture, untrusted) {
-    this.eventName = name;
-    this.func = func;
-    if (capture != null) {
-      this.capture = capture;
-    }
-    if (untrusted != null) {
-      this.untrusted = untrusted;
-    }
-  }
-
-  click() {
-    if (this.func) {
-      let details = {
-        capture: this.capture,
-        target: this,
-        type: this.eventName,
-        untrusted: this.untrusted,
-      };
-      this.func(details);
-    }
-  }
-
-  removeEventListener(name, func) {
-    this.capture = false;
-    this.func = null;
-    this.eventName = null;
-    this.untrusted = false;
-  }
-}
-
-/**
- * Mimic a message manager for sending messages.
- */
-class MessageManager {
-  constructor() {
-    this.func = null;
-    this.message = null;
-  }
-
-  addMessageListener(message, func) {
-    this.func = func;
-    this.message = message;
-  }
-
-  removeMessageListener(message) {
-    this.func = null;
-    this.message = null;
-  }
-
-  send(message, data) {
-    if (this.func) {
-      this.func({
-        data,
-        message,
-        target: this,
-      });
-    }
-  }
-}
-
-/**
  * Mimics nsITimer, but instead of using a system clock you can
  * preprogram it to invoke the callback after a given number of ticks.
  */
 class MockTimer {
   constructor(ticksBeforeFiring) {
     this.goal = ticksBeforeFiring;
     this.ticks = 0;
     this.cancelled = false;
@@ -107,33 +30,16 @@ class MockTimer {
     }
   }
 
   cancel() {
     this.cancelled = true;
   }
 }
 
-add_test(function test_executeSoon_callback() {
-  // executeSoon() is already defined for xpcshell in head.js. As such import
-  // our implementation into a custom namespace.
-  let sync = {};
-  ChromeUtils.import("chrome://marionette/content/sync.js", sync);
-
-  for (let func of ["foo", null, true, [], {}]) {
-    Assert.throws(() => sync.executeSoon(func), /TypeError/);
-  }
-
-  let a;
-  sync.executeSoon(() => { a = 1; });
-  executeSoon(() => equal(1, a));
-
-  run_next_test();
-});
-
 add_test(function test_PollPromise_funcTypes() {
   for (let type of ["foo", 42, null, undefined, true, [], {}]) {
     Assert.throws(() => new PollPromise(type), /TypeError/);
   }
   new PollPromise(() => {});
   new PollPromise(function() {});
 
   run_next_test();
@@ -302,160 +208,8 @@ add_task(async function test_DebounceCal
   // we only expect the last one to fire
   debouncer.handleEvent(uniqueEvent);
   debouncer.handleEvent(uniqueEvent);
   debouncer.handleEvent(uniqueEvent);
 
   equal(ncalls, 1);
   ok(debouncer.timer.cancelled);
 });
-
-add_task(async function test_waitForEvent_subjectAndEventNameTypes() {
-  let element = new MockElement();
-
-  for (let subject of ["foo", 42, null, undefined, true, [], {}]) {
-    Assert.throws(() => waitForEvent(subject, "click"), /TypeError/);
-  }
-
-  for (let eventName of [42, null, undefined, true, [], {}]) {
-    Assert.throws(() => waitForEvent(element, eventName), /TypeError/);
-  }
-
-  let clicked = waitForEvent(element, "click");
-  element.click();
-  let event = await clicked;
-  equal(element, event.target);
-});
-
-add_task(async function test_waitForEvent_captureTypes() {
-  let element = new MockElement();
-
-  for (let capture of ["foo", 42, [], {}]) {
-    Assert.throws(() => waitForEvent(
-        element, "click", {capture}), /TypeError/);
-  }
-
-  for (let capture of [null, undefined, false, true]) {
-    let expected_capture = (capture == null) ? false : capture;
-
-    element = new MockElement();
-    let clicked = waitForEvent(element, "click", {capture});
-    element.click();
-    let event = await clicked;
-    equal(element, event.target);
-    equal(expected_capture, event.capture);
-  }
-});
-
-add_task(async function test_waitForEvent_checkFnTypes() {
-  let element = new MockElement();
-
-  for (let checkFn of ["foo", 42, true, [], {}]) {
-    Assert.throws(() => waitForEvent(
-        element, "click", {checkFn}), /TypeError/);
-  }
-
-  let count;
-  for (let checkFn of [null, undefined, event => count++ > 0]) {
-    let expected_count = (checkFn == null) ? 0 : 2;
-    count = 0;
-
-    element = new MockElement();
-    let clicked = waitForEvent(element, "click", {checkFn});
-    element.click();
-    element.click();
-    let event = await clicked;
-    equal(element, event.target);
-    equal(expected_count, count);
-  }
-});
-
-add_task(async function test_waitForEvent_wantsUntrustedTypes() {
-  let element = new MockElement();
-
-  for (let wantsUntrusted of ["foo", 42, [], {}]) {
-    Assert.throws(() => waitForEvent(
-        element, "click", {wantsUntrusted}), /TypeError/);
-  }
-
-  for (let wantsUntrusted of [null, undefined, false, true]) {
-    let expected_untrusted = (wantsUntrusted == null) ? false : wantsUntrusted;
-
-    element = new MockElement();
-    let clicked = waitForEvent(element, "click", {wantsUntrusted});
-    element.click();
-    let event = await clicked;
-    equal(element, event.target);
-    equal(expected_untrusted, event.untrusted);
-  }
-});
-
-add_task(async function test_waitForMessage_messageManagerAndMessageTypes() {
-  let messageManager = new MessageManager();
-
-  for (let manager of ["foo", 42, null, undefined, true, [], {}]) {
-    Assert.throws(() => waitForMessage(manager, "message"), /TypeError/);
-  }
-
-  for (let message of [42, null, undefined, true, [], {}]) {
-    Assert.throws(() => waitForEvent(messageManager, message), /TypeError/);
-  }
-
-  let data = {"foo": "bar"};
-  let sent = waitForMessage(messageManager, "message");
-  messageManager.send("message", data);
-  equal(data, await sent);
-});
-
-add_task(async function test_waitForMessage_checkFnTypes() {
-  let messageManager = new MessageManager();
-
-  for (let checkFn of ["foo", 42, true, [], {}]) {
-    Assert.throws(() => waitForMessage(
-        messageManager, "message", {checkFn}), /TypeError/);
-  }
-
-  let data1 = {"fo": "bar"};
-  let data2 = {"foo": "bar"};
-
-  for (let checkFn of [null, undefined, msg => "foo" in msg.data]) {
-    let expected_data = (checkFn == null) ? data1 : data2;
-
-    messageManager = new MessageManager();
-    let sent = waitForMessage(messageManager, "message", {checkFn});
-    messageManager.send("message", data1);
-    messageManager.send("message", data2);
-    equal(expected_data, await sent);
-  }
-});
-
-add_task(async function test_waitForObserverTopic_topicTypes() {
-  for (let topic of [42, null, undefined, true, [], {}]) {
-    Assert.throws(() => waitForObserverTopic(topic), /TypeError/);
-  }
-
-  let data = {"foo": "bar"};
-  let sent = waitForObserverTopic("message");
-  Services.obs.notifyObservers(this, "message", data);
-  let result = await sent;
-  equal(this, result.subject);
-  equal(data, result.data);
-});
-
-add_task(async function test_waitForObserverTopic_checkFnTypes() {
-  for (let checkFn of ["foo", 42, true, [], {}]) {
-    Assert.throws(() => waitForObserverTopic(
-        "message", {checkFn}), /TypeError/);
-  }
-
-  let data1 = {"fo": "bar"};
-  let data2 = {"foo": "bar"};
-
-  for (let checkFn of [null, undefined, (subject, data) => data == data2]) {
-    let expected_data = (checkFn == null) ? data1 : data2;
-
-    let sent = waitForObserverTopic("message");
-    Services.obs.notifyObservers(this, "message", data1);
-    Services.obs.notifyObservers(this, "message", data2);
-    let result = await sent;
-    equal(expected_data, result.data);
-  }
-});
--- a/testing/marionette/transport.js
+++ b/testing/marionette/transport.js
@@ -5,27 +5,24 @@
 "use strict";
 
 /* global Pipe, ScriptableInputStream */
 
 const CC = Components.Constructor;
 
 ChromeUtils.import("resource://gre/modules/Services.jsm");
 ChromeUtils.import("resource://gre/modules/EventEmitter.jsm");
-const {
-  StreamUtils,
-} = ChromeUtils.import("chrome://marionette/content/stream-utils.js", {});
-const {
-  BulkPacket,
-  JSONPacket,
-  Packet,
-} = ChromeUtils.import("chrome://marionette/content/packets.js", {});
-const {
-  executeSoon,
-} = ChromeUtils.import("chrome://marionette/content/sync.js", {});
+const {StreamUtils} =
+    ChromeUtils.import("chrome://marionette/content/stream-utils.js", {});
+const {Packet, JSONPacket, BulkPacket} =
+    ChromeUtils.import("chrome://marionette/content/packets.js", {});
+
+const executeSoon = function(func) {
+  Services.tm.dispatchToMainThread(func);
+};
 
 const flags = {wantVerbose: false, wantLogging: false};
 
 const dumpv =
   flags.wantVerbose ?
   function(msg) { dump(msg + "\n"); } :
   function() {};