Bug 852847 - Part 2: Do things later in our browser-element tests, thus avoiding doing things before the browser-element machinery has loaded. r=pwang a=tef+
☠☠ backed out by a41f9308a042 ☠ ☠
authorJustin Lebar <justin.lebar@gmail.com>
Wed, 27 Mar 2013 07:14:00 +0100
changeset 119132 2449b8d0f7e641831bea91d8faff186a1a3c8a55
parent 119131 c5d79650594275eca07f6a4dc2dbf67dd4edfa41
child 119133 09470bb4b4a74ddd26604f87da9d84311ebae973
push id689
push userjosh@joshmatthews.net
push dateFri, 19 Apr 2013 09:22:05 +0000
reviewerspwang, tef
bugs852847
milestone18.0
Bug 852847 - Part 2: Do things later in our browser-element tests, thus avoiding doing things before the browser-element machinery has loaded. r=pwang a=tef+
dom/browser-element/mochitest/browserElementTestHelpers.js
dom/browser-element/mochitest/browserElement_Alert.js
dom/browser-element/mochitest/browserElement_AlertInFrame.js
dom/browser-element/mochitest/browserElement_AppFramePermission.js
dom/browser-element/mochitest/browserElement_AppWindowNamespace.js
dom/browser-element/mochitest/browserElement_Auth.js
dom/browser-element/mochitest/browserElement_BackForward.js
dom/browser-element/mochitest/browserElement_BadScreenshot.js
dom/browser-element/mochitest/browserElement_BrowserWindowNamespace.js
dom/browser-element/mochitest/browserElement_Close.js
dom/browser-element/mochitest/browserElement_CloseApp.js
dom/browser-element/mochitest/browserElement_CloseFromOpener.js
dom/browser-element/mochitest/browserElement_ContextmenuEvents.js
dom/browser-element/mochitest/browserElement_CookiesNotThirdParty.js
dom/browser-element/mochitest/browserElement_DOMRequestError.js
dom/browser-element/mochitest/browserElement_DataURI.js
dom/browser-element/mochitest/browserElement_ErrorSecurity.js
dom/browser-element/mochitest/browserElement_ExposableURI.js
dom/browser-element/mochitest/browserElement_FirstPaint.js
dom/browser-element/mochitest/browserElement_ForwardName.js
dom/browser-element/mochitest/browserElement_FrameWrongURI.js
dom/browser-element/mochitest/browserElement_GetScreenshot.js
dom/browser-element/mochitest/browserElement_Iconchange.js
dom/browser-element/mochitest/browserElement_KeyEvents.js
dom/browser-element/mochitest/browserElement_LoadEvents.js
dom/browser-element/mochitest/browserElement_NextPaint.js
dom/browser-element/mochitest/browserElement_OpenMixedProcess.js
dom/browser-element/mochitest/browserElement_OpenNamed.js
dom/browser-element/mochitest/browserElement_OpenWindow.js
dom/browser-element/mochitest/browserElement_OpenWindowDifferentOrigin.js
dom/browser-element/mochitest/browserElement_OpenWindowInFrame.js
dom/browser-element/mochitest/browserElement_OpenWindowRejected.js
dom/browser-element/mochitest/browserElement_OpenWindowRejected2.js
dom/browser-element/mochitest/browserElement_PromptCheck.js
dom/browser-element/mochitest/browserElement_PromptConfirm.js
dom/browser-element/mochitest/browserElement_PurgeHistory.js
dom/browser-element/mochitest/browserElement_Reload.js
dom/browser-element/mochitest/browserElement_ReloadPostRequest.js
dom/browser-element/mochitest/browserElement_RemoveBrowserElement.js
dom/browser-element/mochitest/browserElement_ScrollEvent.js
dom/browser-element/mochitest/browserElement_SecurityChange.js
dom/browser-element/mochitest/browserElement_SendEvent.js
dom/browser-element/mochitest/browserElement_SetVisible.js
dom/browser-element/mochitest/browserElement_SetVisibleFrames.js
dom/browser-element/mochitest/browserElement_SetVisibleFrames2.js
dom/browser-element/mochitest/browserElement_Stop.js
dom/browser-element/mochitest/browserElement_TargetBlank.js
dom/browser-element/mochitest/browserElement_TargetTop.js
dom/browser-element/mochitest/browserElement_Titlechange.js
dom/browser-element/mochitest/browserElement_TopBarrier.js
dom/browser-element/mochitest/browserElement_XFrameOptions.js
dom/browser-element/mochitest/browserElement_XFrameOptionsAllowFrom.js
dom/browser-element/mochitest/browserElement_XFrameOptionsDeny.js
dom/browser-element/mochitest/browserElement_XFrameOptionsSameOrigin.js
dom/browser-element/mochitest/createNewTest.py
dom/browser-element/mochitest/file_browserElement_AlertInFrame_Inner.html
dom/browser-element/mochitest/file_browserElement_BrowserWindowNamespace.html
--- a/dom/browser-element/mochitest/browserElementTestHelpers.js
+++ b/dom/browser-element/mochitest/browserElementTestHelpers.js
@@ -1,153 +1,133 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Helpers for managing the browser frame preferences.
 "use strict";
 
+function _getPath() {
+  return window.location.pathname
+               .substring(0, window.location.pathname.lastIndexOf('/'))
+               .replace("/priority", "");
+}
+
 const browserElementTestHelpers = {
   _getBoolPref: function(pref) {
     try {
       return SpecialPowers.getBoolPref(pref);
     }
     catch (e) {
       return undefined;
     }
   },
 
-  _setBoolPref: function(pref, value) {
-    if (value !== undefined) {
-      SpecialPowers.setBoolPref(pref, value);
-    }
-    else {
-      SpecialPowers.clearUserPref(pref);
-    }
-  },
-
-  _getCharPref: function(pref) {
-    try {
-      return SpecialPowers.getCharPref(pref);
-    }
-    catch (e) {
-      return undefined;
+  _setPref: function(pref, value) {
+    this.lockTestReady();
+    if (value !== undefined && value !== null) {
+      SpecialPowers.pushPrefEnv({'set': [[pref, value]]}, this.unlockTestReady.bind(this));
+    } else {
+      SpecialPowers.pushPrefEnv({'clear': [[pref]]}, this.unlockTestReady.bind(this));
     }
   },
 
-  _setCharPref: function(pref, value) {
-    if (value !== undefined) {
-      SpecialPowers.setCharPref(pref, value);
-    }
-    else {
-      SpecialPowers.clearUserPref(pref);
+  _testReadyLockCount: 0,
+  _firedTestReady: false,
+  lockTestReady: function() {
+    this._testReadyLockCount++;
+  },
+
+  unlockTestReady: function() {
+    this._testReadyLockCount--;
+    if (this._testReadyLockCount == 0 && !this._firedTestReady) {
+      this._firedTestReady = true;
+      dispatchEvent(new Event("testready"));
     }
   },
 
-  getEnabledPref: function() {
-    return this._getBoolPref('dom.mozBrowserFramesEnabled');
+  enableProcessPriorityManager: function() {
+    this._setPref('dom.ipc.processPriorityManager.testMode', true);
+    this._setPref('dom.ipc.processPriorityManager.enabled', true);
   },
 
   setEnabledPref: function(value) {
-    this._setBoolPref('dom.mozBrowserFramesEnabled', value);
-  },
-
-  getOOPDisabledPref: function() {
-    return this._getBoolPref('dom.ipc.tabs.disabled');
-  },
-
-  setOOPDisabledPref: function(value) {
-    this._setBoolPref('dom.ipc.tabs.disabled', value);
+    this._setPref('dom.mozBrowserFramesEnabled', value);
   },
 
   getOOPByDefaultPref: function() {
     return this._getBoolPref("dom.ipc.browser_frames.oop_by_default");
   },
 
-  setOOPByDefaultPref: function(value) {
-    return this._setBoolPref("dom.ipc.browser_frames.oop_by_default", value);
-  },
-
-  getIPCSecurityDisabledPref: function() {
-    return this._getBoolPref("network.disable.ipc.security");
-  },
-
-  setIPCSecurityDisabledPref: function(value) {
-    return this._setBoolPref("network.disable.ipc.security", value);
-  },
-
-  getPageThumbsEnabledPref: function() {
-    return this._getBoolPref('browser.pageThumbs.enabled');
-  },
-
-  setPageThumbsEnabledPref: function(value) {
-    this._setBoolPref('browser.pageThumbs.enabled', value);
-  },
-
   addPermission: function() {
     SpecialPowers.addPermission("browser", true, document);
     this.tempPermissions.push(location.href)
   },
 
   removeAllTempPermissions: function() {
     for(var i = 0; i < this.tempPermissions.length; i++) {
       SpecialPowers.removePermission("browser", this.tempPermissions[i]);
     }
   },
 
   addPermissionForUrl: function(url) {
     SpecialPowers.addPermission("browser", true, url);
     this.tempPermissions.push(url);
   },
 
-  restoreOriginalPrefs: function() {
-    this.setEnabledPref(this.origEnabledPref);
-    this.setOOPDisabledPref(this.origOOPDisabledPref);
-    this.setOOPByDefaultPref(this.origOOPByDefaultPref);
-    this.setPageThumbsEnabledPref(this.origPageThumbsEnabledPref);
-    this.setIPCSecurityDisabledPref(this.origIPCSecurityPref);
-    this.removeAllTempPermissions();
-  },
-
-  'origEnabledPref': null,
-  'origOOPDisabledPref': null,
-  'origOOPByDefaultPref': null,
-  'origPageThumbsEnabledPref': null,
-  'origIPCSecurityPref': null,
   'tempPermissions': [],
 
   // Some basically-empty pages from different domains you can load.
-  'emptyPage1': 'http://example.com' +
-                window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) +
-                '/file_empty.html',
-  'emptyPage2': 'http://example.org' +
-                window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) +
-                '/file_empty.html',
-  'emptyPage3': 'http://test1.example.org' +
-                window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) +
-                '/file_empty.html',
-  'focusPage': 'http://example.org' +
-                window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) +
-                '/file_focus.html',
+  'emptyPage1': 'http://example.com' + _getPath() + '/file_empty.html',
+  'emptyPage2': 'http://example.org' + _getPath() + '/file_empty.html',
+  'emptyPage3': 'http://test1.example.org' + _getPath() + '/file_empty.html',
+  'focusPage': 'http://example.org' + _getPath() + '/file_focus.html',
 };
 
-browserElementTestHelpers.origEnabledPref = browserElementTestHelpers.getEnabledPref();
-browserElementTestHelpers.origOOPDisabledPref = browserElementTestHelpers.getOOPDisabledPref();
-browserElementTestHelpers.origOOPByDefaultPref = browserElementTestHelpers.getOOPByDefaultPref();
-browserElementTestHelpers.origPageThumbsEnabledPref = browserElementTestHelpers.getPageThumbsEnabledPref();
-browserElementTestHelpers.origIPCSecurityPref = browserElementTestHelpers.getIPCSecurityDisabledPref();
-
-// Disable tab view; it seriously messes us up.
-browserElementTestHelpers.setPageThumbsEnabledPref(false);
+// Set some prefs:
+//
+//  * browser.pageThumbs.enabled: false
+//
+//    Disable tab view; it seriously messes us up.
+//
+//  * dom.ipc.browser_frames.oop_by_default
+//
+//    Enable or disable OOP-by-default depending on the test's filename.  You
+//    can still force OOP on or off with <iframe mozbrowser remote=true/false>,
+//    at least until bug 756376 lands.
+//
+//  * dom.ipc.tabs.disabled: false
+//
+//    Allow us to create OOP frames.  Even if they're not the default, some
+//    "in-process" tests create OOP frames.
+//
+//  * network.disable.ipc.security: true
+//
+//    Disable the networking security checks; our test harness just tests
+//    browser elements without sticking them in apps, and the security checks
+//    dislike that.
+//
+//    Unfortunately setting network.disable.ipc.security to false before the
+//    child process(es) created by this test have shut down can cause us to
+//    assert and kill the child process.  That doesn't cause the tests to fail,
+//    but it's still scary looking.  So we just set the pref to true and never
+//    pop that value.  We'll rely on the tests which test IPC security to set
+//    it to false.
 
-// Enable or disable OOP-by-default depending on the test's filename.  You can
-// still force OOP on or off with <iframe mozbrowser remote=true/false>, at
-// least until bug 756376 lands.
-var oop = location.pathname.indexOf('_inproc_') == -1;
-browserElementTestHelpers.setOOPByDefaultPref(oop);
-browserElementTestHelpers.setOOPDisabledPref(false);
+(function() {
+  var oop = location.pathname.indexOf('_inproc_') == -1;
 
-// Disable the networking security checks; our test harness just tests browser elements
-// without sticking them in apps, and the security checks dislike that.
-browserElementTestHelpers.setIPCSecurityDisabledPref(true);
+  browserElementTestHelpers.lockTestReady();
+  SpecialPowers.setBoolPref("network.disable.ipc.security", true);
+  SpecialPowers.pushPrefEnv({set: [["browser.pageThumbs.enabled", false],
+                                   ["dom.ipc.browser_frames.oop_by_default", oop],
+                                   ["dom.ipc.tabs.disabled", false]]},
+                            browserElementTestHelpers.unlockTestReady.bind(browserElementTestHelpers));
+})();
 
 addEventListener('unload', function() {
-  browserElementTestHelpers.restoreOriginalPrefs();
+  browserElementTestHelpers.removeAllTempPermissions();
 });
+
+// Wait for the load event before unlocking the test-ready event.
+browserElementTestHelpers.lockTestReady();
+addEventListener('load', function() {
+  SimpleTest.executeSoon(browserElementTestHelpers.unlockTestReady.bind(browserElementTestHelpers));
+});
--- a/dom/browser-element/mochitest/browserElement_Alert.js
+++ b/dom/browser-element/mochitest/browserElement_Alert.js
@@ -1,24 +1,23 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Test that alert works.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 var numPendingChildTests = 0;
 var iframe;
 var mm;
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   document.body.appendChild(iframe);
 
   mm = SpecialPowers.getBrowserFrameMessageManager(iframe);
   mm.addMessageListener('test-success', function(msg) {
     numPendingChildTests--;
     ok(true, SpecialPowers.wrap(msg).json);
@@ -154,10 +153,9 @@ function waitForPendingTests(next) {
     SimpleTest.executeSoon(function() { waitForPendingTests(next); });
     return;
   }
 
   prevNumPendingTests = null;
   next();
 }
 
-runTest();
-
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_AlertInFrame.js
+++ b/dom/browser-element/mochitest/browserElement_AlertInFrame.js
@@ -1,25 +1,24 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Test that alert works from inside an <iframe> inside an <iframe mozbrowser>.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowsershowmodalprompt', function(e) {
     is(e.detail.message, 'Hello');
     SimpleTest.finish();
   });
 
   iframe.src = 'file_browserElement_AlertInFrame.html';
   document.body.appendChild(iframe);
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_AppFramePermission.js
+++ b/dom/browser-element/mochitest/browserElement_AppFramePermission.js
@@ -1,15 +1,17 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 777384 - Test mozapp permission.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function makeAllAppsLaunchable() {
   var Webapps = {};
   SpecialPowers.wrap(Components).utils.import("resource://gre/modules/Webapps.jsm", Webapps);
   var appRegistry = SpecialPowers.wrap(Webapps.DOMApplicationRegistry);
 
   var originalValue = appRegistry.allAppsLaunchable;
   appRegistry.allAppsLaunchable = true;
@@ -32,21 +34,18 @@ function testAppElement(expectAnApp, cal
     is(e.detail.message == 'app', expectAnApp, e.detail.message);
     SimpleTest.executeSoon(callback);
   });
   document.body.appendChild(iframe);
   iframe.src = 'http://example.org/tests/dom/browser-element/mochitest/file_browserElement_AppFramePermission.html';
 }
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   SpecialPowers.addPermission("embed-apps", true, document);
   testAppElement(true, function() {
     SpecialPowers.removePermission("embed-apps", document);
     testAppElement(false, function() {
       SimpleTest.finish();
     });
   });
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_AppWindowNamespace.js
+++ b/dom/browser-element/mochitest/browserElement_AppWindowNamespace.js
@@ -1,22 +1,21 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 780351 - Test that mozapp divides the window name namespace.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
+// Permission to embed an app.
+SpecialPowers.addPermission("embed-apps", true, document);
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-  // Permission to embed an app.
-  SpecialPowers.addPermission("embed-apps", true, document);
-
   var iframe1 = document.createElement('iframe');
   iframe1.mozbrowser = true;
   iframe1.setAttribute('mozapp', 'http://example.org/manifest.webapp');
 
   // Two mozapp frames for different apps with the same code both do the same
   // window.open("foo", "bar") call.  We should get two mozbrowseropenwindow
   // events.
 
@@ -39,9 +38,9 @@ function runTest() {
       iframe2.src = 'http://example.com/tests/dom/browser-element/mochitest/file_browserElement_AppWindowNamespace.html';
     });
   });
 
   document.body.appendChild(iframe1);
   iframe1.src = 'http://example.org/tests/dom/browser-element/mochitest/file_browserElement_AppWindowNamespace.html';
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_Auth.js
+++ b/dom/browser-element/mochitest/browserElement_Auth.js
@@ -1,26 +1,25 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Test that auth prompt works.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function testFail(msg) {
   ok(false, JSON.stringify(msg));
 }
 
 var iframe;
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   document.body.appendChild(iframe);
 
   // Wait for the initial load to finish, then navigate the page, then start test
   // by loading SJS with http 401 response.
   iframe.addEventListener('mozbrowserloadend', function loadend() {
     iframe.removeEventListener('mozbrowserloadend', loadend);
@@ -157,9 +156,9 @@ function testFinish() {
 
   var pwmgr = SpecialPowers.Cc["@mozilla.org/login-manager;1"]
     .getService(SpecialPowers.Ci.nsILoginManager);
   pwmgr.removeAllLogins();
 
   SimpleTest.finish();
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_BackForward.js
+++ b/dom/browser-element/mochitest/browserElement_BackForward.js
@@ -1,31 +1,30 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 741755 - Test that canGo{Back,Forward} and go{Forward,Back} work with
 // <iframe mozbrowser>.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 var iframe;
 function addOneShotIframeEventListener(event, fn) {
   function wrapper(e) {
     iframe.removeEventListener(event, wrapper);
     fn(e);
   };
 
   iframe.addEventListener(event, wrapper);
 }
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   addOneShotIframeEventListener('mozbrowserloadend', function() {
     SimpleTest.executeSoon(test2);
   });
 
   iframe.src = browserElementTestHelpers.emptyPage1;
@@ -92,9 +91,9 @@ function test5() {
 function test6() {
   addOneShotIframeEventListener('mozbrowserlocationchange', function(e) {
     is(e.detail, browserElementTestHelpers.emptyPage1);
     checkCanGoBackAndForward(false, true, SimpleTest.finish);
   });
   iframe.goBack();
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_BadScreenshot.js
+++ b/dom/browser-element/mochitest/browserElement_BadScreenshot.js
@@ -1,16 +1,18 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 800170 - Test that we get errors when we pass bad arguments to
 // mozbrowser's getScreenshot.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 var iframe;
 var numPendingTests = 0;
 
 // Call iframe.getScreenshot with the given args.  If expectSuccess is true, we
 // expect the screenshot's onsuccess handler to fire.  Otherwise, we expect
 // getScreenshot() to throw an exception.
 function checkScreenshotResult(expectSuccess, args) {
@@ -38,19 +40,16 @@ function checkScreenshotResult(expectSuc
     numPendingTests--;
     if (numPendingTests == 0) {
       SimpleTest.finish();
     }
   };
 }
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   document.body.appendChild(iframe);
   iframe.src = 'data:text/html,<html>' +
     '<body style="background:green">hello</body></html>';
 
   iframe.addEventListener('mozbrowserfirstpaint', function() {
     // This one should succeed.
@@ -65,9 +64,9 @@ function runTest() {
     checkScreenshotResult(false, [100, -1]);
 
     if (numPendingTests == 0) {
       SimpleTest.finish();
     }
   });
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_BrowserWindowNamespace.js
+++ b/dom/browser-element/mochitest/browserElement_BrowserWindowNamespace.js
@@ -3,21 +3,20 @@
 
 // Bug 780351 - Test that mozbrowser does /not/ divide the window name namespace.
 // Multiple mozbrowsers inside the same app are like multiple browser tabs;
 // they share a window name namespace.
 
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe1 = document.createElement('iframe');
   iframe1.mozbrowser = true;
 
   // Two mozbrowser frames with the same code both do the same
   // window.open("foo", "bar") call.  We should only get one
   // mozbrowseropenwindow event.
 
   iframe1.addEventListener('mozbrowseropenwindow', function(e) {
@@ -46,9 +45,9 @@ function runTest() {
       iframe2.src = 'file_browserElement_BrowserWindowNamespace.html#2';
     });
   });
 
   document.body.appendChild(iframe1);
   iframe1.src = 'file_browserElement_BrowserWindowNamespace.html#1';
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_Close.js
+++ b/dom/browser-element/mochitest/browserElement_Close.js
@@ -1,25 +1,24 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Test that window.close() works.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   document.body.appendChild(iframe);
 
   iframe.addEventListener("mozbrowserclose", function(e) {
     ok(true, "got mozbrowserclose event.");
     SimpleTest.finish();
   });
 
   iframe.src = "data:text/html,<html><body><script>window.close()</scr"+"ipt></body></html>";
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_CloseApp.js
+++ b/dom/browser-element/mochitest/browserElement_CloseApp.js
@@ -1,26 +1,25 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 789392 - Test that apps frames can trigger mozbrowserclose by calling
 // window.close(), but browser frames cannot.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
+SpecialPowers.addPermission("embed-apps", true, window.document);
+
+addEventListener('unload', function() {
+  SpecialPowers.removePermission("embed-apps", window.document);
+});
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-  SpecialPowers.addPermission("embed-apps", true, window.document);
-
-  addEventListener('unload', function() {
-    SpecialPowers.removePermission("embed-apps", window.document);
-  });
-
   // Our app frame and browser frame load the same content.  That content calls
   // window.close() and then alert().  We should get a mozbrowserclose event on
   // the app frame before the mozbrowsershowmodalprompt, but not on the browser
   // frame.
 
   var appFrame = document.createElement('iframe');
   appFrame.mozbrowser = true;
   appFrame.setAttribute('mozapp', 'http://example.org/manifest.webapp');
@@ -63,9 +62,11 @@ function runTest() {
   appFrame.src = 'http://example.org/tests/dom/browser-element/mochitest/file_browserElement_CloseApp.html';
   browserFrame.src = 'http://example.org/tests/dom/browser-element/mochitest/file_browserElement_CloseApp.html';
 }
 
 // The test harness sets dom.allow_scripts_to_close_windows to true (as of
 // writing, anyway).  But that means that browser tabs can close themselves,
 // which is what we want to test /can't/ happen!   For the purposes of this
 // test (and normal browser operation), this pref should be false.
-SpecialPowers.pushPrefEnv({'set': [['dom.allow_scripts_to_close_windows', false]]}, runTest);
+addEventListener('testready', function() {
+  SpecialPowers.pushPrefEnv({'set': [['dom.allow_scripts_to_close_windows', false]]}, runTest);
+});
--- a/dom/browser-element/mochitest/browserElement_CloseFromOpener.js
+++ b/dom/browser-element/mochitest/browserElement_CloseFromOpener.js
@@ -1,20 +1,19 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 764718 - Test that window.close() works from the opener window.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     ok(true, "got openwindow event.");
     document.body.appendChild(e.detail.frameElement);
 
     e.detail.frameElement.addEventListener("mozbrowserclose", function(e) {
@@ -26,9 +25,9 @@ function runTest() {
 
   document.body.appendChild(iframe);
 
   // file_browserElement_CloseFromOpener opens a new window and then calls
   // close() on it.
   iframe.src = "file_browserElement_CloseFromOpener.html";
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_ContextmenuEvents.js
+++ b/dom/browser-element/mochitest/browserElement_ContextmenuEvents.js
@@ -1,11 +1,13 @@
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 var iframeScript = function() {
 
   content.fireContextMenu = function(element) {
     var ev = content.document.createEvent('HTMLEvents');
     ev.initEvent('contextmenu', true, false);
     element.dispatchEvent(ev);
   };
@@ -24,20 +26,16 @@ var iframeScript = function() {
   content.fireContextMenu(content.document.getElementById('menu2-trigger'));
 }
 
 var trigger1 = function() {
   content.fireContextMenu(content.document.getElementById('menu1-trigger'));
 };
 
 function runTest() {
-
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe1 = document.createElement('iframe');
   iframe1.mozbrowser = true;
   document.body.appendChild(iframe1);
   iframe1.src = 'data:text/html,<html>' +
     '<body>' +
     '<menu type="context" id="menu1" label="firstmenu">' +
       '<menuitem label="foo" onclick="window.ctxCallbackFired(\'foo\')"></menuitem>' +
       '<menuitem label="bar" onclick="throw(\'anerror\')"></menuitem>' +
@@ -136,9 +134,9 @@ function runTest() {
       mm.loadFrameScript('data:,(' + iframeScript.toString() + ')();', false);
     }
   }
 
   iframe1.addEventListener('mozbrowsercontextmenu', iframeContextmenuHandler);
   iframe1.addEventListener('mozbrowserloadend', iframeLoadedHandler);
 }
 
-addEventListener('load', function() { SimpleTest.executeSoon(runTest); });
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_CookiesNotThirdParty.js
+++ b/dom/browser-element/mochitest/browserElement_CookiesNotThirdParty.js
@@ -1,21 +1,20 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 806127 - Test that cookies set by <iframe mozbrowser> are not considered
 // third-party.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   const innerPage = 'http://example.com/tests/dom/browser-element/mochitest/file_browserElement_CookiesNotThirdParty.html';
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowsershowmodalprompt', function(e) {
     if (e.detail.message == 'next') {
       iframe.src = innerPage + '?step=2';
@@ -42,9 +41,11 @@ function runTest() {
   // fact that we've disabled third-party cookies) and alert('success:') or
   // alert('failure:'), as appropriate.  Finally, the page will
   // alert('finish');
   iframe.src = innerPage;
   document.body.appendChild(iframe);
 }
 
 // Disable third-party cookies for this test.
-SpecialPowers.pushPrefEnv({'set': [['network.cookie.cookieBehavior', 1]]}, runTest);
+addEventListener('testready', function() {
+  SpecialPowers.pushPrefEnv({'set': [['network.cookie.cookieBehavior', 1]]}, runTest);
+});
--- a/dom/browser-element/mochitest/browserElement_DOMRequestError.js
+++ b/dom/browser-element/mochitest/browserElement_DOMRequestError.js
@@ -1,21 +1,20 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Test if DOMRequest returned by an iframe gets an error callback when
 // the iframe is not in the DOM.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe1 = document.createElement('iframe');
   iframe1.mozbrowser = true;
   iframe1.src = 'data:text/html,<html>' +
     '<body style="background:green">hello</body></html>';
   document.body.appendChild(iframe1);
 
   function testIframe(beforeRun, isErrorExpected, nextTest) {
     return function() {
@@ -56,9 +55,9 @@ function runTest() {
     }, true, test3);
     var test1 = testIframe(null, false, test2);
     SimpleTest.executeSoon(test1);
   }
 
   iframe1.addEventListener('mozbrowserloadend', iframeLoadedHandler);
 }
 
-addEventListener('load', function() { SimpleTest.executeSoon(runTest); });
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_DataURI.js
+++ b/dom/browser-element/mochitest/browserElement_DataURI.js
@@ -1,20 +1,19 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Test that data: URIs work with mozbrowserlocationchange events.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe1 = document.createElement('iframe');
   iframe1.mozbrowser = true;
   iframe1.id = 'iframe1';
   iframe1.addEventListener('mozbrowserloadend', function if1_loadend() {
     iframe1.removeEventListener('mozbrowserloadend', if1_loadend);
     ok(true, 'Got first loadend event.');
     SimpleTest.executeSoon(runTest2);
   });
@@ -61,9 +60,9 @@ function runTest2() {
 
   iframe1.src = 'data:text/html,1';
 
   // Load something into iframe2 to check that it doesn't trigger a
   // locationchange for our iframe1 listener.
   iframe2.src = browserElementTestHelpers.emptyPage2;
 }
 
-addEventListener('load', function() { SimpleTest.executeSoon(runTest); });
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_ErrorSecurity.js
+++ b/dom/browser-element/mochitest/browserElement_ErrorSecurity.js
@@ -1,27 +1,26 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 764718 - Test that mozbrowsererror works for a security error.
 
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener("mozbrowsererror", function(e) {
     ok(true, "Got mozbrowsererror event.");
     ok(e.detail.type, "Event's detail has a |type| param.");
     SimpleTest.finish();
   });
 
   iframe.src = "https://expired.example.com";
   document.body.appendChild(iframe);
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_ExposableURI.js
+++ b/dom/browser-element/mochitest/browserElement_ExposableURI.js
@@ -1,20 +1,21 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 795317: Test that the browser element sanitizes its URIs by removing the
 // "unexposable" parts before sending them in the locationchange event.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 var iframe;
 
-
 function testPassword() {
   function locationchange(e) {
     var uri = e.detail;
     is(uri, 'http://mochi.test:8888/tests/dom/browser-element/mochitest/file_empty.html',
        "Username and password shouldn't be exposed in uri.");
     SimpleTest.finish();
   }
 
@@ -40,18 +41,15 @@ function testWyciwyg() {
   }
 
   // file_wyciwyg.html calls document.write() to create a wyciwyg channel.
   iframe.src = 'file_wyciwyg.html';
   iframe.addEventListener('mozbrowserlocationchange', locationchange);
 }
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   document.body.appendChild(iframe);
   testWyciwyg();
 }
 
-addEventListener('load', function() { SimpleTest.executeSoon(runTest); });
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_FirstPaint.js
+++ b/dom/browser-element/mochitest/browserElement_FirstPaint.js
@@ -1,20 +1,19 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 787378 - Add mozbrowserfirstpaint event.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   var gotFirstPaint = false;
   var gotFirstLocationChange = false;
   iframe.addEventListener('mozbrowserfirstpaint', function(e) {
     ok(!gotFirstPaint, "Got only one first paint.");
     gotFirstPaint = true;
@@ -36,9 +35,9 @@ function runTest() {
     }
   });
 
   document.body.appendChild(iframe);
 
   iframe.src = browserElementTestHelpers.emptyPage1;
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_ForwardName.js
+++ b/dom/browser-element/mochitest/browserElement_ForwardName.js
@@ -2,21 +2,20 @@
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 781320 - Test that the name in <iframe mozbrowser name="foo"> is
 // forwarded down to remote mozbrowsers.
 
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   iframe.setAttribute('name', 'foo');
 
   iframe.addEventListener("mozbrowseropenwindow", function(e) {
     ok(false, 'Got mozbrowseropenwindow, but should not have.');
   });
 
@@ -36,9 +35,9 @@ function runTest() {
   document.body.appendChild(iframe);
 
   // This file does window.open('file_browserElement_ForwardName.html#finish',
   // 'foo');  That should open in the curent window, because the window should
   // be named foo.
   iframe.src = 'file_browserElement_ForwardName.html';
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_FrameWrongURI.js
+++ b/dom/browser-element/mochitest/browserElement_FrameWrongURI.js
@@ -1,20 +1,19 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 804446 - Test that window.open(javascript:..) works with <iframe mozbrowser>.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframeJS = document.createElement('iframe');
   iframeJS.mozbrowser = true;
 
   iframeJS.addEventListener('mozbrowserloadstart', function(e) {
     ok(false, "This should not happen!");
   });
 
   iframeJS.addEventListener('mozbrowserloadend', function(e) {
@@ -45,9 +44,9 @@ function runTest() {
       ok(false, "Got invalid message: " + e.detail.message);
     }
   });
 
   iframe.src = 'file_browserElement_FrameWrongURI.html';
   document.body.appendChild(iframe);
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_GetScreenshot.js
+++ b/dom/browser-element/mochitest/browserElement_GetScreenshot.js
@@ -88,9 +88,9 @@ function runTest() {
         return screenshotArrayBuffer.byteLength != 0;
       });
     }
   }
 
   iframe1.addEventListener('mozbrowserloadend', iframeLoadedHandler);
 }
 
-addEventListener('load', function() { SimpleTest.executeSoon(runTest); });
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_Iconchange.js
+++ b/dom/browser-element/mochitest/browserElement_Iconchange.js
@@ -101,9 +101,9 @@ function runTest() {
 
   iframe1.src = createHtml(createLink('myicon'));
   // We should not recieve icon change events for either of the below iframes
   iframe2.src = createHtml(createLink('myicon'));
   iframe3.src = createHtml(createLink('myicon'));
 
 }
 
-addEventListener('load', function() { SimpleTest.executeSoon(runTest); });
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_KeyEvents.js
+++ b/dom/browser-element/mochitest/browserElement_KeyEvents.js
@@ -16,45 +16,54 @@ let whitelistedEvents = [
   Ci.nsIDOMKeyEvent.DOM_VK_PAGE_DOWN // Volume down.
 ];
 
 SimpleTest.waitForExplicitFinish();
 
 browserElementTestHelpers.setEnabledPref(true);
 browserElementTestHelpers.addPermission();
 
-var iframe = document.createElement('iframe');
-iframe.mozbrowser = true;
-iframe.src = browserElementTestHelpers.focusPage;
-document.body.appendChild(iframe);
-
 // Number of expected events at which point we will consider the test as done.
 var nbEvents = whitelistedEvents.length * 3;
 
+var iframe;
+var finished = false;
+function runTest() {
+  iframe = document.createElement('iframe');
+  iframe.mozbrowser = true;
+  iframe.src = browserElementTestHelpers.focusPage;
+  document.body.appendChild(iframe);
+
+  SimpleTest.waitForFocus(function() {
+    iframe.focus();
+    SimpleTest.executeSoon(test2);
+  });
+}
+
 function eventHandler(e) {
   ok(((e.type == 'keydown' || e.type == 'keypress' || e.type == 'keyup') &&
       !e.defaultPrevented &&
       (whitelistedEvents.indexOf(e.keyCode) != -1)),
       "[ " + e.type + "] Handled event should be a non prevented key event in the white list.");
 
   nbEvents--;
 
   if (nbEvents == 0) {
     SimpleTest.finish();
     return;
   }
 
-  if (nbEvents < 0) {
+  if (nbEvents < 0 && !finished) {
     ok(false, "got an unexpected event! " + e.type + " " + e.keyCode);
     SimpleTest.finish();
     return;
   }
 }
 
-function runTest() {
+function test2() {
   is(document.activeElement, iframe, "iframe should be focused");
 
   addEventListener('keydown', eventHandler);
   addEventListener('keypress', eventHandler);
   addEventListener('keyup', eventHandler);
 
   // Those event should not be received because not whitelisted.
   synthesizeKey("VK_A", {});
@@ -65,15 +74,12 @@ function runTest() {
 
   // Those events should be received.
   synthesizeKey("VK_F5", {}); // F5 key is going to be canceled by ESC key.
   synthesizeKey("VK_ESCAPE", {});
   synthesizeKey("VK_PAGE_UP", {});   // keypress is ignored because .preventDefault() will be called.
   synthesizeKey("VK_PAGE_DOWN", {}); // keypress is ignored because .preventDefault() will be called.
   synthesizeKey("VK_CONTEXT_MENU", {});
   synthesizeKey("VK_SLEEP", {});
+  finished = true;
 }
 
-SimpleTest.waitForFocus(function() {
-  iframe.focus();
-  SimpleTest.executeSoon(runTest);
-});
-
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_LoadEvents.js
+++ b/dom/browser-element/mochitest/browserElement_LoadEvents.js
@@ -1,21 +1,20 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Test that an iframe with the |mozbrowser| attribute emits mozbrowserloadX
 // events when this page is in the whitelist.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   // Load emptypage1 into the iframe, wait for that to finish loading, then
   // call runTest2.
   //
   // This should trigger loadstart, locationchange, and loadend events.
 
   var seenLoadEnd = false;
   var seenLoadStart = false;
   var seenLocationChange = false;
@@ -110,9 +109,9 @@ function runTest2() {
     }
 
     SimpleTest.finish();
   }
 
   waitForAllCallbacks();
 }
 
-addEventListener('load', function() { SimpleTest.executeSoon(runTest); });
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_NextPaint.js
+++ b/dom/browser-element/mochitest/browserElement_NextPaint.js
@@ -1,20 +1,19 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 808231 - Add mozbrowsernextpaint event.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   document.body.appendChild(iframe);
 
   // Add a first listener that we'll remove shortly after.
   iframe.addNextPaintListener(wrongListener);
 
   var gotFirstNextPaintEvent = false;
@@ -37,9 +36,9 @@ function runTest() {
   iframe.removeNextPaintListener(wrongListener);
   iframe.src = 'file_browserElement_NextPaint.html';
 }
 
 function wrongListener() {
   ok(false, 'first listener should have been removed');
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_OpenMixedProcess.js
+++ b/dom/browser-element/mochitest/browserElement_OpenMixedProcess.js
@@ -14,21 +14,20 @@
 //
 // Since the name of the test determines the OOP-by-default pref, the "inproc"
 // version of this test opens an OOP frame, and the "oop" version opens an
 // in-process frame.  Enjoy.  :)
 
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   // We're going to open a remote frame if OOP off by default.  If OOP is on by
   // default, we're going to open an in-process frame.
   var remote = !browserElementTestHelpers.getOOPByDefaultPref();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   iframe.setAttribute('remote', remote);
 
@@ -99,9 +98,9 @@ function test2(popup, blankScreenshotArr
       }
 
       SimpleTest.executeSoon(function() { test2(popup, blankScreenshot) });
     };
     fr.readAsArrayBuffer(e.target.result);
   };
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_OpenNamed.js
+++ b/dom/browser-element/mochitest/browserElement_OpenNamed.js
@@ -1,23 +1,22 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 742944 - In <iframe mozbrowser>, test that if we call window.open twice
 // with the same name, we get only one mozbrowseropenwindow event.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 var iframe;
 var popupFrame;
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   var gotPopup = false;
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     is(gotPopup, false, 'Should get just one popup.');
     gotPopup = true;
     popupFrame = e.detail.frameElement;
@@ -50,9 +49,9 @@ function test2() {
   popupFrame.addEventListener('mozbrowsershowmodalprompt', function(e) {
     is(e.detail.message, 'success: loaded');
     SimpleTest.finish();
   });
 
   iframe.src = 'file_browserElement_OpenNamed.html?test2';
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_OpenWindow.js
+++ b/dom/browser-element/mochitest/browserElement_OpenWindow.js
@@ -1,20 +1,19 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 742944 - Test that window.open works with <iframe mozbrowser>.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   var gotPopup = false;
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     is(gotPopup, false, 'Should get just one popup.');
     gotPopup = true;
 
@@ -51,9 +50,9 @@ function runTest() {
    *
    * Onload, we fire a few alerts saying "success:REASON" or "failure:REASON".
    * Finally, we fire a "finish" alert, which ends the test.
    */
   iframe.src = 'file_browserElement_Open1.html';
   document.body.appendChild(iframe);
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_OpenWindowDifferentOrigin.js
+++ b/dom/browser-element/mochitest/browserElement_OpenWindowDifferentOrigin.js
@@ -1,20 +1,19 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 769182 - window.open to a different origin should load the page.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     ok(true, 'Got first window.open call');
 
     e.detail.frameElement.addEventListener('mozbrowseropenwindow', function(e) {
       ok(true, 'Got second window.open call');
@@ -34,9 +33,9 @@ function runTest() {
   //   window.open('http://example.com/.../DifferentOrigin.html?2'),
   //
   // which calls alert().
 
   iframe.src = 'http://example.org/tests/dom/browser-element/mochitest/file_browserElement_OpenWindowDifferentOrigin.html?1';
   document.body.appendChild(iframe);
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_OpenWindowInFrame.js
+++ b/dom/browser-element/mochitest/browserElement_OpenWindowInFrame.js
@@ -6,21 +6,20 @@
 // This is basically the same as browserElement_OpenWindow, except that instead
 // of loading file_browserElement_Open1.html directly inside the <iframe
 // mozbrowser>, we load file_browserElement_OpenWindowInFrame.html into the
 // mozbrowser.  OpenWindowInFrame loads file_browserElement_Open1.html inside
 // an iframe.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   var gotPopup = false;
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     is(gotPopup, false, 'Should get just one popup.');
     gotPopup = true;
 
@@ -58,9 +57,9 @@ function runTest() {
    *
    * Onload, we fire a few alerts saying "success:REASON" or "failure:REASON".
    * Finally, we fire a "finish" alert, which ends the test.
    */
   iframe.src = 'file_browserElement_OpenWindowInFrame.html';
   document.body.appendChild(iframe);
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_OpenWindowRejected.js
+++ b/dom/browser-element/mochitest/browserElement_OpenWindowRejected.js
@@ -1,21 +1,20 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 742944 - Do window.open from inside <iframe mozbrowser>.  But then
 // reject the call.  This shouldn't cause problems (crashes, leaks).
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     ok(e.detail.url.indexOf('does_not_exist.html') != -1,
        'Opened URL; got ' + e.detail.url);
     is(e.detail.name, '');
     is(e.detail.features, '');
@@ -36,9 +35,9 @@ function runTest() {
       ok(false, msg);
     }
   });
 
   iframe.src = 'file_browserElement_OpenWindowRejected.html';
   document.body.appendChild(iframe);
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_OpenWindowRejected2.js
+++ b/dom/browser-element/mochitest/browserElement_OpenWindowRejected2.js
@@ -5,21 +5,20 @@
 // reject the call.  This shouldn't cause problems (crashes, leaks).
 //
 // This is the same as OpenWindowRejected, except we "reject" the popup by not
 // adding the iframe element to our DOM, instead of by not calling
 // preventDefault() on the event.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     ok(e.detail.url.indexOf('does_not_exist.html') != -1,
        'Opened URL; got ' + e.detail.url);
     is(e.detail.name, '');
     is(e.detail.features, '');
@@ -40,9 +39,9 @@ function runTest() {
     else {
       ok(false, msg);
     }
   });
 
   iframe.src = 'file_browserElement_OpenWindowRejected.html';
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_PromptCheck.js
+++ b/dom/browser-element/mochitest/browserElement_PromptCheck.js
@@ -2,63 +2,54 @@
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Test that alertCheck (i.e., alert with the opportunity to opt out of future
 // alerts), promptCheck, and confirmCheck work.  We do this by spamming
 // alerts/prompts/confirms from inside an <iframe mozbrowser>.
 //
 // At the moment, we treat alertCheck/promptCheck/confirmCheck just like a
 // normal alert.  But it's different to nsIPrompt!
+
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
-
 browserElementTestHelpers.setEnabledPref(true);
 browserElementTestHelpers.addPermission();
 
-// Test harness sets dom.successive_dialog_time_limit to 0 for some bizarre
-// reason.  That's not normal usage, and it keeps us from testing alertCheck!
-const dialogTimeLimitPrefName = 'dom.successive_dialog_time_limit';
-var oldDialogTimeLimitPref;
-try {
-  oldDialogTimeLimitPref = SpecialPowers.getIntPref(dialogTimeLimitPrefName);
-}
-catch(e) {}
-
-SpecialPowers.setIntPref(dialogTimeLimitPrefName, 10);
-
-var iframe = document.createElement('iframe');
-iframe.mozbrowser = true;
-document.body.appendChild(iframe);
+function runTest()
+{
+  var iframe = document.createElement('iframe');
+  iframe.mozbrowser = true;
+  document.body.appendChild(iframe);
 
-var numPrompts = 0;
-iframe.addEventListener('mozbrowsershowmodalprompt', function(e) {
-  is(e.detail.message, numPrompts, "prompt message");
-  if (numPrompts / 10 < 1) {
-    is(e.detail.promptType, 'alert');
-  }
-  else if (numPrompts / 10 < 2) {
-    is(e.detail.promptType, 'confirm');
-  }
-  else {
-    is(e.detail.promptType, 'prompt');
-  }
-
-  numPrompts++;
-  if (numPrompts == 30) {
-    if (oldDialogTimeLimitPref !== undefined) {
-      SpecialPowers.setIntPref(dialogTimeLimitPrefName, oldDialogTimeLimitPref);
+  var numPrompts = 0;
+  iframe.addEventListener('mozbrowsershowmodalprompt', function(e) {
+    is(e.detail.message, numPrompts, "prompt message");
+    if (numPrompts / 10 < 1) {
+      is(e.detail.promptType, 'alert');
+    }
+    else if (numPrompts / 10 < 2) {
+      is(e.detail.promptType, 'confirm');
     }
     else {
-      SpecialPowers.clearUserPref(dialogTimeLimitPrefName);
+      is(e.detail.promptType, 'prompt');
     }
 
-    SimpleTest.finish();
-  }
-});
+    numPrompts++;
+    if (numPrompts == 30) {
+      SimpleTest.finish();
+    }
+  });
 
-iframe.src =
-  'data:text/html,<html><body><script>\
-    var i = 0; \
-    for (; i < 10; i++) { alert(i); } \
-    for (; i < 20; i++) { confirm(i); } \
-    for (; i < 30; i++) { prompt(i); } \
-   </scr' + 'ipt></body></html>';
+  iframe.src =
+    'data:text/html,<html><body><script>\
+      var i = 0; \
+      for (; i < 10; i++) { alert(i); } \
+      for (; i < 20; i++) { confirm(i); } \
+      for (; i < 30; i++) { prompt(i); } \
+     </scr' + 'ipt></body></html>';
+}
+
+// The test harness sets dom.successive_dialog_time_limit to 0 for some bizarre
+// reason.  That's not normal usage, and it keeps us from testing alertCheck!
+addEventListener('testready', function() {
+  SpecialPowers.pushPrefEnv({'set': [['dom.successive_dialog_time_limit', 10]]}, runTest);
+});
--- a/dom/browser-element/mochitest/browserElement_PromptConfirm.js
+++ b/dom/browser-element/mochitest/browserElement_PromptConfirm.js
@@ -4,21 +4,20 @@
 // Test that prompt and confirm work.  In particular, we're concerned that we
 // get correct return values out of them.
 //
 // We use alert() to communicate the return values of prompt/confirm back to
 // ourselves.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   document.body.appendChild(iframe);
 
   var prompts = [
     {msg: 1, type: 'alert', rv: 42, expected: 'undefined'},
     {msg: 2, type: 'confirm', rv: true, expected: 'true'},
     {msg: 3, type: 'confirm', rv: false, expected: 'false'},
@@ -80,9 +79,9 @@ function runTest() {
       sendVal(confirm("3")); \
       sendVal(confirm("4")); \
       sendVal(prompt("5", "initial")); \
       sendVal(prompt("6", "initial")); \
       sendVal(prompt("7", "initial")); \
     </scr' + 'ipt></body></html>';
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_PurgeHistory.js
+++ b/dom/browser-element/mochitest/browserElement_PurgeHistory.js
@@ -1,31 +1,30 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 807056 - [Browser] Clear History doesn't clear back/forward history in open tabs
 // <iframe mozbrowser>.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 var iframe;
 function addOneShotIframeEventListener(event, fn) {
   function wrapper(e) {
     iframe.removeEventListener(event, wrapper);
     fn(e);
   };
 
   iframe.addEventListener(event, wrapper);
 }
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   addOneShotIframeEventListener('mozbrowserloadend', function() {
     SimpleTest.executeSoon(test2);
   });
 
   iframe.src = browserElementTestHelpers.emptyPage1;
@@ -79,9 +78,9 @@ function test4() {
     purgeHistory(SimpleTest.finish);
   });
 
   SimpleTest.executeSoon(function() {
     iframe.src = browserElementTestHelpers.emptyPage3;
   });
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_Reload.js
+++ b/dom/browser-element/mochitest/browserElement_Reload.js
@@ -1,31 +1,30 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 741717 - Test the reload ability of <iframe mozbrowser>.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 var iframeScript = function() {
   sendAsyncMessage('test:innerHTML', {
     data: XPCNativeWrapper.unwrap(content).document.body.innerHTML
   });
 }
 
 var mm;
 var iframe;
 var loadedEvents = 0;
 var countAcc;
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowserloadend', mozbrowserLoaded);
 
   iframe.src = 'file_bug741717.sjs';
   document.body.appendChild(iframe);
 }
@@ -52,9 +51,9 @@ function iframeBodyRecv(data) {
 
 function mozbrowserLoaded() {
   loadedEvents++;
   mm = SpecialPowers.getBrowserFrameMessageManager(iframe);
   mm.addMessageListener('test:innerHTML', iframeBodyRecv);
   mm.loadFrameScript('data:,(' + iframeScript.toString() + ')();', false);
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_ReloadPostRequest.js
+++ b/dom/browser-element/mochitest/browserElement_ReloadPostRequest.js
@@ -1,16 +1,18 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 793644, fire an event when attempting to reloads browser element after
 // POST respest.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 var iframe;
 var gotConfirmRepost = false;
 var doRepost = true;
 var timer;
 var isPostRequestSubmitted;
 
 function getExpectedStrings() {
@@ -67,19 +69,16 @@ function pageLoadDone() {
     // We don't expect browserelement to reload; use a timer to make sure
     // it is not reloaded.
     iframe.addEventListener('mozbrowserloadend', failBecauseReloaded);
   }
   iframe.reload();
 }
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   isPostRequestSubmitted = false;
   iframe.src = 'file_post_request.html';
   document.body.appendChild(iframe);
 
   iframe.addEventListener('mozbrowserloadend', pageLoadDone);
@@ -109,9 +108,9 @@ function runTest() {
           iframe.removeEventListener('mozbrowserloadend', failBecauseReloaded);
           SimpleTest.finish();
         }, 1000);
       }
     }
   });
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_RemoveBrowserElement.js
+++ b/dom/browser-element/mochitest/browserElement_RemoveBrowserElement.js
@@ -2,31 +2,30 @@
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 787517: Remove iframe in the handler of showmodalprompt. This shouldn't
 // cause an exception to be thrown.
 
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   document.body.appendChild(iframe);
 
   iframe.addEventListener("mozbrowsershowmodalprompt", function(e) {
     document.body.removeChild(iframe);
     SimpleTest.executeSoon(function() {
       ok(true);
       SimpleTest.finish();
     });
   });
 
   iframe.src = "data:text/html,<html><body><script>alert(\"test\")</script>" +
                "</body></html>";
 }
 
-runTest();
+addEventListener('testready', runTest);
 
--- a/dom/browser-element/mochitest/browserElement_ScrollEvent.js
+++ b/dom/browser-element/mochitest/browserElement_ScrollEvent.js
@@ -1,28 +1,27 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Test that scroll event bubbles up.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   document.body.appendChild(iframe);
 
   iframe.addEventListener("mozbrowserscroll", function(e) {
     ok(true, "got mozbrowserscroll event.");
     ok(e.detail, "event.detail is not null.");
     ok(e.detail.top === 4000, "top position is correct.");
     ok(e.detail.left === 4000, "left position is correct.");
     SimpleTest.finish();
   });
 
   iframe.src = "data:text/html,<html><body style='min-height: 5000px; min-width: 5000px;'></body><script>window.scrollTo(4000, 4000);</script></html>";
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_SecurityChange.js
+++ b/dom/browser-element/mochitest/browserElement_SecurityChange.js
@@ -1,21 +1,20 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 763694 - Test that <iframe mozbrowser> delivers proper
 // mozbrowsersecuritychange events.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   var lastSecurityState;
   iframe.addEventListener('mozbrowsersecuritychange', function(e) {
     lastSecurityState = e.detail;
   });
 
@@ -42,9 +41,9 @@ function runTest() {
       SimpleTest.finish();
     }
   });
 
   iframe.src = "https://example.com/" + filepath;
   document.body.appendChild(iframe);
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_SendEvent.js
+++ b/dom/browser-element/mochitest/browserElement_SendEvent.js
@@ -1,20 +1,19 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Test that sendMouseEvent dispatch events.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement("iframe");
   iframe.mozbrowser = true;
   document.body.appendChild(iframe);
 
   iframe.addEventListener("mozbrowserloadend", function onloadend(e) {
     iframe.sendMouseEvent("mousedown", 10, 10, 0, 1, 0);
   });
 
@@ -74,9 +73,9 @@ function runTest() {
                "window.addEventListener('touchstart', changeHash);" +
                "window.addEventListener('touchmove', changeHash);" +
                "window.addEventListener('touchend', changeHash);" +
                "window.addEventListener('touchcancel', changeHash);" +
                "</script></html>";
 
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_SetVisible.js
+++ b/dom/browser-element/mochitest/browserElement_SetVisible.js
@@ -69,11 +69,9 @@ function runTest() {
     mm.addMessageListener('test:visibilitychange', recvVisibilityChanged);
     mm.loadFrameScript('data:,(' + iframeScript.toString() + ')();', false);
     iframe1.setVisible(false);
   }
 
   iframe1.addEventListener('mozbrowserloadend', iframeLoaded);
 }
 
-addEventListener('load', function() { SimpleTest.executeSoon(runTest); });
-
-
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_SetVisibleFrames.js
+++ b/dom/browser-element/mochitest/browserElement_SetVisibleFrames.js
@@ -6,23 +6,22 @@
 //
 // In this test, we modify the parent's visibility and check that the child's
 // visibility is changed as appopriate.  We test modifying the child's
 // visibility in a separate testcase.
 
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 var iframe;
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var principal = SpecialPowers.wrap(SpecialPowers.getNodePrincipal(document));
   SpecialPowers.addPermission("browser", true, { url: SpecialPowers.wrap(principal.URI).spec,
                                                  appId: principal.appId,
                                                  isInBrowserElement: true });
 
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
@@ -69,16 +68,17 @@ function getVisibleTest2() {
 
 function finish() {
   // We need to remove this listener because when this test finishes and the
   // iframe containing this document is navigated, we'll fire a
   // visibilitychange(false) event on all child iframes.  That's OK and
   // expected, but if we don't remove our listener, then we'll end up causing
   // the /next/ test to fail!
   iframe.removeEventListener('mozbrowsershowmodalprompt', checkMessage);
+  iframe.setVisible(false);
 
   var principal = SpecialPowers.wrap(SpecialPowers.getNodePrincipal(document));
   SpecialPowers.removePermission("browser", { url: SpecialPowers.wrap(principal.URI).spec,
                                               appId: principal.appId,
                                               isInBrowserElement: true });
 
   SimpleTest.finish();
 }
@@ -94,9 +94,9 @@ function checkMessage(e) {
   var msg = e.detail.message;
   is(msg, expectedMsg);
   if (msg == expectedMsg) {
     expectedMsg = null;
     SimpleTest.executeSoon(function() { expectedMsgCallback() });
   }
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_SetVisibleFrames2.js
+++ b/dom/browser-element/mochitest/browserElement_SetVisibleFrames2.js
@@ -2,21 +2,20 @@
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 762939 - Test that setting a <iframe mozbrowser> to invisible / visible
 // inside an invisible <iframe mozbrowser> doesn't trigger any events.
 
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var principal = SpecialPowers.wrap(SpecialPowers.getNodePrincipal(document));
   SpecialPowers.addPermission("browser", true, { url: SpecialPowers.wrap(principal.URI).spec,
                                                  appId: principal.appId,
                                                  isInBrowserElement: true });
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
@@ -59,9 +58,9 @@ function finish() {
   var principal = SpecialPowers.wrap(SpecialPowers.getNodePrincipal(document));
   SpecialPowers.removePermission("browser", { url: SpecialPowers.wrap(principal.URI).spec,
                                               appId: principal.appId,
                                               isInBrowserElement: true });
 
   SimpleTest.finish();
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_Stop.js
+++ b/dom/browser-element/mochitest/browserElement_Stop.js
@@ -5,25 +5,24 @@
 
 // The img that is loaded will never be returned and will block
 // the page from loading, the timeout ensures that the page is
 // actually blocked from loading, once stop is called the
 // image load will be cancaelled and mozbrowserloadend should be called.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 var iframe;
 var stopped = false;
 var imgSrc = 'http://test/tests/dom/browser-element/mochitest/file_bug709759.sjs';
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowserloadend', loadend);
   iframe.src = 'data:text/html,<html>' +
     '<body><img src="' + imgSrc + '" /></body></html>';
 
   document.body.appendChild(iframe);
@@ -44,9 +43,9 @@ function loadend() {
     SimpleTest.finish();
   }, 1000);
 }
 
 function handleError() {
   ok(false, "mozbrowsererror should not be fired");
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_TargetBlank.js
+++ b/dom/browser-element/mochitest/browserElement_TargetBlank.js
@@ -1,26 +1,25 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 764718 - Test that clicking a link with _target=blank works.
 
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     is(e.detail.url, 'http://example.com/');
     SimpleTest.finish();
   });
 
   iframe.src = "file_browserElement_TargetBlank.html";
   document.body.appendChild(iframe);
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_TargetTop.js
+++ b/dom/browser-element/mochitest/browserElement_TargetTop.js
@@ -1,21 +1,20 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 771273 - Check that window.open(url, '_top') works properly with <iframe
 // mozbrowser>.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     ok(false, 'Not expecting an openwindow event.');
   });
 
   iframe.addEventListener('mozbrowserlocationchange', function(e) {
@@ -24,9 +23,9 @@ function runTest() {
       SimpleTest.finish();
     }
   });
 
   document.body.appendChild(iframe);
   iframe.src = 'file_browserElement_TargetTop.html';
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_Titlechange.js
+++ b/dom/browser-element/mochitest/browserElement_Titlechange.js
@@ -61,11 +61,9 @@ function runTest() {
     ok(false, 'Should not get a titlechange event for iframe3.');
   });
 
   iframe1.src = 'data:text/html,<html><head><title>Title</title></head><body></body></html>';
   iframe2.src = 'data:text/html,<html><head><title>BAD TITLE</title></head><body></body></html>';
   iframe3.src = 'data:text/html,<html><head><title>SHOULD NOT GET EVENT</title></head><body></body></html>';
 }
 
-addEventListener('load', function() { SimpleTest.executeSoon(runTest); });
-
-
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_TopBarrier.js
+++ b/dom/browser-element/mochitest/browserElement_TopBarrier.js
@@ -1,14 +1,15 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Test that an <iframe mozbrowser> is a window.{top,parent,frameElement} barrier.
 "use strict";
 
+SimpleTest.waitForExplicitFinish();
 browserElementTestHelpers.setEnabledPref(true);
 browserElementTestHelpers.addPermission();
 
 var iframe;
 function runTest() {
   iframe = document.createElement('iframe');
   iframe.addEventListener('mozbrowserloadend', function() {
     try {
@@ -18,18 +19,16 @@ function runTest() {
     }
   });
   iframe.mozbrowser = true;
   iframe.src = 'data:text/html,Outer iframe <iframe id="inner-iframe"></iframe>';
   // For kicks, this test uses a display:none iframe.  This shouldn't make a
   // difference in anything.
   iframe.style.display = 'none';
   document.body.appendChild(iframe);
-
-  SimpleTest.waitForExplicitFinish();
 }
 
 var numMsgReceived = 0;
 function outerIframeLoaded() {
   var injectedScript =
     "data:,function is(a, b, desc) {                                     \
       if (a == b) {                                                      \
         sendAsyncMessage('test:test-pass', desc);                        \
@@ -71,9 +70,9 @@ function waitForMessages(num) {
   if (numMsgReceived < num) {
     SimpleTest.executeSoon(function() { waitForMessages(num); });
     return;
   }
 
   SimpleTest.finish();
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_XFrameOptions.js
+++ b/dom/browser-element/mochitest/browserElement_XFrameOptions.js
@@ -1,16 +1,18 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 770239 - Test that we can load pages with X-Frame-Options: Deny inside
 // <iframe mozbrowser>.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
   browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
@@ -19,9 +21,9 @@ function runTest() {
     ok(true, "Got alert");
     SimpleTest.finish();
   });
 
   document.body.appendChild(iframe);
   iframe.src = 'file_browserElement_XFrameOptions.sjs?DENY';
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_XFrameOptionsAllowFrom.js
+++ b/dom/browser-element/mochitest/browserElement_XFrameOptionsAllowFrom.js
@@ -1,15 +1,17 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 690168 - Support Allow-From notation for X-Frame-Options header.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 var initialScreenshotArrayBuffer = null;
 
 function arrayBuffersEqual(a, b) {
   var x = new Int8Array(a);
   var y = new Int8Array(b);
   if (x.length != y.length) {
     return false;
@@ -20,18 +22,16 @@ function arrayBuffersEqual(a, b) {
       return false;
     }
   }
 
   return true;
 }
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
   var count = 0;
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   iframe.height = '1000px';
 
   // The innermost page we load will fire an alert when it successfully loads.
   iframe.addEventListener('mozbrowsershowmodalprompt', function(e) {
@@ -70,9 +70,9 @@ function runTest() {
     }
   });
 
   document.body.appendChild(iframe);
 
   iframe.src = 'http://example.com/tests/dom/browser-element/mochitest/file_browserElement_XFrameOptionsAllowFrom.html';
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_XFrameOptionsDeny.js
+++ b/dom/browser-element/mochitest/browserElement_XFrameOptionsDeny.js
@@ -1,16 +1,18 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Bug 770239 - Test that X-Frame-Options will correctly block a page inside a
 // subframe of <iframe mozbrowser>.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 var initialScreenshotArrayBuffer;
 
 function arrayBuffersEqual(a, b) {
   var x = new Int8Array(a);
   var y = new Int8Array(b);
   if (x.length != y.length) {
     return false;
@@ -21,19 +23,16 @@ function arrayBuffersEqual(a, b) {
       return false;
     }
   }
 
   return true;
 }
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   // Our child will create two iframes, so make sure this iframe is big enough
   // to show both of them without scrolling, so taking a screenshot gets both
   // frames.
   iframe.height = '1000px';
 
@@ -72,9 +71,9 @@ function runTest() {
   document.body.appendChild(iframe);
 
   // Load this page from a different origin than ourselves.  This page will, in
   // turn, load a child from mochi.test:8888, our origin, with X-Frame-Options:
   // SAMEORIGIN.  That load should be denied.
   iframe.src = 'http://example.com/tests/dom/browser-element/mochitest/file_browserElement_XFrameOptionsDeny.html';
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/browserElement_XFrameOptionsSameOrigin.js
+++ b/dom/browser-element/mochitest/browserElement_XFrameOptionsSameOrigin.js
@@ -3,27 +3,26 @@
 
 // Bug 770239 - Load an X-Frame-Options: SAMEORIGIN page inside an <iframe>
 // inside <iframe mozbrowser>.  The two iframes will have the same origin, but
 // this page will be of a different origin.  The load should succeed.
 
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
 
 function runTest() {
-  browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addPermission();
-
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   // The innermost page we load will fire an alert when it successfully loads.
   iframe.addEventListener('mozbrowsershowmodalprompt', function(e) {
     ok(true, "Got alert");
     SimpleTest.finish();
   });
 
   document.body.appendChild(iframe);
   iframe.src = 'http://example.com/tests/dom/browser-element/mochitest/file_browserElement_XFrameOptionsSameOrigin.html';
 }
 
-runTest();
+addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/createNewTest.py
+++ b/dom/browser-element/mochitest/createNewTest.py
@@ -30,30 +30,30 @@ html_template = textwrap.dedent("""\
 js_template = textwrap.dedent("""\
     /* Any copyright is dedicated to the public domain.
        http://creativecommons.org/publicdomain/zero/1.0/ */
 
     // Bug {bug} - FILL IN TEST DESCRIPTION
     "use strict";
 
     SimpleTest.waitForExplicitFinish();
+    browserElementTestHelpers.setEnabledPref(true);
+    browserElementTestHelpers.addPermission();
 
     function runTest() {{
-      browserElementTestHelpers.setEnabledPref(true);
-      browserElementTestHelpers.addPermission();
-
       var iframe = document.createElement('iframe');
       iframe.mozbrowser = true;
 
       // FILL IN TEST
 
       document.body.appendChild(iframe);
     }}
 
-    runTest();""")
+    addEventListener('testready', runTest);
+    """)
 
 def print_fill(s):
     print(textwrap.fill(textwrap.dedent(s)))
 
 def add_to_makefile(filenames):
     """Add a list of filenames to this directory's Makefile.in, then open
     $EDITOR and let the user move the filenames to their appropriate places in
     the file.
--- a/dom/browser-element/mochitest/file_browserElement_AlertInFrame_Inner.html
+++ b/dom/browser-element/mochitest/file_browserElement_AlertInFrame_Inner.html
@@ -1,10 +1,12 @@
 <html>
 <body>
 I'm file_browserElement_AlertInFrame_Inner.html.
 
 <script>
-alert("Hello");
+addEventListener('load', function() {
+  alert("Hello");
+});
 </script>
 
 </body>
 </html>
--- a/dom/browser-element/mochitest/file_browserElement_BrowserWindowNamespace.html
+++ b/dom/browser-element/mochitest/file_browserElement_BrowserWindowNamespace.html
@@ -1,7 +1,9 @@
 <html>
 <body>
 <script>
-window.open("http://example.com/" + location.hash, "foo");
+addEventListener('load', function() {
+  window.open("http://example.com/" + location.hash, "foo");
+});
 </script>
 </body>
 </html>