Bug 1334156 - script-generated patch to replace .ownerDocument.defaultView with .ownerGlobal, r=jaws.
authorFlorian Quèze <florian@queze.net>
Fri, 27 Jan 2017 10:51:03 +0100
changeset 380406 25c0a38d2d7ed50ed3c1d419f70c01595c481ae7
parent 380405 b10f411c1481d136b7f07f928793c67b01950869
child 380407 3703867c611a64c40472658a56912eb35670fe2e
push id1468
push userasasaki@mozilla.com
push dateMon, 05 Jun 2017 19:31:07 +0000
treeherdermozilla-release@0641fc6ee9d1 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersjaws
bugs1334156
milestone54.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1334156 - script-generated patch to replace .ownerDocument.defaultView with .ownerGlobal, r=jaws.
accessible/jsat/EventManager.jsm
accessible/tests/mochitest/events.js
accessible/tests/mochitest/events/test_focus_autocomplete.xul
accessible/tests/mochitest/layout.js
addon-sdk/source/lib/framescript/context-menu.js
addon-sdk/source/lib/framescript/util.js
addon-sdk/source/lib/sdk/content/context-menu.js
addon-sdk/source/lib/sdk/context-menu.js
addon-sdk/source/lib/sdk/dom/events.js
addon-sdk/source/lib/sdk/event/dom.js
addon-sdk/source/lib/sdk/panel/utils.js
addon-sdk/source/lib/sdk/selection.js
addon-sdk/source/lib/sdk/tab/events.js
addon-sdk/source/lib/sdk/tabs/tab-firefox.js
addon-sdk/source/lib/sdk/tabs/utils.js
addon-sdk/source/lib/sdk/ui/button/view.js
addon-sdk/source/lib/sdk/window/utils.js
addon-sdk/source/test/addons/private-browsing-supported/sidebar/utils.js
addon-sdk/source/test/context-menu/util.js
addon-sdk/source/test/sidebar/utils.js
addon-sdk/source/test/test-ui-action-button.js
addon-sdk/source/test/test-ui-toggle-button.js
b2g/chrome/content/shell.js
b2g/components/ContentPermissionPrompt.js
b2g/components/ErrorPage.jsm
b2g/components/Screenshot.jsm
browser/base/content/nsContextMenu.js
browser/base/content/tabbrowser.xml
browser/base/content/urlbarBindings.xml
browser/components/contextualidentity/test/browser/browser_eme.js
browser/components/contextualidentity/test/browser/browser_imageCache.js
browser/components/customizableui/content/panelUI.xml
browser/components/extensions/ext-browserAction.js
browser/components/extensions/ext-commands.js
browser/components/extensions/ext-devtools.js
browser/components/extensions/ext-pageAction.js
browser/components/extensions/test/browser/head.js
browser/extensions/mortar/host/common/ppapi-runtime.jsm
browser/extensions/mortar/host/flash/ppapi-content-sandbox.js
browser/extensions/mortar/host/pdf/ppapi-content-sandbox.js
browser/modules/BrowserUsageTelemetry.jsm
browser/modules/URLBarZoom.jsm
devtools/server/actors/highlighters/auto-refresh.js
devtools/server/actors/highlighters/box-model.js
devtools/server/actors/highlighters/geometry-editor.js
devtools/server/actors/highlighters/simple-outline.js
devtools/server/actors/inspector.js
devtools/server/actors/webbrowser.js
devtools/server/actors/webconsole.js
dom/browser-element/BrowserElementChildPreload.js
dom/browser-element/BrowserElementCopyPaste.js
dom/browser-element/BrowserElementParent.js
dom/events/test/test_bug591249.xul
dom/plugins/test/mochitest/browser_pluginscroll.js
dom/security/test/hsts/head.js
dom/tests/mochitest/chrome/window_focus.xul
editor/AsyncSpellCheckTestHelper.jsm
layout/xul/test/test_bug987230.xul
mobile/android/chrome/content/CastingApps.js
mobile/android/chrome/content/Feedback.js
mobile/android/chrome/content/InputWidgetHelper.js
mobile/android/chrome/content/PluginHelper.js
mobile/android/chrome/content/SelectHelper.js
mobile/android/chrome/content/browser.js
mobile/android/components/ContentPermissionPrompt.js
mobile/android/components/LoginManagerPrompter.js
mobile/android/components/SessionStore.js
mobile/android/modules/NetErrorHelper.jsm
mobile/android/tests/browser/robocop/testAccessibleCarets.js
netwerk/cookie/test/browser/browser_originattributes.js
services/sync/tps/extensions/mozmill/resource/driver/controller.js
services/sync/tps/extensions/mozmill/resource/driver/mozelement.js
services/sync/tps/extensions/mozmill/resource/stdlib/utils.js
testing/marionette/accessibility.js
testing/marionette/capture.js
testing/marionette/element.js
testing/marionette/event.js
testing/marionette/interaction.js
testing/marionette/legacyaction.js
testing/mochitest/BrowserTestUtils/BrowserTestUtils.jsm
testing/mochitest/tests/SimpleTest/AsyncUtilsContent.js
toolkit/components/addoncompat/RemoteAddonsParent.jsm
toolkit/components/narrate/Narrator.jsm
toolkit/components/narrate/test/NarrateTestUtils.jsm
toolkit/components/passwordmgr/LoginManagerParent.jsm
toolkit/components/passwordmgr/test/browser/browser_passwordmgr_editing.js
toolkit/components/passwordmgr/test/chrome/notification_common.js
toolkit/components/processsingleton/MainProcessSingleton.js
toolkit/components/prompts/src/nsPrompter.js
toolkit/components/satchel/AutoCompletePopup.jsm
toolkit/components/satchel/nsFormAutoComplete.js
toolkit/components/tooltiptext/TooltipTextProvider.js
toolkit/content/browser-content.js
toolkit/content/customizeToolbar.js
toolkit/content/tests/chrome/test_arrowpanel.xul
toolkit/content/tests/chrome/window_browser_drop.xul
toolkit/content/tests/widgets/test_popupreflows.xul
toolkit/content/widgets/autocomplete.xml
toolkit/content/widgets/button.xml
toolkit/content/widgets/popup.xml
toolkit/modules/BrowserUtils.jsm
toolkit/modules/DateTimePickerHelper.jsm
toolkit/modules/Finder.jsm
toolkit/modules/FinderHighlighter.jsm
toolkit/modules/FinderIterator.jsm
toolkit/modules/InlineSpellChecker.jsm
toolkit/modules/InlineSpellCheckerContent.jsm
toolkit/modules/PageMenu.jsm
toolkit/modules/PopupNotifications.jsm
toolkit/modules/PrivateBrowsingUtils.jsm
toolkit/modules/RemoteController.jsm
toolkit/modules/SelectContentHelper.jsm
toolkit/modules/SelectParentHelper.jsm
toolkit/modules/SpatialNavigation.jsm
toolkit/modules/WindowDraggingUtils.jsm
toolkit/modules/addons/WebNavigation.jsm
toolkit/mozapps/extensions/AddonManager.jsm
toolkit/mozapps/extensions/amContentHandler.js
toolkit/mozapps/extensions/amInstallTrigger.js
toolkit/mozapps/extensions/internal/XPIProvider.jsm
toolkit/mozapps/extensions/test/browser/head.js
widget/tests/test_keycodes.xul
xpfe/components/autocomplete/resources/content/autocomplete.xml
--- a/accessible/jsat/EventManager.jsm
+++ b/accessible/jsat/EventManager.jsm
@@ -111,17 +111,17 @@ this.EventManager.prototype = {
       {
         // the target could be an element, document or window
         let window = null;
         if (aEvent.target instanceof Ci.nsIDOMWindow)
           window = aEvent.target;
         else if (aEvent.target instanceof Ci.nsIDOMDocument)
           window = aEvent.target.defaultView;
         else if (aEvent.target instanceof Ci.nsIDOMElement)
-          window = aEvent.target.ownerDocument.defaultView;
+          window = aEvent.target.ownerGlobal;
         this.present(Presentation.viewportChanged(window));
         break;
       }
       }
     } catch (x) {
       Logger.logException(x, 'Error handling DOM event');
     }
   },
--- a/accessible/tests/mochitest/events.js
+++ b/accessible/tests/mochitest/events.js
@@ -107,17 +107,17 @@ function waitForEvent(aEventType, aTarge
 /**
  * Generate mouse move over image map what creates image map accessible (async).
  * See waitForImageMap() function.
  */
 function waveOverImageMap(aImageMapID)
 {
   var imageMapNode = getNode(aImageMapID);
   synthesizeMouse(imageMapNode, 10, 10, { type: "mousemove" },
-                  imageMapNode.ownerDocument.defaultView);
+                  imageMapNode.ownerGlobal);
 }
 
 /**
  * Call the given function when the tree of the given image map is built.
  */
 function waitForImageMap(aImageMapID, aTestFunc)
 {
   waveOverImageMap(aImageMapID);
@@ -1592,17 +1592,17 @@ function moveCaretToDOMPoint(aID, aDOMPo
   this.focus = aFocusTargetID ? getAccessible(aFocusTargetID) : null;
   this.focusNode = this.focus ? this.focus.DOMNode : null;
 
   this.invoke = function moveCaretToDOMPoint_invoke()
   {
     if (this.focusNode)
       this.focusNode.focus();
 
-    var selection = this.DOMPointNode.ownerDocument.defaultView.getSelection();
+    var selection = this.DOMPointNode.ownerGlobal.getSelection();
     var selRange = selection.getRangeAt(0);
     selRange.setStart(this.DOMPointNode, aDOMPointOffset);
     selRange.collapse(true);
 
     selection.removeRange(selRange);
     selection.addRange(selRange);
   }
 
--- a/accessible/tests/mochitest/events/test_focus_autocomplete.xul
+++ b/accessible/tests/mochitest/events/test_focus_autocomplete.xul
@@ -156,17 +156,17 @@
     function focusOnMouseOver(aIDFunc, aIDFuncArg)
     {
       this.eventSeq = [ new focusChecker(aIDFunc, aIDFuncArg) ];
 
       this.invoke = function focusOnMouseOver_invoke()
       {
         this.id = aIDFunc.call(null, aIDFuncArg);
         this.node = getNode(this.id);
-        this.window = this.node.ownerDocument.defaultView;
+        this.window = this.node.ownerGlobal;
 
         if (this.node.localName == "tree") {
           var tree = getAccessible(this.node);
           var accessible = getAccessible(this.id);
           if (tree != accessible) {
             var itemX = {}, itemY = {}, treeX = {}, treeY = {};
             accessible.getBounds(itemX, itemY, {}, {});
             tree.getBounds(treeX, treeY, {}, {});
@@ -214,17 +214,17 @@
                            aFocusTargetFunc, aFocusTargetFuncArg)
     {
       this.eventSeq = [ new focusChecker(aFocusTargetFunc, aFocusTargetFuncArg) ];
 
       this.invoke = function selectByClick_invoke()
       {
         var id = aIDFunc.call(null, aIDFuncArg);
         var node = getNode(id);
-        var targetWindow = node.ownerDocument.defaultView;
+        var targetWindow = node.ownerGlobal;
 
         var x = 0, y = 0;
         if (node.localName == "tree") {
           var tree = getAccessible(node);
           var accessible = getAccessible(id);
           if (tree != accessible) {
             var itemX = {}, itemY = {}, treeX = {}, treeY = {};
             accessible.getBounds(itemX, itemY, {}, {});
--- a/accessible/tests/mochitest/layout.js
+++ b/accessible/tests/mochitest/layout.js
@@ -230,17 +230,17 @@ function getBoundsForDOMElm(aID)
   else {
     var rect = elm.getBoundingClientRect();
     x = rect.left;
     y = rect.top;
     width = rect.width;
     height = rect.height;
   }
 
-  var elmWindow = elm.ownerDocument.defaultView;
+  var elmWindow = elm.ownerGlobal;
   return CSSToDevicePixels(elmWindow,
                            x + elmWindow.mozInnerScreenX,
                            y + elmWindow.mozInnerScreenY,
                            width,
                            height);
 }
 
 function CSSToDevicePixels(aWindow, aX, aY, aWidth, aHeight)
--- a/addon-sdk/source/lib/framescript/context-menu.js
+++ b/addon-sdk/source/lib/framescript/context-menu.js
@@ -57,21 +57,21 @@ const SVG_NS = "http://www.w3.org/2000/s
 // directly. If the media is actually audio, be smarter and provide a
 // context menu with audio operations.
 // Source: https://github.com/mozilla/gecko-dev/blob/28c2fca3753c5371643843fc2f2f205146b083b7/browser/base/content/nsContextMenu.js#L632-L637
 const isVideoLoadingAudio = node =>
   node.readyState >= node.HAVE_METADATA &&
     (node.videoWidth == 0 || node.videoHeight == 0)
 
 const isVideo = node =>
-  node instanceof node.ownerDocument.defaultView.HTMLVideoElement &&
+  node instanceof node.ownerGlobal.HTMLVideoElement &&
   !isVideoLoadingAudio(node);
 
 const isAudio = node => {
-  const {HTMLVideoElement, HTMLAudioElement} = node.ownerDocument.defaultView;
+  const {HTMLVideoElement, HTMLAudioElement} = node.ownerGlobal;
   return node instanceof HTMLAudioElement ? true :
          node instanceof HTMLVideoElement ? isVideoLoadingAudio(node) :
          false;
 };
 
 const isImage = ({namespaceURI, localName}) =>
   namespaceURI === HTML_NS && localName === "img" ? true :
   namespaceURI === XUL_NS && localName === "image" ? true :
@@ -160,22 +160,22 @@ const nonPageElements = ["a", "applet", 
 const nonPageSelector = nonPageElements.
                           concat(nonPageElements.map(tag => `${tag} *`)).
                           join(", ");
 
 // Note: isPageContext implementation could have actually used SelectorMatch reader,
 // but old implementation was also checked for collapsed selection there for to keep
 // the behavior same we end up implementing a new reader.
 parsers["reader/isPage()"] = constant(node =>
-  node.ownerDocument.defaultView.getSelection().isCollapsed &&
+  node.ownerGlobal.getSelection().isCollapsed &&
   !node.matches(nonPageSelector));
 
 // Reads `true` if node is in an iframe otherwise returns true.
 parsers["reader/isFrame()"] = constant(node =>
-  !!node.ownerDocument.defaultView.frameElement);
+  !!node.ownerGlobal.frameElement);
 
 parsers["reader/isEditable()"] = constant(node => {
   const selection = getInputSelection(node);
   return selection ? !node.readOnly && !node.disabled : node.isContentEditable;
 });
 
 
 // TODO: Add some reader to read out tab id.
--- a/addon-sdk/source/lib/framescript/util.js
+++ b/addon-sdk/source/lib/framescript/util.js
@@ -16,10 +16,10 @@ const windowToMessageManager = window =>
     getInterface(Ci.nsIDocShell).
     sameTypeRootTreeItem.
     QueryInterface(Ci.nsIDocShell).
     QueryInterface(Ci.nsIInterfaceRequestor).
     getInterface(Ci.nsIContentFrameMessageManager);
 exports.windowToMessageManager = windowToMessageManager;
 
 const nodeToMessageManager = node =>
-  windowToMessageManager(node.ownerDocument.defaultView);
+  windowToMessageManager(node.ownerGlobal);
 exports.nodeToMessageManager = nodeToMessageManager;
--- a/addon-sdk/source/lib/sdk/content/context-menu.js
+++ b/addon-sdk/source/lib/sdk/content/context-menu.js
@@ -127,17 +127,17 @@ var Context = Class({
 
 // Matches when the context-clicked node doesn't have any of
 // NON_PAGE_CONTEXT_ELTS in its ancestors
 CONTEXTS.PageContext = Class({
   extends: Context,
 
   getState: function(popupNode) {
     // If there is a selection in the window then this context does not match
-    if (!popupNode.ownerDocument.defaultView.getSelection().isCollapsed)
+    if (!popupNode.ownerGlobal.getSelection().isCollapsed)
       return false;
 
     // If the clicked node or any of its ancestors is one of the blocked
     // NON_PAGE_CONTEXT_ELTS then this context does not match
     while (!(popupNode instanceof Ci.nsIDOMDocument)) {
       if (NON_PAGE_CONTEXT_ELTS.some(type => popupNode instanceof type))
         return false;
 
@@ -148,17 +148,17 @@ CONTEXTS.PageContext = Class({
   }
 });
 
 // Matches when there is an active selection in the window
 CONTEXTS.SelectionContext = Class({
   extends: Context,
 
   getState: function(popupNode) {
-    if (!popupNode.ownerDocument.defaultView.getSelection().isCollapsed)
+    if (!popupNode.ownerGlobal.getSelection().isCollapsed)
       return true;
 
     try {
       // The node may be a text box which has selectionStart and selectionEnd
       // properties. If not this will throw.
       let { selectionStart, selectionEnd } = popupNode;
       return !isNaN(selectionStart) && !isNaN(selectionEnd) &&
              selectionStart !== selectionEnd;
@@ -206,17 +206,17 @@ CONTEXTS.URLContext = Class({
   }
 });
 
 // Matches when the user-supplied predicate returns true
 CONTEXTS.PredicateContext = Class({
   extends: Context,
 
   getState: function(node) {
-    let window = node.ownerDocument.defaultView;
+    let window = node.ownerGlobal;
     let data = {};
 
     data.documentType = node.ownerDocument.contentType;
 
     data.documentURL = node.ownerDocument.location.href;
     data.targetName = node.nodeName.toLowerCase();
     data.targetID = node.id || null ;
 
@@ -320,17 +320,17 @@ var RemoteItem = Class({
   destroy: function() {
     for (let worker of this.workerMap.values()) {
       worker.destroy();
     }
     keepAlive.delete(this.id);
   },
 
   activate: function(popupNode, data) {
-    let worker = getItemWorkerForWindow(this, popupNode.ownerDocument.defaultView);
+    let worker = getItemWorkerForWindow(this, popupNode.ownerGlobal);
     if (!worker)
       return;
 
     for (let context of this.contexts)
       popupNode = context.adjustPopupNode(popupNode);
 
     worker.fireClick(popupNode, data);
   },
@@ -339,17 +339,17 @@ var RemoteItem = Class({
   getContextState: function(popupNode, addonInfo) {
     if (!(self.id in addonInfo)) {
       addonInfo[self.id] = {
         processID: process.id,
         items: {}
       };
     }
 
-    let worker = getItemWorkerForWindow(this, popupNode.ownerDocument.defaultView);
+    let worker = getItemWorkerForWindow(this, popupNode.ownerGlobal);
     let contextStates = {};
     for (let context of this.contexts)
       contextStates[context.id] = context.getState(popupNode);
 
     addonInfo[self.id].items[this.id] = {
       // It isn't ideal to create a PageContext for every item but there isn't
       // a good shared place to do it.
       pageContext: (new CONTEXTS.PageContext()).getState(popupNode),
--- a/addon-sdk/source/lib/sdk/context-menu.js
+++ b/addon-sdk/source/lib/sdk/context-menu.js
@@ -991,17 +991,17 @@ var MenuWrapper = Class({
       if (internal(this.items).children.length == 0)
         return;
 
       if (!this.populated) {
         this.populated = true;
         this.populate(this.items);
       }
 
-      let mainWindow = event.target.ownerDocument.defaultView;
+      let mainWindow = event.target.ownerGlobal;
       this.contextMenuContentData = mainWindow.gContextMenuContentData
       if (!(self.id in this.contextMenuContentData.addonInfo)) {
         console.warn("No context menu state data was provided.");
         return;
       }
       let addonInfo = this.contextMenuContentData.addonInfo[self.id];
       lastContextProcessId = addonInfo.processID;
       this.setVisibility(this.items, addonInfo.items, true);
--- a/addon-sdk/source/lib/sdk/dom/events.js
+++ b/addon-sdk/source/lib/sdk/dom/events.js
@@ -152,17 +152,17 @@ function emit(element, type, { category,
   }
 };
 exports.emit = emit;
 
 // Takes DOM `element` and returns promise which is resolved
 // when given element is removed from it's parent node.
 const removed = element => {
   return new Promise(resolve => {
-    const { MutationObserver } = element.ownerDocument.defaultView;
+    const { MutationObserver } = element.ownerGlobal;
     const observer = new MutationObserver(mutations => {
       for (let mutation of mutations) {
         for (let node of mutation.removedNodes || []) {
           if (node === element) {
             observer.disconnect();
             resolve(element);
           }
         }
--- a/addon-sdk/source/lib/sdk/event/dom.js
+++ b/addon-sdk/source/lib/sdk/event/dom.js
@@ -16,17 +16,17 @@ var listeners = new WeakMap();
 
 const { Cu } = require("chrome");
 const { ShimWaiver } = Cu.import("resource://gre/modules/ShimWaiver.jsm");
 const { ThreadSafeChromeUtils } = Cu.import("resource://gre/modules/Services.jsm", {});
 
 var getWindowFrom = x =>
                     x instanceof Ci.nsIDOMWindow ? x :
                     x instanceof Ci.nsIDOMDocument ? x.defaultView :
-                    x instanceof Ci.nsIDOMNode ? x.ownerDocument.defaultView :
+                    x instanceof Ci.nsIDOMNode ? x.ownerGlobal :
                     null;
 
 function removeFromListeners() {
   ShimWaiver.getProperty(this, "removeEventListener")("DOMWindowClose", removeFromListeners);
   for (let cleaner of listeners.get(this))
     cleaner();
 
   listeners.delete(this);
--- a/addon-sdk/source/lib/sdk/panel/utils.js
+++ b/addon-sdk/source/lib/sdk/panel/utils.js
@@ -133,17 +133,17 @@ function display(panel, options, anchor)
     let viewportRect = document.defaultView.gBrowser.getBoundingClientRect();
 
     ({x, y, width, height} = calculateRegion(options, viewportRect));
   }
   else {
     // The XUL Panel has an arrow, so the margin needs to be reset
     // to the default value.
     panel.style.margin = "";
-    let { CustomizableUI, window } = anchor.ownerDocument.defaultView;
+    let { CustomizableUI, window } = anchor.ownerGlobal;
 
     // In Australis, widgets may be positioned in an overflow panel or the
     // menu panel.
     // In such cases clicking this widget will hide the overflow/menu panel,
     // and the widget's panel will show instead.
     // If `CustomizableUI` is not available, it means the anchor is not in a
     // chrome browser window, and therefore there is no need for this check.
     if (CustomizableUI) {
--- a/addon-sdk/source/lib/sdk/selection.js
+++ b/addon-sdk/source/lib/sdk/selection.js
@@ -140,17 +140,17 @@ function getFocusedWindow() {
  * Returns the focused element in the most recent focused window
  * if private browsing window is most recent and not supported,
  * then ignore it and return `null`, because the focused element
  * can't be targeted.
  */
 function getFocusedElement() {
   let element = winUtils.getFocusedElement();
 
-  if (!element || ignoreWindow(element.ownerDocument.defaultView))
+  if (!element || ignoreWindow(element.ownerGlobal))
     return null;
 
   return element;
 }
 
 /**
  * Returns the current selection from most recent content window. Depending on
  * the specified |type|, the value returned can be a string of text, stringified
--- a/addon-sdk/source/lib/sdk/tab/events.js
+++ b/addon-sdk/source/lib/sdk/tab/events.js
@@ -63,12 +63,12 @@ function makeEvents() {
   // to cover all tab events on all windows that will open.
   return merge([eventsFromInteractive, eventsFromFuture]);
 }
 
 // Map events to Fennec format if necessary
 exports.events = map(makeEvents(), function (event) {
   return !isFennec ? event : {
     type: event.type,
-    target: event.target.ownerDocument.defaultView.BrowserApp
+    target: event.target.ownerGlobal.BrowserApp
             .getTabForBrowser(event.target)
   };
 });
--- a/addon-sdk/source/lib/sdk/tabs/tab-firefox.js
+++ b/addon-sdk/source/lib/sdk/tabs/tab-firefox.js
@@ -62,17 +62,17 @@ const Tab = Class({
       // Note that activate is defered and so will run after any open event
       // is sent out
       if (!options.inBackground)
         this.activate();
     }
 
     getURL.implement(this, tab => tab.url);
     isPrivate.implement(this, tab => {
-      return isWindowPrivate(viewsFor.get(tab).ownerDocument.defaultView);
+      return isWindowPrivate(viewsFor.get(tab).ownerGlobal);
     });
   },
 
   get id() {
     return isDestroyed(this) ? undefined : getTabId(viewsFor.get(this));
   },
 
   get title() {
@@ -118,17 +118,17 @@ const Tab = Class({
 
   get window() {
     if (isClosed(this))
       return undefined;
 
     // TODO: Remove the dependency on the windows module, see bug 792670
     require('../windows');
     let tabElement = viewsFor.get(this);
-    let domWindow = tabElement.ownerDocument.defaultView;
+    let domWindow = tabElement.ownerGlobal;
     return modelFor(domWindow);
   },
 
   get readyState() {
     return isDestroyed(this) ? undefined : this[remoteReadyStateCached] || "uninitialized";
   },
 
   pin: function() {
@@ -251,17 +251,17 @@ function maybeWindowFor(domWindow) {
 function tabEmit(tab, event, ...args) {
   // Don't emit events for destroyed tabs
   if (isDestroyed(tab))
     return;
 
   // If the windows module was never loaded this will return null. We don't need
   // to emit to the window.tabs object in this case as nothing can be listening.
   let tabElement = viewsFor.get(tab);
-  let window = maybeWindowFor(tabElement.ownerDocument.defaultView);
+  let window = maybeWindowFor(tabElement.ownerGlobal);
   if (window)
     emit(window.tabs, event, tab, ...args);
 
   emit(tabEvents, event, tab, ...args);
   emit(tab, event, tab, ...args);
 }
 
 function windowClosed(domWindow) {
@@ -276,17 +276,17 @@ windowObserver.on('close', windowClosed)
 
 // Don't want to send close events after unloaded
 when(_ => {
   windowObserver.off('close', windowClosed);
 });
 
 // Listen for tabbrowser events
 function tabEventListener(event, tabElement, ...args) {
-  let domWindow = tabElement.ownerDocument.defaultView;
+  let domWindow = tabElement.ownerGlobal;
 
   if (ignoreWindow(domWindow))
     return;
 
   // Don't send events for tabs that are already closing
   if (event != "close" && (tabElement.closing || !tabElement.parentNode))
     return;
 
--- a/addon-sdk/source/lib/sdk/tabs/utils.js
+++ b/addon-sdk/source/lib/sdk/tabs/utils.js
@@ -101,17 +101,17 @@ exports.getTabs = getTabs;
 function getActiveTab(window) {
   return getSelectedTab(window);
 }
 exports.getActiveTab = getActiveTab;
 
 function getOwnerWindow(tab) {
   // normal case
   if (tab.ownerDocument)
-    return tab.ownerDocument.defaultView;
+    return tab.ownerGlobal;
 
   // try fennec case
   return getWindowHoldingTab(tab);
 }
 exports.getOwnerWindow = getOwnerWindow;
 
 // fennec
 function getWindowHoldingTab(rawTab) {
--- a/addon-sdk/source/lib/sdk/ui/button/view.js
+++ b/addon-sdk/source/lib/sdk/ui/button/view.js
@@ -46,17 +46,17 @@ const buttonListener = {
 
       if (placement)
         emit(viewEvents, 'data', { type: 'update', target: id, window: window });
     }
   },
   onWidgetAfterDOMChange: (node, nextNode, container) => {
     let { id } = node;
     let view = views.get(id);
-    let window = node.ownerDocument.defaultView;
+    let window = node.ownerGlobal;
 
     if (view) {
       emit(viewEvents, 'data', { type: 'update', target: id, window: window });
     }
   }
 };
 
 CustomizableUI.addListener(buttonListener);
--- a/addon-sdk/source/lib/sdk/window/utils.js
+++ b/addon-sdk/source/lib/sdk/window/utils.js
@@ -410,17 +410,17 @@ function getScreenPixelsPerCSSPixel(wind
                 getInterface(Ci.nsIDOMWindowUtils).screenPixelsPerCSSPixel;
 }
 exports.getScreenPixelsPerCSSPixel = getScreenPixelsPerCSSPixel;
 
 function getOwnerBrowserWindow(node) {
   /**
   Takes DOM node and returns browser window that contains it.
   **/
-  let window = getToplevelWindow(node.ownerDocument.defaultView);
+  let window = getToplevelWindow(node.ownerGlobal);
   // If anchored window is browser then it's target browser window.
   return isBrowser(window) ? window : null;
 }
 exports.getOwnerBrowserWindow = getOwnerBrowserWindow;
 
 function getParentWindow(window) {
   try {
     return window.QueryInterface(Ci.nsIInterfaceRequestor)
--- a/addon-sdk/source/test/addons/private-browsing-supported/sidebar/utils.js
+++ b/addon-sdk/source/test/addons/private-browsing-supported/sidebar/utils.js
@@ -35,27 +35,27 @@ function getExtraSidebarMenuitems() {
 exports.getExtraSidebarMenuitems = getExtraSidebarMenuitems;
 
 function makeID(id) {
   return 'jetpack-sidebar-' + id;
 }
 exports.makeID = makeID;
 
 function simulateCommand(ele) {
-  let window = ele.ownerDocument.defaultView;
+  let window = ele.ownerGlobal;
   let { document } = window;
   var evt = document.createEvent('XULCommandEvent');
   evt.initCommandEvent('command', true, true, window,
     0, false, false, false, false, null);
   ele.dispatchEvent(evt);
 }
 exports.simulateCommand = simulateCommand;
 
 function simulateClick(ele) {
-  let window = ele.ownerDocument.defaultView;
+  let window = ele.ownerGlobal;
   let { document } = window;
   let evt = document.createEvent('MouseEvents');
   evt.initMouseEvent('click', true, true, window,
     0, 0, 0, 0, 0, false, false, false, false, 0, null);
   ele.dispatchEvent(evt);
 }
 exports.simulateClick = simulateClick;
 
--- a/addon-sdk/source/test/context-menu/util.js
+++ b/addon-sdk/source/test/context-menu/util.js
@@ -37,23 +37,23 @@ exports.openTab = openTab;
 
 const openContextMenu = (selector, tab=getActiveTab()) => {
   const browser = tabUtils.getBrowserForTab(tab);
   browser.
     messageManager.
     sendAsyncMessage("sdk/test/context-menu/open",
                      {target: selector});
 
-  return when(tab.ownerDocument.defaultView, "popupshown").
+  return when(tab.ownerGlobal, "popupshown").
           then(_target);
 };
 exports.openContextMenu = openContextMenu;
 
 const closeContextMenu = (menu) => {
-  const result = when(menu.ownerDocument.defaultView, "popuphidden").
+  const result = when(menu.ownerGlobal, "popuphidden").
                   then(_target);
 
   menu.hidePopup();
   return result;
 };
 exports.closeContextMenu = closeContextMenu;
 
 const closeTab = (tab) => {
--- a/addon-sdk/source/test/sidebar/utils.js
+++ b/addon-sdk/source/test/sidebar/utils.js
@@ -42,27 +42,27 @@ function getExtraSidebarMenuitems() {
 exports.getExtraSidebarMenuitems = getExtraSidebarMenuitems;
 
 function makeID(id) {
   return 'jetpack-sidebar-' + id;
 }
 exports.makeID = makeID;
 
 function simulateCommand(ele) {
-  let window = ele.ownerDocument.defaultView;
+  let window = ele.ownerGlobal;
   let { document } = window;
   var evt = document.createEvent('XULCommandEvent');
   evt.initCommandEvent('command', true, true, window,
     0, false, false, false, false, null);
   ele.dispatchEvent(evt);
 }
 exports.simulateCommand = simulateCommand;
 
 function simulateClick(ele) {
-  let window = ele.ownerDocument.defaultView;
+  let window = ele.ownerGlobal;
   let { document } = window;
   let evt = document.createEvent('MouseEvents');
   evt.initMouseEvent('click', true, true, window,
     0, 0, 0, 0, 0, false, false, false, false, 0, null);
   ele.dispatchEvent(evt);
 }
 exports.simulateClick = simulateClick;
 
--- a/addon-sdk/source/test/test-ui-action-button.js
+++ b/addon-sdk/source/test/test-ui-action-button.js
@@ -830,17 +830,17 @@ exports['test button icon set'] = functi
       '5': './icon5.png',
       '16': './icon16.png',
       '32': './icon32.png',
       '64': './icon64.png'
     }
   });
 
   let { node, id: widgetId } = getWidget(button.id);
-  let { devicePixelRatio } = node.ownerDocument.defaultView;
+  let { devicePixelRatio } = node.ownerGlobal;
 
   let size = 16 * devicePixelRatio;
 
   assert.equal(node.getAttribute('image'), data.url(button.icon[size].substr(2)),
     'the icon is set properly in navbar');
 
   size = 32 * devicePixelRatio;
 
@@ -1120,17 +1120,17 @@ exports['test button badge property'] = 
 
   assert.equal(button.badge, 123456,
     'badge is set');
 
   assert.equal(button.badgeColor, undefined,
     'badge color is not set');
 
   let { node } = getWidget(button.id);
-  let { getComputedStyle } = node.ownerDocument.defaultView;
+  let { getComputedStyle } = node.ownerGlobal;
   let badgeNode = badgeNodeFor(node);
 
   assert.equal('1234', node.getAttribute('badge'),
     'badge text is displayed up to four characters');
 
   assert.equal(getComputedStyle(badgeNode).backgroundColor, 'rgb(217, 0, 0)',
     'badge color is the default one');
 
@@ -1163,17 +1163,17 @@ exports['test button badge color'] = fun
     badge: '+1',
     badgeColor: 'blue'
   });
 
   assert.equal(button.badgeColor, 'blue',
     'badge color is set');
 
   let { node } = getWidget(button.id);
-  let { getComputedStyle } = node.ownerDocument.defaultView;
+  let { getComputedStyle } = node.ownerGlobal;
   let badgeNode = badgeNodeFor(node);
 
   assert.equal(badgeNodeFor(node).style.backgroundColor, 'blue',
     'badge color is displayed properly');
   assert.equal(getComputedStyle(badgeNode).backgroundColor, 'rgb(0, 0, 255)',
     'badge color overrides the default one');
 
   loader.unload();
--- a/addon-sdk/source/test/test-ui-toggle-button.js
+++ b/addon-sdk/source/test/test-ui-toggle-button.js
@@ -810,17 +810,17 @@ exports['test button icon set'] = functi
       '5': './icon5.png',
       '16': './icon16.png',
       '32': './icon32.png',
       '64': './icon64.png'
     }
   });
 
   let { node, id: widgetId } = getWidget(button.id);
-  let { devicePixelRatio } = node.ownerDocument.defaultView;
+  let { devicePixelRatio } = node.ownerGlobal;
 
   let size = 16 * devicePixelRatio;
 
   assert.equal(node.getAttribute('image'), data.url(button.icon[size].substr(2)),
     'the icon is set properly in navbar');
 
   size = 32 * devicePixelRatio;
 
@@ -1099,17 +1099,17 @@ exports['test button badge property'] = 
 
   assert.equal(button.badge, 123456,
     'badge is set');
 
   assert.equal(button.badgeColor, undefined,
     'badge color is not set');
 
   let { node } = getWidget(button.id);
-  let { getComputedStyle } = node.ownerDocument.defaultView;
+  let { getComputedStyle } = node.ownerGlobal;
   let badgeNode = badgeNodeFor(node);
 
   assert.equal('1234', node.getAttribute('badge'),
     'badge text is displayed up to four characters');
 
   assert.equal(getComputedStyle(badgeNode).backgroundColor, 'rgb(217, 0, 0)',
     'badge color is the default one');
 
@@ -1142,17 +1142,17 @@ exports['test button badge color'] = fun
     badge: '+1',
     badgeColor: 'blue'
   });
 
   assert.equal(button.badgeColor, 'blue',
     'badge color is set');
 
   let { node } = getWidget(button.id);
-  let { getComputedStyle } = node.ownerDocument.defaultView;
+  let { getComputedStyle } = node.ownerGlobal;
   let badgeNode = badgeNodeFor(node);
 
   assert.equal(badgeNodeFor(node).style.backgroundColor, 'blue',
     'badge color is displayed properly');
   assert.equal(getComputedStyle(badgeNode).backgroundColor, 'rgb(0, 0, 255)',
     'badge color overrides the default one');
 
   loader.unload();
--- a/b2g/chrome/content/shell.js
+++ b/b2g/chrome/content/shell.js
@@ -555,17 +555,17 @@ var shell = {
         this.sendChromeEvent({
           type: 'scrollviewchange',
           detail: evt.detail,
         });
         break;
       case 'mozbrowsercaretstatechanged':
         {
           let elt = evt.target;
-          let win = elt.ownerDocument.defaultView;
+          let win = elt.ownerGlobal;
           let offsetX = win.mozInnerScreenX - window.mozInnerScreenX;
           let offsetY = win.mozInnerScreenY - window.mozInnerScreenY;
 
           let rect = elt.getBoundingClientRect();
           offsetX += rect.left;
           offsetY += rect.top;
 
           let data = evt.detail;
--- a/b2g/components/ContentPermissionPrompt.js
+++ b/b2g/components/ContentPermissionPrompt.js
@@ -292,20 +292,20 @@ ContentPermissionPrompt.prototype = {
     // In both cases the message needs to be dispatched to the top-level
     // <iframe mozbrowser> container in the system app.
     // So the above code iterates over window.realFrameElement in order
     // to crosss mozbrowser iframes boundaries and find the top-level
     // one in the system app.
     // window.realFrameElement will be |null| if the code try to cross
     // content -> chrome boundaries.
     let targetElement = request.element;
-    let targetWindow = request.window || targetElement.ownerDocument.defaultView;
+    let targetWindow = request.window || targetElement.ownerGlobal;
     while (targetWindow.realFrameElement) {
       targetElement = targetWindow.realFrameElement;
-      targetWindow = targetElement.ownerDocument.defaultView;
+      targetWindow = targetElement.ownerGlobal;
     }
 
     SystemAppProxy.dispatchEvent(details, targetElement);
   },
 
   classID: Components.ID("{8c719f03-afe0-4aac-91ff-6c215895d467}"),
 
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIContentPermissionPrompt])
--- a/b2g/components/ErrorPage.jsm
+++ b/b2g/components/ErrorPage.jsm
@@ -130,17 +130,17 @@ SSLExceptions.prototype = {
     this._temporary = aTemporary;
     this._checkCert();
   }
 };
 
 var ErrorPage = {
   _addCertException: function(aMessage) {
     let frameLoaderOwner = aMessage.target.QueryInterface(Ci.nsIFrameLoaderOwner);
-    let win = frameLoaderOwner.ownerDocument.defaultView;
+    let win = frameLoaderOwner.ownerGlobal;
     let mm = frameLoaderOwner.frameLoader.messageManager;
 
     let uri = Services.io.newURI(aMessage.data.url);
     let sslExceptions = new SSLExceptions((function() {
       mm.sendAsyncMessage('ErrorPage:ReloadPage');
     }).bind(this), uri, win);
     try {
       sslExceptions.addException(!aMessage.data.isPermanent);
--- a/b2g/components/Screenshot.jsm
+++ b/b2g/components/Screenshot.jsm
@@ -10,17 +10,17 @@ Cu.import('resource://gre/modules/XPCOMU
 
 XPCOMUtils.defineLazyModuleGetter(this, "SystemAppProxy", "resource://gre/modules/SystemAppProxy.jsm");
 
 this.EXPORTED_SYMBOLS = ['Screenshot'];
 
 var Screenshot = {
   get: function screenshot_get() {
     let systemAppFrame = SystemAppProxy.getFrame();
-    let window = systemAppFrame.ownerDocument.defaultView;
+    let window = systemAppFrame.ownerGlobal;
     let document = window.document;
 
     var canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
     var docRect = document.body.getBoundingClientRect();
     var width = docRect.width;
     var height = docRect.height;
 
     // Convert width and height from CSS pixels (potentially fractional)
--- a/browser/base/content/nsContextMenu.js
+++ b/browser/base/content/nsContextMenu.js
@@ -891,25 +891,23 @@ nsContextMenu.prototype = {
              node.tagName == "label" &&
              node.classList.contains('text-link') &&
              node.href;
     }
   },
 
   // Returns the computed style attribute for the given element.
   getComputedStyle: function(aElem, aProp) {
-    return aElem.ownerDocument
-                .defaultView
+    return aElem.ownerGlobal
                 .getComputedStyle(aElem).getPropertyValue(aProp);
   },
 
   // Returns a "url"-type computed style attribute value, with the url() stripped.
   getComputedURL: function(aElem, aProp) {
-    var url = aElem.ownerDocument
-                   .defaultView.getComputedStyle(aElem)
+    var url = aElem.ownerGlobal.getComputedStyle(aElem)
                    .getPropertyCSSValue(aProp);
     if (url instanceof CSSValueList) {
       if (url.length != 1)
         throw "found multiple URLs";
       url = url[0];
     }
     return url.primitiveType == CSSPrimitiveValue.CSS_URI ?
            url.getStringValue() : null;
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -2831,33 +2831,33 @@
       <method name="swapBrowsersAndCloseOther">
         <parameter name="aOurTab"/>
         <parameter name="aOtherTab"/>
         <body>
           <![CDATA[
             // Do not allow transfering a private tab to a non-private window
             // and vice versa.
             if (PrivateBrowsingUtils.isWindowPrivate(window) !=
-                PrivateBrowsingUtils.isWindowPrivate(aOtherTab.ownerDocument.defaultView))
+                PrivateBrowsingUtils.isWindowPrivate(aOtherTab.ownerGlobal))
               return;
 
             let ourBrowser = this.getBrowserForTab(aOurTab);
             let otherBrowser = aOtherTab.linkedBrowser;
 
             // Can't swap between chrome and content processes.
             if (ourBrowser.isRemoteBrowser != otherBrowser.isRemoteBrowser)
               return;
 
             // Keep the userContextId if set on other browser
             if (otherBrowser.hasAttribute("usercontextid")) {
               ourBrowser.setAttribute("usercontextid", otherBrowser.getAttribute("usercontextid"));
             }
 
             // That's gBrowser for the other window, not the tab's browser!
-            var remoteBrowser = aOtherTab.ownerDocument.defaultView.gBrowser;
+            var remoteBrowser = aOtherTab.ownerGlobal.gBrowser;
             var isPending = aOtherTab.hasAttribute("pending");
 
             let otherTabListener = remoteBrowser._tabListeners.get(aOtherTab);
             let stateFlags = otherTabListener.mStateFlags;
 
             // Expedite the removal of the icon if it was already scheduled.
             if (aOtherTab._soundPlayingAttrRemovalTimer) {
               clearTimeout(aOtherTab._soundPlayingAttrRemovalTimer);
@@ -3000,17 +3000,17 @@
             ourBrowser.webProgress.removeProgressListener(filter);
             filter.removeProgressListener(tabListener);
 
             // Make sure to unregister any open URIs.
             this._swapRegisteredOpenURIs(ourBrowser, aOtherBrowser);
 
             // Unmap old outerWindowIDs.
             this._outerWindowIDBrowserMap.delete(ourBrowser.outerWindowID);
-            let remoteBrowser = aOtherBrowser.ownerDocument.defaultView.gBrowser;
+            let remoteBrowser = aOtherBrowser.ownerGlobal.gBrowser;
             if (remoteBrowser) {
               remoteBrowser._outerWindowIDBrowserMap.delete(aOtherBrowser.outerWindowID);
             }
 
             // If switcher is active, it will intercept swap events and
             // react as needed.
             if (!this._switcher) {
               aOtherBrowser.docShellIsActive = this.shouldActivateDocShell(ourBrowser);
@@ -4115,17 +4115,17 @@
               }
             },
 
             onSwapDocShells(ourBrowser, otherBrowser) {
               // This event fires before the swap. ourBrowser is from
               // our window. We save the state of otherBrowser since ourBrowser
               // needs to take on that state at the end of the swap.
 
-              let otherTabbrowser = otherBrowser.ownerDocument.defaultView.gBrowser;
+              let otherTabbrowser = otherBrowser.ownerGlobal.gBrowser;
               let otherState;
               if (otherTabbrowser && otherTabbrowser._switcher) {
                 let otherTab = otherTabbrowser.getTabForBrowser(otherBrowser);
                 otherState = otherTabbrowser._switcher.getTabState(otherTab);
               } else {
                 otherState = (otherBrowser.docShellIsActive
                               ? this.STATE_LOADED
                               : this.STATE_UNLOADED);
@@ -6164,27 +6164,27 @@
           var dt = event.dataTransfer;
           if (dt.mozItemCount == 1) {
             var types = dt.mozTypesAt(0);
             // tabs are always added as the first type
             if (types[0] == TAB_DROP_TYPE) {
               let sourceNode = dt.mozGetDataAt(TAB_DROP_TYPE, 0);
               if (sourceNode instanceof XULElement &&
                   sourceNode.localName == "tab" &&
-                  sourceNode.ownerDocument.defaultView instanceof ChromeWindow &&
+                  sourceNode.ownerGlobal instanceof ChromeWindow &&
                   sourceNode.ownerDocument.documentElement.getAttribute("windowtype") == "navigator:browser" &&
-                  sourceNode.ownerDocument.defaultView.gBrowser.tabContainer == sourceNode.parentNode) {
+                  sourceNode.ownerGlobal.gBrowser.tabContainer == sourceNode.parentNode) {
                 // Do not allow transfering a private tab to a non-private window
                 // and vice versa.
                 if (PrivateBrowsingUtils.isWindowPrivate(window) !=
-                    PrivateBrowsingUtils.isWindowPrivate(sourceNode.ownerDocument.defaultView))
+                    PrivateBrowsingUtils.isWindowPrivate(sourceNode.ownerGlobal))
                   return "none";
 
                 if (window.gMultiProcessBrowser !=
-                    sourceNode.ownerDocument.defaultView.gMultiProcessBrowser)
+                    sourceNode.ownerGlobal.gMultiProcessBrowser)
                   return "none";
 
                 return dt.dropEffect == "copy" ? "copy" : "move";
               }
             }
           }
 
           if (browserDragAndDrop.canDropLink(event)) {
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -1558,17 +1558,17 @@ file, You can obtain one at http://mozil
           this.view = aInput.controller.QueryInterface(Components.interfaces.nsITreeView);
           this._invalidate();
 
           var rect = window.document.documentElement.getBoundingClientRect();
           var width = rect.right - rect.left;
           this.setAttribute("width", width);
 
           // Adjust the direction of the autocomplete popup list based on the textbox direction, bug 649840
-          var popupDirection = aElement.ownerDocument.defaultView.getComputedStyle(aElement).direction;
+          var popupDirection = aElement.ownerGlobal.getComputedStyle(aElement).direction;
           this.style.direction = popupDirection;
 
           // Make the popup's starting margin negative so that the leading edge
           // of the popup aligns with the window border.
           let elementRect = aElement.getBoundingClientRect();
           if (popupDirection == "rtl") {
             let offset = elementRect.right - rect.right
             this.style.marginRight = offset + "px";
--- a/browser/components/contextualidentity/test/browser/browser_eme.js
+++ b/browser/components/contextualidentity/test/browser/browser_eme.js
@@ -18,17 +18,17 @@ const USER_ID_DEFAULT = 0;
 const USER_ID_PERSONAL = 1;
 
 function* openTabInUserContext(uri, userContextId) {
   // Open the tab in the correct userContextId.
   let tab = gBrowser.addTab(uri, {userContextId});
 
   // Select tab and make sure its browser is focused.
   gBrowser.selectedTab = tab;
-  tab.ownerDocument.defaultView.focus();
+  tab.ownerGlobal.focus();
 
   let browser = gBrowser.getBrowserForTab(tab);
   yield BrowserTestUtils.browserLoaded(browser);
   return {tab, browser};
 }
 
 function HexToBase64(hex) {
   var bin = "";
--- a/browser/components/contextualidentity/test/browser/browser_imageCache.js
+++ b/browser/components/contextualidentity/test/browser/browser_imageCache.js
@@ -38,17 +38,17 @@ add_task(function* setup() {
 // opens `uri' in a new tab with the provided userContextId and focuses it.
 // returns the newly opened tab
 function* openTabInUserContext(uri, userContextId) {
   // open the tab in the correct userContextId
   let tab = gBrowser.addTab(uri, {userContextId});
 
   // select tab and make sure its browser is focused
   gBrowser.selectedTab = tab;
-  tab.ownerDocument.defaultView.focus();
+  tab.ownerGlobal.focus();
 
   let browser = gBrowser.getBrowserForTab(tab);
   yield BrowserTestUtils.browserLoaded(browser);
   return tab;
 }
 
 add_task(function* test() {
   for (let userContextId = 0; userContextId < NUM_USER_CONTEXTS; userContextId++) {
--- a/browser/components/customizableui/content/panelUI.xml
+++ b/browser/components/customizableui/content/panelUI.xml
@@ -258,17 +258,17 @@
         <body><![CDATA[
           if (aAnchor) {
             // We need to find the edge of the anchor, relative to the main panel.
             // Then we need to add half the width of the anchor. This is the target
             // that we need to transition to.
             let anchorRect = aAnchor.getBoundingClientRect();
             let mainViewRect = this._mainViewContainer.getBoundingClientRect();
             let center = aAnchor.clientWidth / 2;
-            let direction = aAnchor.ownerDocument.defaultView.getComputedStyle(aAnchor).direction;
+            let direction = aAnchor.ownerGlobal.getComputedStyle(aAnchor).direction;
             let edge;
             if (direction == "ltr") {
               edge = anchorRect.left - mainViewRect.left;
             } else {
               edge = mainViewRect.right - anchorRect.right;
             }
 
             // If the anchor is an element on the far end of the mainView we
@@ -468,17 +468,17 @@
             }
             if (elementCS) {
               // Include margins - but not borders or paddings because they
               // were dealt with above.
               height += parseFloat(elementCS.marginTop) + parseFloat(elementCS.marginBottom);
             }
             return height;
           }
-          let win = aSubview.ownerDocument.defaultView;
+          let win = aSubview.ownerGlobal;
           let body = aSubview.querySelector(".panel-subview-body");
           let height = getFullHeight(body || aSubview);
           if (body) {
             let header = aSubview.querySelector(".panel-subview-header");
             let footer = aSubview.querySelector(".panel-subview-footer");
             height += (header ? getFullHeight(header) : 0) +
                       (footer ? getFullHeight(footer) : 0);
           }
--- a/browser/components/extensions/ext-browserAction.js
+++ b/browser/components/extensions/ext-browserAction.js
@@ -181,17 +181,17 @@ BrowserAction.prototype = {
       widget.node.dispatchEvent(event);
     } else {
       this.emit("click");
     }
   }),
 
   handleEvent(event) {
     let button = event.target;
-    let window = button.ownerDocument.defaultView;
+    let window = button.ownerGlobal;
 
     switch (event.type) {
       case "mousedown":
         if (event.button == 0) {
           // Begin pre-loading the browser for the popup, so it's more likely to
           // be ready by the time we get a complete click.
           let tab = window.gBrowser.selectedTab;
           let popupURL = this.getProperty(tab, "popup");
--- a/browser/components/extensions/ext-commands.js
+++ b/browser/components/extensions/ext-commands.js
@@ -121,20 +121,20 @@ CommandList.prototype = {
     // and it is currently ignored when set to the empty string.
     keyElement.setAttribute("oncommand", "//");
 
     /* eslint-disable mozilla/balanced-listeners */
     // We remove all references to the key elements when the extension is shutdown,
     // therefore the listeners for these elements will be garbage collected.
     keyElement.addEventListener("command", (event) => {
       if (name == "_execute_page_action") {
-        let win = event.target.ownerDocument.defaultView;
+        let win = event.target.ownerGlobal;
         pageActionFor(this.extension).triggerAction(win);
       } else if (name == "_execute_browser_action") {
-        let win = event.target.ownerDocument.defaultView;
+        let win = event.target.ownerGlobal;
         browserActionFor(this.extension).triggerAction(win);
       } else {
         TabManager.for(this.extension)
                   .addActiveTabPermission(TabManager.activeTab);
         this.emit("command", name);
       }
     });
     /* eslint-enable mozilla/balanced-listeners */
--- a/browser/components/extensions/ext-devtools.js
+++ b/browser/components/extensions/ext-devtools.js
@@ -73,17 +73,17 @@ global.getDevToolsTargetForContext = (co
  */
 global.getTargetTabIdForToolbox = (toolbox) => {
   let {target} = toolbox;
 
   if (!target.isLocalTab) {
     throw new Error("Unexpected target type: only local tabs are currently supported.");
   }
 
-  let parentWindow = target.tab.linkedBrowser.ownerDocument.defaultView;
+  let parentWindow = target.tab.linkedBrowser.ownerGlobal;
   let tab = parentWindow.gBrowser.getTabForBrowser(target.tab.linkedBrowser);
 
   return TabManager.getId(tab);
 };
 
 /**
  * The DevToolsPage represents the "devtools_page" related to a particular
  * Toolbox and WebExtension.
--- a/browser/components/extensions/ext-pageAction.js
+++ b/browser/components/extensions/ext-pageAction.js
@@ -149,17 +149,17 @@ PageAction.prototype = {
   triggerAction(window) {
     let pageAction = pageActionMap.get(this.extension);
     if (pageAction.getProperty(window.gBrowser.selectedTab, "show")) {
       pageAction.handleClick(window);
     }
   },
 
   handleEvent(event) {
-    const window = event.target.ownerDocument.defaultView;
+    const window = event.target.ownerGlobal;
 
     switch (event.type) {
       case "click":
         if (event.button === 0) {
           this.handleClick(window);
         }
         break;
 
--- a/browser/components/extensions/test/browser/head.js
+++ b/browser/components/extensions/test/browser/head.js
@@ -64,17 +64,17 @@ var focusWindow = Task.async(function* f
   win.focus();
   yield promise;
 });
 
 let img = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==";
 var imageBuffer = Uint8Array.from(atob(img), byte => byte.charCodeAt(0)).buffer;
 
 function getListStyleImage(button) {
-  let style = button.ownerDocument.defaultView.getComputedStyle(button);
+  let style = button.ownerGlobal.getComputedStyle(button);
 
   let match = /^url\("(.*)"\)$/.exec(style.listStyleImage);
 
   return match && match[1];
 }
 
 function promisePopupShown(popup) {
   return new Promise(resolve => {
--- a/browser/extensions/mortar/host/common/ppapi-runtime.jsm
+++ b/browser/extensions/mortar/host/common/ppapi-runtime.jsm
@@ -369,17 +369,17 @@ class OffscreenCanvas {
   set heigth(height) {
     this._canvas.height = height;
   }
 
   getContext(contextId, contextOptions) {
     return this._canvas.getContext(contextId, contextOptions);
   }
   transferToImageBitmap() {
-    let window = this._canvas.ownerDocument.defaultView;
+    let window = this._canvas.ownerGlobal;
     return window.createImageBitmap(this._canvas);
   }
 }
 
 
 class ObjectCache {
   constructor(getkeyForLookup=(v) => v) {
     this.objects = [];
--- a/browser/extensions/mortar/host/flash/ppapi-content-sandbox.js
+++ b/browser/extensions/mortar/host/flash/ppapi-content-sandbox.js
@@ -7,17 +7,17 @@
 /**
  * This code runs in the sandbox in the content process where the page that
  * loaded the plugin lives. It communicates with the process where the PPAPI
  * implementation lives.
  */
 const { utils: Cu } = Components;
 
 let mm = pluginElement.frameLoader.messageManager;
-let containerWindow = pluginElement.ownerDocument.defaultView;
+let containerWindow = pluginElement.ownerGlobal;
 
 function mapValue(v, instance) {
   return instance.rt.toPP_Var(v, instance);
 }
 
 dump("<>>>>>>>>>>>>>>>>>>>> AHA <<<<<<<<<<<<<<<<<<<<<>\n");
 dump(`pluginElement: ${pluginElement.toSource()}\n`);
 dump(`pluginElement.frameLoader: ${pluginElement.frameLoader.toSource()}\n`);
--- a/browser/extensions/mortar/host/pdf/ppapi-content-sandbox.js
+++ b/browser/extensions/mortar/host/pdf/ppapi-content-sandbox.js
@@ -14,17 +14,17 @@ const { classes: Cc, interfaces: Ci, res
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
                                           "resource://gre/modules/NetUtil.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
                              "resource://gre/modules/PrivateBrowsingUtils.jsm");
 
 let mm = pluginElement.frameLoader.messageManager;
-let containerWindow = pluginElement.ownerDocument.defaultView;
+let containerWindow = pluginElement.ownerGlobal;
 // Prevent the drag event's default action on the element, to avoid dragging of
 // that element while the user selects text.
 pluginElement.addEventListener("dragstart",
                                function(event) { event.preventDefault(); });
 // For synthetic documents only, prevent the select event's default action on
 // the element, to avoid selecting the element and the copying of an empty
 // string into the clipboard. Don't do this for non-synthetic documents, as
 // users still need to be able to select text outside the plugin.
--- a/browser/modules/BrowserUsageTelemetry.jsm
+++ b/browser/modules/BrowserUsageTelemetry.jsm
@@ -147,17 +147,17 @@ let URICountListener = {
       // an unfiltered URI.
       Services.telemetry.scalarAdd(UNFILTERED_URI_COUNT_SCALAR_NAME, 1);
       return;
     }
 
 
     // Don't count about:blank and similar pages, as they would artificially
     // inflate the counts.
-    if (browser.ownerDocument.defaultView.gInitialPages.includes(uriSpec)) {
+    if (browser.ownerGlobal.gInitialPages.includes(uriSpec)) {
       return;
     }
 
     // If the URI we're loading is in the _restoredURIsMap, then it comes from a
     // restored tab. If so, let's skip it and remove it from the map as we want to
     // count page refreshes.
     if (this._restoredURIsMap.get(browser) === uriSpec) {
       this._restoredURIsMap.delete(browser);
--- a/browser/modules/URLBarZoom.jsm
+++ b/browser/modules/URLBarZoom.jsm
@@ -15,17 +15,17 @@ var URLBarZoom = {
     // Register ourselves with the service so we know when the zoom prefs change.
     Services.obs.addObserver(updateZoomButton, "browser-fullZoom:zoomChange", false);
     Services.obs.addObserver(updateZoomButton, "browser-fullZoom:zoomReset", false);
     Services.obs.addObserver(updateZoomButton, "browser-fullZoom:location-change", false);
   },
 }
 
 function updateZoomButton(aSubject, aTopic) {
-  let win = aSubject.ownerDocument.defaultView;
+  let win = aSubject.ownerGlobal;
   let customizableZoomControls = win.document.getElementById("zoom-controls");
   let zoomResetButton = win.document.getElementById("urlbar-zoom-button");
   let zoomFactor = Math.round(win.ZoomManager.zoom * 100);
 
   // Ensure that zoom controls haven't already been added to browser in Customize Mode
   if (customizableZoomControls &&
       customizableZoomControls.getAttribute("cui-areatype") == "toolbar") {
     zoomResetButton.hidden = true;
--- a/devtools/server/actors/highlighters/auto-refresh.js
+++ b/devtools/server/actors/highlighters/auto-refresh.js
@@ -187,17 +187,17 @@ AutoRefreshHighlighter.prototype = {
 
   _hide: function () {
     // To be implemented by sub classes
     // When called, sub classes should actually hide the highlighter
     throw new Error("Custom highlighter class had to implement _hide method");
   },
 
   _startRefreshLoop: function () {
-    let win = this.currentNode.ownerDocument.defaultView;
+    let win = this.currentNode.ownerGlobal;
     this.rafID = win.requestAnimationFrame(this._startRefreshLoop.bind(this));
     this.rafWin = win;
     this.update();
   },
 
   _stopRefreshLoop: function () {
     if (this.rafID && !Cu.isDeadWrapper(this.rafWin)) {
       this.rafWin.cancelAnimationFrame(this.rafID);
--- a/devtools/server/actors/highlighters/box-model.js
+++ b/devtools/server/actors/highlighters/box-model.js
@@ -290,17 +290,17 @@ BoxModelHighlighter.prototype = extend(A
   },
 
   /**
    * Track the current node markup mutations so that the node info bar can be
    * updated to reflects the node's attributes
    */
   _trackMutations: function () {
     if (isNodeValid(this.currentNode)) {
-      let win = this.currentNode.ownerDocument.defaultView;
+      let win = this.currentNode.ownerGlobal;
       this.currentNodeObserver = new win.MutationObserver(this.update);
       this.currentNodeObserver.observe(this.currentNode, {attributes: true});
     }
   },
 
   _untrackMutations: function () {
     if (isNodeValid(this.currentNode) && this.currentNodeObserver) {
       this.currentNodeObserver.disconnect();
--- a/devtools/server/actors/highlighters/geometry-editor.js
+++ b/devtools/server/actors/highlighters/geometry-editor.js
@@ -87,17 +87,17 @@ var GeoProp = {
  *
  * node.offsetParent returns the nearest positioned ancestor but if it is
  * non-positioned itself, we just return null to let consumers know the node is
  * actually positioned relative to the viewport.
  *
  * @return {Object}
  */
 function getOffsetParent(node) {
-  let win = node.ownerDocument.defaultView;
+  let win = node.ownerGlobal;
 
   let offsetParent = node.offsetParent;
   if (offsetParent &&
       getComputedStyle(offsetParent).position === "static") {
     offsetParent = null;
   }
 
   let width, height;
@@ -638,17 +638,17 @@ GeometryEditorHighlighter.prototype = ex
         }
         return marginBox[side] - parseFloat(this.computedStyle[side]);
       }
 
       // In case the element is positioned in the viewport.
       if (GeoProp.isInverted(side)) {
         return this.offsetParent.dimension[GeoProp.mainAxisSize(side)];
       }
-      return -1 * this.currentNode.ownerDocument.defaultView["scroll" +
+      return -1 * this.currentNode.ownerGlobal["scroll" +
                                               GeoProp.axis(side).toUpperCase()];
     };
 
     for (let side of GeoProp.SIDES) {
       let sideProp = this.definedProperties.get(side);
       if (!sideProp) {
         continue;
       }
--- a/devtools/server/actors/highlighters/simple-outline.js
+++ b/devtools/server/actors/highlighters/simple-outline.js
@@ -43,17 +43,17 @@ SimpleOutlineHighlighter.prototype = {
   /**
    * Show the highlighter on a given node
    * @param {DOMNode} node
    */
   show: function (node) {
     if (isNodeValid(node) && (!this.currentNode || node !== this.currentNode)) {
       this.hide();
       this.currentNode = node;
-      installHelperSheet(node.ownerDocument.defaultView, SIMPLE_OUTLINE_SHEET);
+      installHelperSheet(node.ownerGlobal, SIMPLE_OUTLINE_SHEET);
       addPseudoClassLock(node, HIGHLIGHTED_PSEUDO_CLASS);
     }
     return true;
   },
 
   /**
    * Hide the highlighter, the outline and the infobar.
    */
--- a/devtools/server/actors/inspector.js
+++ b/devtools/server/actors/inspector.js
@@ -1820,17 +1820,17 @@ var WalkerActor = protocol.ActorClassWit
     this._queuePseudoClassMutation(node);
     return true;
   },
 
   _installHelperSheet: function (node) {
     if (!this.installedHelpers) {
       this.installedHelpers = new WeakMap();
     }
-    let win = node.rawNode.ownerDocument.defaultView;
+    let win = node.rawNode.ownerGlobal;
     if (!this.installedHelpers.has(win)) {
       let { Style } = require("sdk/stylesheet/style");
       let { attach } = require("sdk/content/mod");
       let style = Style({source: HELPER_SHEET, type: "agent" });
       attach(style, win);
       this.installedHelpers.set(win, style);
     }
   },
@@ -3120,17 +3120,17 @@ function nodeHasSize(node) {
  * @param {HTMLImageElement} image - The image element.
  * @param {Number} timeout - Maximum amount of time the image is allowed to load
  * before the waiting is aborted. Ignored if flags.testing is set.
  *
  * @return {Promise} that is fulfilled once the image has loaded. If the image
  * fails to load or the load takes too long, the promise is rejected.
  */
 function ensureImageLoaded(image, timeout) {
-  let { HTMLImageElement } = image.ownerDocument.defaultView;
+  let { HTMLImageElement } = image.ownerGlobal;
   if (!(image instanceof HTMLImageElement)) {
     return promise.reject("image must be an HTMLImageELement");
   }
 
   if (image.complete) {
     // The image has already finished loading.
     return promise.resolve();
   }
@@ -3175,17 +3175,17 @@ function ensureImageLoaded(image, timeou
  *     naturalWidth: 400,
  *     naturalHeight: 300,
  *     resized: true }
  *  }.
  *
  * If something goes wrong, the promise is rejected.
  */
 var imageToImageData = Task.async(function* (node, maxDim) {
-  let { HTMLCanvasElement, HTMLImageElement } = node.ownerDocument.defaultView;
+  let { HTMLCanvasElement, HTMLImageElement } = node.ownerGlobal;
 
   let isImg = node instanceof HTMLImageElement;
   let isCanvas = node instanceof HTMLCanvasElement;
 
   if (!isImg && !isCanvas) {
     throw new Error("node is not a <canvas> or <img> element.");
   }
 
--- a/devtools/server/actors/webbrowser.js
+++ b/devtools/server/actors/webbrowser.js
@@ -662,17 +662,17 @@ DevToolsUtils.makeInfallible(function (w
    */
   Services.tm.currentThread.dispatch(DevToolsUtils.makeInfallible(() => {
     /*
      * Scan the entire map for actors representing tabs that were in this
      * top-level window, and exit them.
      */
     for (let [browser, actor] of this._actorByBrowser) {
       /* The browser document of a closed window has no default view. */
-      if (!browser.ownerDocument.defaultView) {
+      if (!browser.ownerGlobal) {
         this._handleActorClose(actor, browser);
       }
     }
   }, "BrowserTabList.prototype.onCloseWindow's delayed body"), 0);
 }, "BrowserTabList.prototype.onCloseWindow");
 
 exports.BrowserTabList = BrowserTabList;
 
--- a/devtools/server/actors/webconsole.js
+++ b/devtools/server/actors/webconsole.js
@@ -1777,17 +1777,17 @@ WebConsoleActor.prototype =
    *         The XUL window that owns the content window.
    */
   chromeWindow: function WCA_chromeWindow()
   {
     let window = null;
     try {
       window = this.window.QueryInterface(Ci.nsIInterfaceRequestor)
              .getInterface(Ci.nsIWebNavigation).QueryInterface(Ci.nsIDocShell)
-             .chromeEventHandler.ownerDocument.defaultView;
+             .chromeEventHandler.ownerGlobal;
     }
     catch (ex) {
       // The above can fail because chromeEventHandler is not available for all
       // kinds of |this.window|.
     }
 
     return window;
   },
--- a/dom/browser-element/BrowserElementChildPreload.js
+++ b/dom/browser-element/BrowserElementChildPreload.js
@@ -575,17 +575,17 @@ BrowserElementChild.prototype = {
     debug('Got manifestchanged: (' + e.target.href + ')');
     let manifest = { href: e.target.href };
     sendAsyncMsg('manifestchange', manifest);
 
   },
 
   // Processes the "rel" field in <link> tags and forward to specific handlers.
   _linkAddedHandler: function(e) {
-    let win = e.target.ownerDocument.defaultView;
+    let win = e.target.ownerGlobal;
     // Ignore links which don't come from the top-level
     // <iframe mozbrowser> window.
     if (win != content) {
       debug('Not top level!');
       return;
     }
 
     let handlers = {
@@ -601,17 +601,17 @@ BrowserElementChild.prototype = {
       let token = x.toLowerCase();
       if (handlers[token]) {
         handlers[token](e);
       }
     }, this);
   },
 
   _metaChangedHandler: function(e) {
-    let win = e.target.ownerDocument.defaultView;
+    let win = e.target.ownerGlobal;
     // Ignore metas which don't come from the top-level
     // <iframe mozbrowser> window.
     if (win != content) {
       debug('Not top level!');
       return;
     }
 
     var name = e.target.name;
--- a/dom/browser-element/BrowserElementCopyPaste.js
+++ b/dom/browser-element/BrowserElementCopyPaste.js
@@ -103,17 +103,17 @@ var CopyPasteAssistent = {
     // Get correct geometry information if we have nested iframe.
     let currentWindow = e.target.defaultView;
     while (currentWindow.realFrameElement) {
       let currentRect = currentWindow.realFrameElement.getBoundingClientRect();
       detail.rect.top += currentRect.top;
       detail.rect.bottom += currentRect.top;
       detail.rect.left += currentRect.left;
       detail.rect.right += currentRect.left;
-      currentWindow = currentWindow.realFrameElement.ownerDocument.defaultView;
+      currentWindow = currentWindow.realFrameElement.ownerGlobal;
 
       let targetDocShell = currentWindow
           .QueryInterface(Ci.nsIInterfaceRequestor)
           .getInterface(Ci.nsIWebNavigation);
       if(targetDocShell.isMozBrowser) {
         break;
       }
     }
--- a/dom/browser-element/BrowserElementParent.js
+++ b/dom/browser-element/BrowserElementParent.js
@@ -219,21 +219,21 @@ BrowserElementParent.prototype = {
 
   /**
    * You shouldn't touch this._frameElement or this._window if _isAlive is
    * false.  (You'll likely get an exception if you do.)
    */
   _isAlive: function() {
     return !Cu.isDeadWrapper(this._frameElement) &&
            !Cu.isDeadWrapper(this._frameElement.ownerDocument) &&
-           !Cu.isDeadWrapper(this._frameElement.ownerDocument.defaultView);
+           !Cu.isDeadWrapper(this._frameElement.ownerGlobal);
   },
 
   get _window() {
-    return this._frameElement.ownerDocument.defaultView;
+    return this._frameElement.ownerGlobal;
   },
 
   get _windowUtils() {
     return this._window.QueryInterface(Ci.nsIInterfaceRequestor)
                        .getInterface(Ci.nsIDOMWindowUtils);
   },
 
   promptAuth: function(authDetail, callback) {
--- a/dom/events/test/test_bug591249.xul
+++ b/dom/events/test/test_bug591249.xul
@@ -24,17 +24,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 SimpleTest.waitForExplicitFinish();
 
 function completeTest(aBox) {
   ok(window.getComputedStyle(aBox).backgroundColor == "rgb(255, 0, 0)", "The -moz-drag-over style should be removed.");
   SimpleTest.finish();
 }
 
 function fireEvent(target, event) {
-  var win = target.ownerDocument.defaultView;
+  var win = target.ownerGlobal;
   var utils =
     win.QueryInterface(Components.interfaces.nsIInterfaceRequestor).
         getInterface(Components.interfaces.nsIDOMWindowUtils);
   utils.dispatchDOMEventViaPresShell(target, event, true);
 }
 
 function RunTest() {
   var image = document.getElementById("image");
@@ -56,17 +56,17 @@ function RunTest() {
   window.addEventListener("dragstart", trapDrag, true);
   synthesizeMouse(image, 2, 2, { type: "mousedown" });
   synthesizeMouse(image, 11, 11, { type: "mousemove" });
   synthesizeMouse(image, 20, 20, { type: "mousemove" });
   window.removeEventListener("dragstart", trapDrag, true);
   synthesizeMouse(image, 20, 20, { type: "mouseup" });
 
   var event = document.createEvent("DragEvent");
-  event.initDragEvent("dragover", true, true, iBox.ownerDocument.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, iBox, dataTransfer);
+  event.initDragEvent("dragover", true, true, iBox.ownerGlobal, 0, 0, 0, 0, 0, false, false, false, false, 0, iBox, dataTransfer);
   fireEvent(iBox, event);
   synthesizeMouse(image, 3, 3, { type: "mousedown" });
   synthesizeMouse(image, 23, 23, { type: "mousemove" });
   synthesizeMouse(iBox, insideBoxX, insideBoxY, { type: "mousemove" });
   ok(window.getComputedStyle(iBox).backgroundColor == "rgb(255, 255, 0)", "The -moz-drag-over style should be applied.");
   synthesizeMouse(iBox, insideBoxX, insideBoxY, { type: "mouseup" });
   window.setTimeout(function () { completeTest(iBox); }, 40);
 }
--- a/dom/plugins/test/mochitest/browser_pluginscroll.js
+++ b/dom/plugins/test/mochitest/browser_pluginscroll.js
@@ -1,16 +1,16 @@
 var gTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
 
 /**
  * tests for plugin windows and scroll
  */
 
 function coordinatesRelativeToWindow(aX, aY, aElement) {
-  var targetWindow = aElement.ownerDocument.defaultView;
+  var targetWindow = aElement.ownerGlobal;
   var scale = targetWindow.devicePixelRatio;
   var rect = aElement.getBoundingClientRect();
   return {
     x: targetWindow.mozInnerScreenX + ((rect.left + aX) * scale),
     y: targetWindow.mozInnerScreenY + ((rect.top + aY) * scale)
   };
 }
 
--- a/dom/security/test/hsts/head.js
+++ b/dom/security/test/hsts/head.js
@@ -302,17 +302,17 @@ var Observer = {
 
 // opens `uri' in a new tab and focuses it.
 // returns the newly opened tab
 function openTab(uri) {
   let tab = gBrowser.addTab(uri);
 
   // select tab and make sure its browser is focused
   gBrowser.selectedTab = tab;
-  tab.ownerDocument.defaultView.focus();
+  tab.ownerGlobal.focus();
 
   return tab;
 }
 
 function clear_sts_data() {
   for (let test in test_servers) {
     SpecialPowers.cleanUpSTSData('http://'+test_servers[test].host);
   }
--- a/dom/tests/mochitest/chrome/window_focus.xul
+++ b/dom/tests/mochitest/chrome/window_focus.xul
@@ -88,17 +88,17 @@ function eventOccured(event)
     gEvents += " ";
   gEvents += event.type + ": " + id;
 }
 
 function expectFocusShift(callback, expectedWindow, expectedElement, focusChanged, testid)
 {
   if (expectedWindow == null)
     expectedWindow = expectedElement ?
-                     expectedElement.ownerDocument.defaultView :
+                     expectedElement.ownerGlobal :
                      gLastFocusWindow;
 
   var expectedEvents = "";
   if (focusChanged) {
     var id;
     if (getTopWindow(gLastFocusWindow) != getTopWindow(expectedWindow)) {
       id = getTopWindow(gLastFocusWindow).document.documentElement.id;
       expectedEvents += "deactivate: " + id + "-window";
@@ -303,30 +303,30 @@ function mouseWillTriggerFocus(element)
     return true;
   }
 
   return false;
 }
 
 function mouseOnElement(element, expectedElement, focusChanged, testid)
 {
-  var expectedWindow = (element.ownerDocument.defaultView == gChildWindow) ? gChildWindow : window;
+  var expectedWindow = (element.ownerGlobal == gChildWindow) ? gChildWindow : window;
   // on Mac, form elements are not focused when clicking, except for lists and textboxes.
   var noFocusOnMouse = !mouseWillTriggerFocus(element)
 
   if (noFocusOnMouse) {
     // no focus so the last focus method will be 0
     gLastFocusMethod = 0;
-    expectFocusShift(() => synthesizeMouse(element, 4, 4, { }, element.ownerDocument.defaultView),
+    expectFocusShift(() => synthesizeMouse(element, 4, 4, { }, element.ownerGlobal),
                      expectedWindow, null, true, testid);
     gLastFocusMethod = fm.FLAG_BYMOUSE;
   }
   else {
-    expectFocusShift(() => synthesizeMouse(element, 4, 4, { }, element.ownerDocument.defaultView),
-                     element.ownerDocument.defaultView,
+    expectFocusShift(() => synthesizeMouse(element, 4, 4, { }, element.ownerGlobal),
+                     element.ownerGlobal,
                      expectedElement, focusChanged, testid);
   }
 }
 
 function done()
 {
   var opener = window.opener;
   window.close();
@@ -451,17 +451,17 @@ function startTest()
       continue;
 
     var element = getById("t" + idx);
     // skip area elements, as getBoundingClientRect doesn't return their actual coordinates
     if (element.localName == "area")
       continue;
 
     mouseOnElement(element, getById("t" + idx), true, "mouse on element t" + idx);
-    var expectedWindow = (element.ownerDocument.defaultView == gChildWindow) ? gChildWindow : window;
+    var expectedWindow = (element.ownerGlobal == gChildWindow) ? gChildWindow : window;
     if (element.localName == "listbox" && expectedWindow == window &&
         navigator.platform.indexOf("Mac") == 0) {
       // after focusing a listbox on Mac, clear the focus before continuing.
       setFocusTo(null, window);
     }
   }
 
   ok(t19.selectionStart == t19.selectionEnd, "input focused from mouse selection");
@@ -482,17 +482,17 @@ function startTest()
     gLastFocusMethod = idx % 2 ? 0 : fm.FLAG_BYMOUSE;
 
     mouseOnElement(element, idx % 2 ? null: element, true, "mouse on unfocusable element n" + idx);
   }
 
   if (idx == kOverflowElementIndex) {
     gLastFocusMethod = fm.FLAG_BYMOUSE;
     var element = getById("t" + idx);
-    expectFocusShift(() => synthesizeMouse(element, 4, 4, { }, element.ownerDocument.defaultView),
+    expectFocusShift(() => synthesizeMouse(element, 4, 4, { }, element.ownerGlobal),
                      window, null, true, "mouse on scrollable element");
   }
 
   // focus() method
   gLastFocusMethod = 0;
   for (idx = kTabbableSteps; idx >= 1; idx--) {
     if ((navigator.platform.indexOf("Mac") == 0) && (idx == kBeforeTabboxIndex + 1))
       continue;
@@ -507,26 +507,26 @@ function startTest()
   $("t7").blur();
   ok(gEvents === "", "blurring element that is not focused");
   is(document.activeElement, $("t1"), "old element still focused after blur() on another element");
 
   // focus() method on elements that are not tabbable 
   for (idx = 1; idx <= kFocusSteps; idx++) {
     var expected = getById("o" + (idx % 2 ? idx : idx - 1));
     expectFocusShift(() => getById("o" + idx).focus(),
-                     expected.ownerDocument.defaultView,
+                     expected.ownerGlobal,
                      expected, idx % 2, "focus method on non-tabbable element o" + idx);
   }
 
   // focus() method on elements that are not tabbable and have user-focus: none
   // or are not focusable for other reasons (for instance, being disabled)
   for (idx = 1; idx <= kNoFocusSteps; idx++) {
     var expected = getById("o" + (idx % 2 ? idx : idx - 1));
     expectFocusShift(() => getById("o" + idx).focus(),
-                     expected.ownerDocument.defaultView,
+                     expected.ownerGlobal,
                      expected, idx % 2, "focus method on unfocusable element n" + idx);
   }
 
   // the focus() method on the legend element should focus the legend if it is
   // focusable, or the first element after the legend if it is not focusable.
   if (!gPartialTabbing) {
     gLastFocusMethod = fm.FLAG_BYMOVEFOCUS;
     var legend = getById("legend");
@@ -548,17 +548,17 @@ function startTest()
   for (var k = 0; k < keys.length; k++) {
     var key = String.fromCharCode(65 + k);
 
     // accesskeys D and G are for labels so get redirected
     gLastFocusMethod = (key == "D" || key == "G") ? fm.FLAG_BYMOVEFOCUS : fm.FLAG_BYKEY;
 
     // on Windows and Linux, the shift key must be pressed for content area access keys
     // and on Mac, the alt key must be pressed for content area access keys
-    var isContent = (getById(keys[k]).ownerDocument.defaultView == gChildWindow);
+    var isContent = (getById(keys[k]).ownerGlobal == gChildWindow);
     if (navigator.platform.indexOf("Mac") == -1) {
       accessKeyDetails.shiftKey = isContent;
     } else {
       accessKeyDetails.altKey = isContent;
     }
 
     expectFocusShift(() => synthesizeKey(key, accessKeyDetails),
                      null, getById(keys[k]), true, "accesskey " + key);
@@ -624,17 +624,17 @@ function startTest()
     gEvents = "";
     element.addEventListener("blur", eventListener, false);
     blurFunction();
     element.removeEventListener("blur", eventListener, false);
   }
 
   var functions = [
     element => element.focus(),
-    element => synthesizeMouse(element, 4, 4, { }, element.ownerDocument.defaultView)
+    element => synthesizeMouse(element, 4, 4, { }, element.ownerGlobal)
   ];
 
   // first, check cases where the focus is adjusted during the blur event. Iterate twice,
   // once with the focus method and then focusing by mouse clicking
   for  (var l = 0; l < 2; l++) {
     var adjustFocus = functions[l];
     var mod = (l == 1) ? " with mouse" : "";
 
@@ -1112,17 +1112,17 @@ function otherWindowFocused(otherWindow)
     if ((navigator.platform.indexOf("Mac") == 0) && (idx == kBeforeTabboxIndex + 1))
       continue;
 
     expectedElement.focus();
 
     is(fm.focusedElement.id, "other", "when lowered focusedElement t" + idx);
     is(fm.focusedWindow, otherWindow, "when lowered focusedWindow t" + idx);
 
-    var checkWindow = expectedElement.ownerDocument.defaultView;
+    var checkWindow = expectedElement.ownerGlobal;
     is(fm.getFocusedElementForWindow(checkWindow, false, {}).id, expectedElement.id,
        "when lowered getFocusedElementForWindow t" + idx);
     is(checkWindow.document.activeElement.id, expectedElement.id, "when lowered activeElement t" + idx);
     if (checkWindow != window) {
       is(fm.getFocusedElementForWindow(window, false, {}), $("childframe"),
          "when lowered parent getFocusedElementForWindow t" + idx);
       is(document.activeElement.id, "childframe",
          "when lowered parent activeElement t" + idx);
--- a/editor/AsyncSpellCheckTestHelper.jsm
+++ b/editor/AsyncSpellCheckTestHelper.jsm
@@ -26,17 +26,17 @@ const { classes: Cc, interfaces: Ci, uti
  * @param editableElement  The element being spell checked.
  * @param callback         Called when spell check has completed or enough turns
  *                         of the event loop have passed to determine it has not
  *                         started.
  */
 function onSpellCheck(editableElement, callback) {
   let editor = editableElement.editor;
   if (!editor) {
-    let win = editableElement.ownerDocument.defaultView;
+    let win = editableElement.ownerGlobal;
     editor = win.QueryInterface(Ci.nsIInterfaceRequestor).
                  getInterface(Ci.nsIWebNavigation).
                  QueryInterface(Ci.nsIInterfaceRequestor).
                  getInterface(Ci.nsIEditingSession).
                  getEditorForWindow(win);
   }
   if (!editor)
     throw new Error("Unable to find editor for element " + editableElement);
--- a/layout/xul/test/test_bug987230.xul
+++ b/layout/xul/test/test_bug987230.xul
@@ -61,17 +61,17 @@ https://bugzilla.mozilla.org/show_bug.cg
   let mouseMove = isWindows ? 1 : 5;
   let utils = window.QueryInterface(Ci.nsIInterfaceRequestor)
                     .getInterface(Ci.nsIDOMWindowUtils);
   let scale = utils.screenPixelsPerCSSPixel;
 
 
   function synthesizeNativeMouseClick(aElement, aOffsetX, aOffsetY) {
     let rect = aElement.getBoundingClientRect();
-    let win = aElement.ownerDocument.defaultView;
+    let win = aElement.ownerGlobal;
     let x = aOffsetX + win.mozInnerScreenX + rect.left;
     let y = aOffsetY + win.mozInnerScreenY + rect.top;
 
     info("Sending mousedown+up for offsets: " + aOffsetX + ", " + aOffsetY +
          "; innerscreen: " + win.mozInnerScreenX + ", " + win.mozInnerScreenY +
          "; rect: " + rect.left + ", " + rect.top + ".");
     info("Resulting x, y, scale: " + x + ", " + y + ", " + scale);
     info("Final params: " + (x * scale) + ", " + (y * scale));
--- a/mobile/android/chrome/content/CastingApps.js
+++ b/mobile/android/chrome/content/CastingApps.js
@@ -602,17 +602,17 @@ var CastingApps = {
     if (!aVideo) {
       aVideo = this._findCastableVideo(BrowserApp.selectedBrowser);
       if (!aVideo) {
         return;
       }
     }
 
     // We only show pageactions if the <video> is from the selected tab
-    if (BrowserApp.selectedTab != BrowserApp.getTabForWindow(aVideo.ownerDocument.defaultView.top)) {
+    if (BrowserApp.selectedTab != BrowserApp.getTabForWindow(aVideo.ownerGlobal.top)) {
       return;
     }
 
     // We check for two state here:
     // 1. The video is actively being cast
     // 2. The video is allowed to be cast and is currently playing
     // Both states have the same action: Show the cast page action
     if (aVideo.mozIsCasting) {
@@ -685,17 +685,17 @@ var CastingApps = {
         return;
 
       // Make sure we have a player app for the given service
       let app = SimpleServiceDiscovery.findAppForService(aService);
       if (!app)
         return;
 
       if (aVideo.element) {
-        aVideo.title = aVideo.element.ownerDocument.defaultView.top.document.title;
+        aVideo.title = aVideo.element.ownerGlobal.top.document.title;
 
         // If the video is currently playing on the device, pause it
         if (!aVideo.element.paused) {
           aVideo.element.pause();
         }
       }
 
       app.stop(function() {
--- a/mobile/android/chrome/content/Feedback.js
+++ b/mobile/android/chrome/content/Feedback.js
@@ -47,17 +47,17 @@ var Feedback = {
         // Do nothing.
         break;
 
       case "FeedbackMaybeLater":
         GlobalEventDispatcher.sendRequest({ type: "Feedback:MaybeLater" });
         break;
     }
 
-    let win = event.target.ownerDocument.defaultView.top;
+    let win = event.target.ownerGlobal.top;
     BrowserApp.closeTab(BrowserApp.getTabForWindow(win));
   },
 
   _isAllowed: function(node) {
     let uri = node.ownerDocument.documentURIObject;
     let feedbackURI = Services.io.newURI(this._feedbackURL);
     return uri.prePath === feedbackURI.prePath;
   }
--- a/mobile/android/chrome/content/InputWidgetHelper.js
+++ b/mobile/android/chrome/content/InputWidgetHelper.js
@@ -19,17 +19,17 @@ var InputWidgetHelper = {
     this._uiBusy = true;
     this.show(aTarget);
     this._uiBusy = false;
   },
 
   show: function(aElement) {
     let type = aElement.getAttribute('type');
     let p = new Prompt({
-      window: aElement.ownerDocument.defaultView,
+      window: aElement.ownerGlobal,
       title: Strings.browser.GetStringFromName("inputWidgetHelper." + aElement.getAttribute('type')),
       buttons: [
         Strings.browser.GetStringFromName("inputWidgetHelper.set"),
         Strings.browser.GetStringFromName("inputWidgetHelper.clear"),
         Strings.browser.GetStringFromName("inputWidgetHelper.cancel")
       ],
     }).addDatePicker({
       value: aElement.value,
--- a/mobile/android/chrome/content/PluginHelper.js
+++ b/mobile/android/chrome/content/PluginHelper.js
@@ -172,17 +172,17 @@ var PluginHelper = {
           overlay.classList.add("visible");
         }
 
         // Add click to play listener to the overlay
         overlay.addEventListener("click", function(e) {
           if (!e.isTrusted)
             return;
           e.preventDefault();
-          let win = e.target.ownerDocument.defaultView.top;
+          let win = e.target.ownerGlobal.top;
           let tab = BrowserApp.getTabForWindow(win);
           tab.clickToPlayPluginsActivated = true;
           PluginHelper.playAllPlugins(win);
 
           NativeWindow.doorhanger.hide("ask-to-play-plugins", tab.id);
         }, true);
 
         // Add handlers for over- and underflow in case the plugin gets resized
--- a/mobile/android/chrome/content/SelectHelper.js
+++ b/mobile/android/chrome/content/SelectHelper.js
@@ -51,17 +51,17 @@ var SelectHelper = {
         this.fireOnChange(element);
       }
     }
   },
 
   show: function(element) {
     let list = this.getListForElement(element);
     let p = new Prompt({
-      window: element.ownerDocument.defaultView
+      window: element.ownerGlobal
     });
 
     if (element.multiple) {
       p.addButton({
         label: Strings.browser.GetStringFromName("selectHelper.closeMultipleSelectDialog")
       }).setMultiChoiceItems(list);
     } else {
       p.setSingleChoiceItems(list);
--- a/mobile/android/chrome/content/browser.js
+++ b/mobile/android/chrome/content/browser.js
@@ -1533,17 +1533,17 @@ var BrowserApp = {
       return null;
 
     if (focused && (focused instanceof HTMLTextAreaElement || focused.isContentEditable)) {
 
       if (focused instanceof HTMLBodyElement) {
         // we are putting focus into a contentEditable frame. scroll the frame into
         // view instead of the contentEditable document contained within, because that
         // results in a better user experience
-        focused = focused.ownerDocument.defaultView.frameElement;
+        focused = focused.ownerGlobal.frameElement;
       }
       return focused;
     }
     return null;
   },
 
   scrollToFocusedInput: function(aBrowser, aAllowZoom = true) {
     let formHelperMode = Services.prefs.getIntPref("formhelper.mode");
@@ -2919,17 +2919,17 @@ var NativeWindow = {
             return 0;
           }
           return (a.order > b.order) ? 1 : -1;
         });
       }
 
       let useTabs = Object.keys(this.menus).length > 1;
       let prompt = new Prompt({
-        window: target.ownerDocument.defaultView,
+        window: target.ownerGlobal,
         title: useTabs ? undefined : title
       });
 
       let items = this._reformatList(target);
       if (useTabs) {
         prompt.addTabs({
           id: "tabs",
           items: items
@@ -3076,17 +3076,17 @@ var LightWeightThemeWebInstaller = {
   },
 
   handleEvent: function (event) {
     switch (event.type) {
       case "InstallBrowserTheme":
       case "PreviewBrowserTheme":
       case "ResetBrowserThemePreview":
         // ignore requests from background tabs
-        if (event.target.ownerDocument.defaultView.top != content)
+        if (event.target.ownerGlobal.top != content)
           return;
     }
 
     switch (event.type) {
       case "InstallBrowserTheme":
         this._installRequest(event);
         break;
       case "PreviewBrowserTheme":
@@ -3153,17 +3153,17 @@ var LightWeightThemeWebInstaller = {
   _preview: function (event) {
     if (!this._isAllowed(event.target))
       return;
     let data = this._getThemeFromNode(event.target);
     if (!data)
       return;
     this._resetPreview();
 
-    this._previewWindow = event.target.ownerDocument.defaultView;
+    this._previewWindow = event.target.ownerGlobal;
     this._previewWindow.addEventListener("pagehide", this, true);
     BrowserApp.deck.addEventListener("TabSelect", this);
     this._manager.previewTheme(data);
   },
 
   _resetPreview: function (event) {
     if (!this._previewWindow ||
         event && !this._isAllowed(event.target))
@@ -4802,17 +4802,17 @@ const ElementTouchHelper = {
 
     let cwu = document.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
     let scrollX = {}, scrollY = {};
     cwu.getScrollXY(false, scrollX, scrollY);
 
     let r = aElement.getBoundingClientRect();
 
     // step out of iframes and frames, offsetting scroll values
-    for (let frame = aElement.ownerDocument.defaultView; frame.frameElement && frame != content; frame = frame.parent) {
+    for (let frame = aElement.ownerGlobal; frame.frameElement && frame != content; frame = frame.parent) {
       // adjust client coordinates' origin to be top left of iframe viewport
       let rect = frame.frameElement.getBoundingClientRect();
       let left = frame.getComputedStyle(frame.frameElement).borderLeftWidth;
       let top = frame.getComputedStyle(frame.frameElement).borderTopWidth;
       scrollX.value += rect.left + parseInt(left);
       scrollY.value += rect.top + parseInt(top);
     }
 
@@ -5027,17 +5027,17 @@ var FormAssistant = {
 
   notifyInvalidSubmit: function notifyInvalidSubmit(aFormElement, aInvalidElements) {
     if (!aInvalidElements.length)
       return;
 
     // Ignore this notificaiton if the current tab doesn't contain the invalid element
     let currentElement = aInvalidElements.queryElementAt(0, Ci.nsISupports);
     if (BrowserApp.selectedBrowser.contentDocument !=
-        currentElement.ownerDocument.defaultView.top.document)
+        currentElement.ownerGlobal.top.document)
       return;
 
     this._invalidSubmit = true;
 
     // Our focus listener will show the element's validation message
     currentElement.focus();
   },
 
--- a/mobile/android/components/ContentPermissionPrompt.js
+++ b/mobile/android/components/ContentPermissionPrompt.js
@@ -66,17 +66,17 @@ ContentPermissionPrompt.prototype = {
      return chromeWin;
   },
 
   getChromeForRequest: function getChromeForRequest(request) {
     if (request.window) {
       let requestingWindow = request.window.top;
       return this.getChromeWindow(requestingWindow).wrappedJSObject;
     }
-    return request.element.ownerDocument.defaultView;
+    return request.element.ownerGlobal;
   },
 
   prompt: function(request) {
     let isApp = request.principal.appId !== Ci.nsIScriptSecurityManager.NO_APP_ID && request.principal.appId !== Ci.nsIScriptSecurityManager.UNKNOWN_APP_ID;
 
     // Only allow exactly one permission rquest here.
     let types = request.types.QueryInterface(Ci.nsIArray);
     if (types.length != 1) {
--- a/mobile/android/components/LoginManagerPrompter.js
+++ b/mobile/android/components/LoginManagerPrompter.js
@@ -339,17 +339,17 @@ LoginManagerPrompter.prototype = {
    * Given a content DOM window, returns the chrome window it's in.
    */
   _getChromeWindow: function (aWindow) {
     if (aWindow instanceof Ci.nsIDOMChromeWindow)
       return aWindow;
     var chromeWin = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
       .getInterface(Ci.nsIWebNavigation)
       .QueryInterface(Ci.nsIDocShell)
-      .chromeEventHandler.ownerDocument.defaultView;
+      .chromeEventHandler.ownerGlobal;
     return chromeWin;
   },
 
   /*
    * _getNativeWindow
    *
    * Returns the NativeWindow to this prompter, or null if there isn't
    * a NativeWindow available (w/ error sent to logcat).
--- a/mobile/android/components/SessionStore.js
+++ b/mobile/android/components/SessionStore.js
@@ -382,17 +382,17 @@ SessionStore.prototype = {
         let data = JSON.parse(aData);
         this._restoreTabs(data);
         break;
       }
     }
   },
 
   handleEvent: function ss_handleEvent(aEvent) {
-    let window = aEvent.currentTarget.ownerDocument.defaultView;
+    let window = aEvent.currentTarget.ownerGlobal;
     switch (aEvent.type) {
       case "TabOpen": {
         let browser = aEvent.target;
         log("TabOpen for tab " + window.BrowserApp.getTabForBrowser(browser).id);
         this.onTabAdd(window, browser);
         break;
       }
       case "TabClose": {
--- a/mobile/android/modules/NetErrorHelper.jsm
+++ b/mobile/android/modules/NetErrorHelper.jsm
@@ -161,15 +161,15 @@ handlers.wifi = {
     let network = Cc["@mozilla.org/network/network-link-service;1"].getService(Ci.nsINetworkLinkService);
     if (network.isLinkUp && network.linkStatusKnown) {
       // If everything worked, reload the page
       UITelemetry.addEvent("neterror.1", "button", null, "wifitoggle.reload");
       Services.obs.removeObserver(this, "network:link-status-changed");
 
       // Even at this point, Android sometimes lies about the real state of the network and this reload request fails.
       // Add a 500ms delay before refreshing the page.
-      node.ownerDocument.defaultView.setTimeout(function() {
+      node.ownerGlobal.setTimeout(function() {
         node.ownerDocument.location.reload(false);
       }, 500);
     }
   }
 }
 
--- a/mobile/android/tests/browser/robocop/testAccessibleCarets.js
+++ b/mobile/android/tests/browser/robocop/testAccessibleCarets.js
@@ -1,9 +1,9 @@
-// -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
+// -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 "use strict";
 
 var { classes: Cc, interfaces: Ci, utils: Cu } = Components;
 Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource://gre/modules/Messaging.jsm");
@@ -52,17 +52,17 @@ function isInputOrTextarea(element) {
 }
 
 /**
  * Return the selection controller based on element.
  */
 function elementSelection(element) {
   return (isInputOrTextarea(element)) ?
     element.editor.selection :
-    element.ownerDocument.defaultView.getSelection();
+    element.ownerGlobal.getSelection();
 }
 
 /**
  * Select the requested character of a target element, w/o affecting focus.
  */
 function selectElementChar(doc, element, char) {
   if (isInputOrTextarea(element)) {
     element.setSelectionRange(char, char + 1);
--- a/netwerk/cookie/test/browser/browser_originattributes.js
+++ b/netwerk/cookie/test/browser/browser_originattributes.js
@@ -15,17 +15,17 @@ let cm = Cc["@mozilla.org/cookiemanager;
 // opens `uri' in a new tab with the provided userContextId and focuses it.
 // returns the newly opened tab
 function* openTabInUserContext(uri, userContextId) {
   // open the tab in the correct userContextId
   let tab = gBrowser.addTab(uri, {userContextId});
 
   // select tab and make sure its browser is focused
   gBrowser.selectedTab = tab;
-  tab.ownerDocument.defaultView.focus();
+  tab.ownerGlobal.focus();
 
   let browser = gBrowser.getBrowserForTab(tab);
   // wait for tab load
   yield BrowserTestUtils.browserLoaded(browser);
 
   return {tab, browser};
 }
 
--- a/services/sync/tps/extensions/mozmill/resource/driver/controller.js
+++ b/services/sync/tps/extensions/mozmill/resource/driver/controller.js
@@ -846,17 +846,17 @@ MozMillController.prototype.mouseMove = 
     clientY = clientY ? clientY: 0;
 
     // make the mouse understand where it is on the screen
     var screenX = element.boxObject.screenX ? element.boxObject.screenX : 0;
     var screenY = element.boxObject.screenY ? element.boxObject.screenY : 0;
 
     var evt = element.ownerDocument.createEvent('MouseEvents');
     if (evt.initMouseEvent) {
-      evt.initMouseEvent('mousemove', true, true, element.ownerDocument.defaultView,
+      evt.initMouseEvent('mousemove', true, true, element.ownerGlobal,
                          1, screenX, screenY, clientX, clientY);
     } else {
       evt.initEvent('mousemove', true, true);
     }
 
     element.dispatchEvent(evt);
   };
 
--- a/services/sync/tps/extensions/mozmill/resource/driver/mozelement.js
+++ b/services/sync/tps/extensions/mozmill/resource/driver/mozelement.js
@@ -373,20 +373,20 @@ MozMillElement.prototype.mouseEvent = fu
     if (!target) {
       throw new Error(arguments.callee.name + ": could not find element " +
                       aExpectedEvent.target.getInfo());
     }
 
     EventUtils.synthesizeMouseExpectEvent(this.element, aOffsetX, aOffsetY, aEvent,
                                           target, aExpectedEvent.type,
                                           "MozMillElement.mouseEvent()",
-                                          this.element.ownerDocument.defaultView);
+                                          this.element.ownerGlobal);
   } else {
     EventUtils.synthesizeMouse(this.element, aOffsetX, aOffsetY, aEvent,
-                               this.element.ownerDocument.defaultView);
+                               this.element.ownerGlobal);
   }
 
   // Bug 555347
   // We don't know why this sleep is necessary but more investigation is needed
   // before it can be removed
   utils.sleep(0);
 
   return true;
@@ -564,17 +564,17 @@ MozMillElement.prototype.touchEvent = fu
   }
 
   // Scroll element into view otherwise the click will fail
   if ("scrollIntoView" in this.element) {
     this.element.scrollIntoView();
   }
 
   EventUtils.synthesizeTouch(this.element, aOffsetX, aOffsetY, aEvent,
-                             this.element.ownerDocument.defaultView);
+                             this.element.ownerGlobal);
 
   return true;
 };
 
 /**
  * Synthesize a touch tap event on the given element
  *
  * @param {Number} [aOffsetX=aElement.width / 2]
--- a/services/sync/tps/extensions/mozmill/resource/stdlib/utils.js
+++ b/services/sync/tps/extensions/mozmill/resource/stdlib/utils.js
@@ -264,17 +264,17 @@ function waitFor(callback, message, time
 
 /**
  * Calculates the x and y chrome offset for an element
  * See https://developer.mozilla.org/en/DOM/window.innerHeight
  *
  * Note this function will not work if the user has custom toolbars (via extension) at the bottom or left/right of the screen
  */
 function getChromeOffset(elem) {
-  var win = elem.ownerDocument.defaultView;
+  var win = elem.ownerGlobal;
   // Calculate x offset
   var chromeWidth = 0;
 
   if (win["name"] != "sidebar") {
     chromeWidth = win.outerWidth - win.innerWidth;
   }
 
   // Calculate y offset
@@ -299,17 +299,17 @@ function getChromeOffset(elem) {
 /**
  * Takes a screenshot of the specified DOM node
  */
 function takeScreenshot(node, highlights) {
   var rect, win, width, height, left, top, needsOffset;
   // node can be either a window or an arbitrary DOM node
   try {
     // node is an arbitrary DOM node
-    win = node.ownerDocument.defaultView;
+    win = node.ownerGlobal;
     rect = node.getBoundingClientRect();
     width = rect.width;
     height = rect.height;
     top = rect.top;
     left = rect.left;
     // offset for highlights not needed as they will be relative to this node
     needsOffset = false;
   } catch (e) {
--- a/testing/marionette/accessibility.js
+++ b/testing/marionette/accessibility.js
@@ -324,17 +324,17 @@ accessibility.Checks = class {
    * @throws ElementNotAccessibleError
    *     If |element|'s enabled state does not match |accessible|'s.
    */
   assertEnabled(accessible, element, enabled) {
     if (!accessible) {
       return;
     }
 
-    let win = element.ownerDocument.defaultView;
+    let win = element.ownerGlobal;
     let disabledAccessibility = this.matchState(
         accessible, accessibility.State.Unavailable);
     let explorable = win.getComputedStyle(element)
         .getPropertyValue("pointer-events") !== "none";
 
     let message;
     if (!explorable && !disabledAccessibility) {
       message = "Element is enabled but is not explorable via the " +
--- a/testing/marionette/capture.js
+++ b/testing/marionette/capture.js
@@ -30,17 +30,17 @@ capture.Format = {
  * @param {Array.<Node>=} highlights
  *     Optional array of nodes, around which a border will be marked to
  *     highlight them in the screenshot.
  *
  * @return {HTMLCanvasElement}
  *     The canvas element where the element has been painted on.
  */
 capture.element = function (node, highlights = []) {
-  let win = node.ownerDocument.defaultView;
+  let win = node.ownerGlobal;
   let rect = node.getBoundingClientRect();
 
   return capture.canvas(
       win,
       rect.left,
       rect.top,
       rect.width,
       rect.height,
--- a/testing/marionette/element.js
+++ b/testing/marionette/element.js
@@ -877,17 +877,17 @@ element.coordinates = function (
  * @param {number=} y
  *     Vertical offset relative to target.  Defaults to the centre of
  *     the target's bounding box.
  *
  * @return {boolean}
  *     True if if |el| is in viewport, false otherwise.
  */
 element.inViewport = function (el, x = undefined, y = undefined) {
-  let win = el.ownerDocument.defaultView;
+  let win = el.ownerGlobal;
   let c = element.coordinates(el, x, y);
   let vp = {
     top: win.pageYOffset,
     left: win.pageXOffset,
     bottom: (win.pageYOffset + win.innerHeight),
     right: (win.pageXOffset + win.innerWidth)
   };
 
@@ -911,17 +911,17 @@ element.inViewport = function (el, x = u
  * @param {number=} y
  *     Vertical offset relative to target.  Defaults to the centre of
  *     the target's bounding box.
  *
  * @return {boolean}
  *     True if visible, false otherwise.
  */
 element.isVisible = function (el, x = undefined, y = undefined) {
-  let win = el.ownerDocument.defaultView;
+  let win = el.ownerGlobal;
 
   // Bug 1094246: webdriver's isShown doesn't work with content xul
   if (!element.isXULElement(el) && !atom.isElementDisplayed(el, win)) {
     return false;
   }
 
   if (el.tagName.toLowerCase() == "body") {
     return true;
--- a/testing/marionette/event.js
+++ b/testing/marionette/event.js
@@ -73,17 +73,17 @@ event.sendMouseEvent = function (mouseEv
 
   if (!target.nodeType && typeof target != "string") {
     throw new TypeError("Target can only be a DOM element or a string: " + target);
   }
 
   if (!target.nodeType) {
     target = window.document.getElementById(target);
   } else {
-    window = window || target.ownerDocument.defaultView;
+    window = window || target.ownerGlobal;
   }
 
   let ev = window.document.createEvent("MouseEvent");
 
   let type = mouseEvent.type;
   let view = window;
 
   let detail = mouseEvent.detail;
--- a/testing/marionette/interaction.js
+++ b/testing/marionette/interaction.js
@@ -390,10 +390,10 @@ interaction.isElementSelected = function
   let a11y = accessibility.get(strict);
   return a11y.getAccessible(el).then(acc => {
     a11y.assertSelected(acc, el, selected);
     return selected;
   });
 };
 
 function getWindow(el) {
-  return el.ownerDocument.defaultView;
+  return el.ownerGlobal;
 }
--- a/testing/marionette/legacyaction.js
+++ b/testing/marionette/legacyaction.js
@@ -313,17 +313,17 @@ action.Chain.prototype.actions = functio
   }
 };
 
 /**
  * Given an element and a pair of coordinates, returns an array of the
  * form [clientX, clientY, pageX, pageY, screenX, screenY].
  */
 action.Chain.prototype.getCoordinateInfo = function (el, corx, cory) {
-  let win = el.ownerDocument.defaultView;
+  let win = el.ownerGlobal;
   return [
     corx, // clientX
     cory, // clientY
     corx + win.pageXOffset, // pageX
     cory + win.pageYOffset, // pageY
     corx + win.mozInnerScreenX, // screenX
     cory + win.mozInnerScreenY // screenY
   ];
@@ -444,17 +444,17 @@ action.Chain.prototype.generateEvents = 
 
       let [clientX, clientY, pageX, pageY, screenX, screenY] =
           this.getCoordinateInfo(target, x, y);
 
       event.initMouseEvent(
           "contextmenu",
           true,
           true,
-          target.ownerDocument.defaultView,
+          target.ownerGlobal,
           1,
           screenX,
           screenY,
           clientX,
           clientY,
           false,
           false,
           false,
--- a/testing/mochitest/BrowserTestUtils/BrowserTestUtils.jsm
+++ b/testing/mochitest/BrowserTestUtils/BrowserTestUtils.jsm
@@ -70,19 +70,19 @@ this.BrowserTestUtils = {
   withNewTab: Task.async(function* (options, taskFn) {
     if (typeof(options) == "string") {
       options = {
         gBrowser: Services.wm.getMostRecentWindow("navigator:browser").gBrowser,
         url: options
       }
     }
     let tab = yield BrowserTestUtils.openNewForegroundTab(options.gBrowser, options.url);
-    let originalWindow = tab.ownerDocument.defaultView;
+    let originalWindow = tab.ownerGlobal;
     let result = yield taskFn(tab.linkedBrowser);
-    let finalWindow = tab.ownerDocument.defaultView;
+    let finalWindow = tab.ownerGlobal;
     if (originalWindow == finalWindow && !tab.closing && tab.linkedBrowser) {
       yield BrowserTestUtils.removeTab(tab);
     } else {
       Services.console.logStringMessage(
         "BrowserTestUtils.withNewTab: Tab was already closed before " +
         "removeTab would have been called");
     }
     return Promise.resolve(result);
@@ -187,17 +187,17 @@ this.BrowserTestUtils = {
         return wantLoad(url);
       } else {
         // It's a string.
         return wantLoad == url;
       }
     }
 
     return new Promise(resolve => {
-      let mm = browser.ownerDocument.defaultView.messageManager;
+      let mm = browser.ownerGlobal.messageManager;
       mm.addMessageListener("browser-test-utils:loadEvent", function onLoad(msg) {
         if (msg.target == browser && (!msg.data.subframe || includeSubFrames) &&
             isWanted(msg.data.url)) {
           mm.removeMessageListener("browser-test-utils:loadEvent", onLoad);
           resolve(msg.data.url);
         }
       });
     });
@@ -385,17 +385,17 @@ this.BrowserTestUtils = {
    * @return {Promise}
    * @resolves When we started loading the given URI.
    */
   loadURI: Task.async(function* (browser, uri) {
     // Load the new URI.
     browser.loadURI(uri);
 
     // Nothing to do in non-e10s mode.
-    if (!browser.ownerDocument.defaultView.gMultiProcessBrowser) {
+    if (!browser.ownerGlobal.gMultiProcessBrowser) {
       return;
     }
 
     // Retrieve the given browser's current process type.
     let process = browser.isRemoteBrowser ? Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT
                                           : Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
 
     // If the new URI can't load in the browser's current process then we
@@ -685,17 +685,17 @@ this.BrowserTestUtils = {
    *
    * @return {Promise}
    * @resolves When an error page has been loaded in the browser.
    */
   waitForErrorPage(browser) {
     let waitForLoad = () =>
       this.waitForContentEvent(browser, "AboutNetErrorLoad", false, null, true);
 
-    let win = browser.ownerDocument.defaultView;
+    let win = browser.ownerGlobal;
     let tab = win.gBrowser.getTabForBrowser(browser);
     if (!tab || browser.isRemoteBrowser || !win.gMultiProcessBrowser) {
       return waitForLoad();
     }
 
     // We're going to switch remoteness when loading an error page. We need to be
     // quite careful in order to make sure we're adding the listener in time to
     // get this event:
@@ -815,17 +815,17 @@ this.BrowserTestUtils = {
       mm.addMessageListener("SessionStore:update", function onMessage(msg) {
         if (msg.targetFrameLoader == frameLoader && msg.data.isFinal) {
           mm.removeMessageListener("SessionStore:update", onMessage);
           resolve();
         }
       }, true);
 
       if (!dontRemove && !tab.closing) {
-        tab.ownerDocument.defaultView.gBrowser.removeTab(tab);
+        tab.ownerGlobal.gBrowser.removeTab(tab);
       }
     });
   },
 
   /**
    * Crashes a remote browser tab and cleans up the generated minidumps.
    * Resolves with the data from the .extra file (the crash annotations).
    *
@@ -974,17 +974,17 @@ this.BrowserTestUtils = {
     // This frame script will crash the remote browser as soon as it is
     // evaluated.
     let mm = browser.messageManager;
     mm.loadFrameScript("data:,(" + frame_script.toString() + ")();", false);
 
     yield Promise.all(expectedPromises);
 
     if (shouldShowTabCrashPage) {
-      let gBrowser = browser.ownerDocument.defaultView.gBrowser;
+      let gBrowser = browser.ownerGlobal.gBrowser;
       let tab = gBrowser.getTabForBrowser(browser);
       if (tab.getAttribute("crashed") != "true") {
         throw new Error("Tab should be marked as crashed");
       }
     }
 
     return extra;
   }),
@@ -997,17 +997,17 @@ this.BrowserTestUtils = {
    * @param {Element} element
    *        The element which should gain the attribute
    * @param {String} value (optional)
    *        Optional, the value the attribute should have.
    *
    * @returns {Promise}
    */
   waitForAttribute(attr, element, value) {
-    let MutationObserver = element.ownerDocument.defaultView.MutationObserver;
+    let MutationObserver = element.ownerGlobal.MutationObserver;
     return new Promise(resolve => {
       let mut = new MutationObserver(mutations => {
         if ((!value && element.getAttribute(attr)) ||
             (value && element.getAttribute(attr) === value)) {
           resolve();
           mut.disconnect();
           return;
         }
--- a/testing/mochitest/tests/SimpleTest/AsyncUtilsContent.js
+++ b/testing/mochitest/tests/SimpleTest/AsyncUtilsContent.js
@@ -36,17 +36,17 @@ addMessageListener("Test:SynthesizeMouse
 
   let left = data.x;
   let top = data.y;
   if (target) {
     if (target.ownerDocument !== content.document) {
       // Account for nodes found in iframes.
       let cur = target;
       do {
-        let frame = cur.ownerDocument.defaultView.frameElement;
+        let frame = cur.ownerGlobal.frameElement;
         let rect = frame.getBoundingClientRect();
 
         left += rect.left;
         top += rect.top;
 
         cur = frame;
       } while (cur && cur.ownerDocument !== content.document);
 
--- a/toolkit/components/addoncompat/RemoteAddonsParent.jsm
+++ b/toolkit/components/addoncompat/RemoteAddonsParent.jsm
@@ -437,30 +437,30 @@ var EventTargetParent = {
       if (target.localName == "browser") {
         return target;
       } else if (target.localName == "tab") {
         return target.linkedBrowser;
       }
 
       // Check if |target| is somewhere on the patch from the
       // <tabbrowser> up to the root element.
-      let window = target.ownerDocument.defaultView;
+      let window = target.ownerGlobal;
       if (window && target.contains(window.gBrowser)) {
         return window;
       }
     }
 
     return null;
   },
 
   // When a given event fires in the child, we fire it on the
   // <browser> element and the window since those are the two possible
   // results of redirectEventTarget.
   getTargets(browser) {
-    let window = browser.ownerDocument.defaultView;
+    let window = browser.ownerGlobal;
     return [browser, window];
   },
 
   addEventListener(addon, target, type, listener, useCapture, wantsUntrusted, delayedWarning) {
     let newTarget = this.redirectEventTarget(target);
     if (!newTarget) {
       return;
     }
@@ -701,17 +701,17 @@ ContentDocShellTreeItemInterposition.get
     let browser = RemoteAddonsParent.globalToBrowser.get(chromeGlobal);
     if (!browser) {
       // Somehow we have a CPOW from the child, but it hasn't sent us
       // its global yet. That shouldn't happen, but return null just
       // in case.
       return null;
     }
 
-    let chromeWin = browser.ownerDocument.defaultView;
+    let chromeWin = browser.ownerGlobal;
 
     // Return that window's docshell.
     return chromeWin.QueryInterface(Ci.nsIInterfaceRequestor)
       .getInterface(Ci.nsIWebNavigation)
       .QueryInterface(Ci.nsIDocShellTreeItem);
   };
 
 function chromeGlobalForContentWindow(window) {
@@ -976,44 +976,44 @@ function wrapProgressListener(kind, list
   };
   let listenerProxy = new Proxy(listener, ListenerHandler);
 
   progressListeners[kind].set(listener, listenerProxy);
   return listenerProxy;
 }
 
 TabBrowserElementInterposition.methods.addProgressListener = function(addon, target, listener) {
-  if (!target.ownerDocument.defaultView.gMultiProcessBrowser) {
+  if (!target.ownerGlobal.gMultiProcessBrowser) {
     return target.addProgressListener(listener);
   }
 
   NotificationTracker.add(["web-progress", addon]);
   return target.addProgressListener(wrapProgressListener("global", listener));
 };
 
 TabBrowserElementInterposition.methods.removeProgressListener = function(addon, target, listener) {
-  if (!target.ownerDocument.defaultView.gMultiProcessBrowser) {
+  if (!target.ownerGlobal.gMultiProcessBrowser) {
     return target.removeProgressListener(listener);
   }
 
   NotificationTracker.remove(["web-progress", addon]);
   return target.removeProgressListener(wrapProgressListener("global", listener));
 };
 
 TabBrowserElementInterposition.methods.addTabsProgressListener = function(addon, target, listener) {
-  if (!target.ownerDocument.defaultView.gMultiProcessBrowser) {
+  if (!target.ownerGlobal.gMultiProcessBrowser) {
     return target.addTabsProgressListener(listener);
   }
 
   NotificationTracker.add(["web-progress", addon]);
   return target.addTabsProgressListener(wrapProgressListener("tabs", listener));
 };
 
 TabBrowserElementInterposition.methods.removeTabsProgressListener = function(addon, target, listener) {
-  if (!target.ownerDocument.defaultView.gMultiProcessBrowser) {
+  if (!target.ownerGlobal.gMultiProcessBrowser) {
     return target.removeTabsProgressListener(listener);
   }
 
   NotificationTracker.remove(["web-progress", addon]);
   return target.removeTabsProgressListener(wrapProgressListener("tabs", listener));
 };
 
 var ChromeWindowInterposition = new Interposition("ChromeWindowInterposition",
--- a/toolkit/components/narrate/Narrator.jsm
+++ b/toolkit/components/narrate/Narrator.jsm
@@ -315,17 +315,17 @@ Highlighter.prototype = {
    *
    * @param {Number} startOffset the start offset
    * @param {Number} length the length in characters of the range
    */
   highlight(startOffset, length) {
     let containerRect = this.container.getBoundingClientRect();
     let range = this._getRange(startOffset, startOffset + length);
     let rangeRects = range.getClientRects();
-    let win = this.container.ownerDocument.defaultView;
+    let win = this.container.ownerGlobal;
     let computedStyle = win.getComputedStyle(range.endContainer.parentNode);
     let nodes = this._getFreshHighlightNodes(rangeRects.length);
 
     let textStyle = {};
     for (let textStyleRule of kTextStylesRules) {
       textStyle[textStyleRule] = computedStyle[textStyleRule];
     }
 
--- a/toolkit/components/narrate/test/NarrateTestUtils.jsm
+++ b/toolkit/components/narrate/test/NarrateTestUtils.jsm
@@ -20,17 +20,17 @@ this.NarrateTestUtils = {
   VOICE_SELECT_LABEL: "#narrate-voices .select-toggle .current-voice",
   RATE: "#narrate-rate-input",
   START: "#narrate-dropdown:not(.speaking) #narrate-start-stop",
   STOP: "#narrate-dropdown.speaking #narrate-start-stop",
   BACK: "#narrate-skip-previous",
   FORWARD: "#narrate-skip-next",
 
   isVisible(element) {
-    let style = element.ownerDocument.defaultView.getComputedStyle(element);
+    let style = element.ownerGlobal.getComputedStyle(element);
     if (style.display == "none") {
       return false;
     } else if (style.visibility != "visible") {
       return false;
     } else if (style.display == "-moz-popup" && element.state != "open") {
       return false;
     }
 
--- a/toolkit/components/passwordmgr/LoginManagerParent.jsm
+++ b/toolkit/components/passwordmgr/LoginManagerParent.jsm
@@ -271,17 +271,17 @@ var LoginManagerParent = {
 
     // XXX In the E10S case, we're responsible for showing our own
     // autocomplete popup here because the autocomplete protocol hasn't
     // been e10s-ized yet. In the non-e10s case, our caller is responsible
     // for showing the autocomplete popup (via the regular
     // nsAutoCompleteController).
     if (remote) {
       let results = new UserAutoCompleteResult(searchString, matchingLogins, {isSecure});
-      AutoCompletePopup.showPopupWithResults({ browser: target.ownerDocument.defaultView, rect, results });
+      AutoCompletePopup.showPopupWithResults({ browser: target.ownerGlobal, rect, results });
     }
 
     // Convert the array of nsILoginInfo to vanilla JS objects since nsILoginInfo
     // doesn't support structured cloning.
     var jsLogins = LoginHelper.loginsToVanillaObjects(matchingLogins);
     target.messageManager.sendAsyncMessage("RemoteLogins:loginsAutoCompleted", {
       requestId,
       logins: jsLogins,
@@ -290,17 +290,17 @@ var LoginManagerParent = {
 
   onFormSubmit(hostname, formSubmitURL,
                          usernameField, newPasswordField,
                          oldPasswordField, openerTopWindow,
                          target) {
     function getPrompter() {
       var prompterSvc = Cc["@mozilla.org/login-manager/prompter;1"].
                         createInstance(Ci.nsILoginManagerPrompter);
-      prompterSvc.init(target.ownerDocument.defaultView);
+      prompterSvc.init(target.ownerGlobal);
       prompterSvc.browser = target;
       prompterSvc.opener = openerTopWindow;
       return prompterSvc;
     }
 
     function recordLoginUse(login) {
       // Update the lastUsed timestamp and increment the use count.
       let propBag = Cc["@mozilla.org/hash-property-bag;1"].
@@ -479,12 +479,12 @@ var LoginManagerParent = {
   setHasInsecureLoginForms(browser, hasInsecureLoginForms) {
     let state = this.stateForBrowser(browser);
 
     // Update the data to use to the latest known values. Since messages are
     // processed in order, this will always be the latest version to use.
     state.hasInsecureLoginForms = hasInsecureLoginForms;
 
     // Report the insecure login form state immediately.
-    browser.dispatchEvent(new browser.ownerDocument.defaultView
+    browser.dispatchEvent(new browser.ownerGlobal
                                  .CustomEvent("InsecureLoginFormsStateChange"));
   },
 };
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_editing.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_editing.js
@@ -23,17 +23,17 @@ function getPassword(row) {
 
 function synthesizeDblClickOnCell(aTree, column, row) {
   let tbo = aTree.treeBoxObject;
   let rect = tbo.getCoordsForCellItem(row, aTree.columns[column], "text");
   let x = rect.x + rect.width / 2;
   let y = rect.y + rect.height / 2;
   // Simulate the double click.
   EventUtils.synthesizeMouse(aTree.body, x, y, { clickCount: 2 },
-                             aTree.ownerDocument.defaultView);
+                             aTree.ownerGlobal);
 }
 
 function* togglePasswords() {
   pwmgrdlg.document.querySelector("#togglePasswords").doCommand();
   yield new Promise(resolve => waitForFocus(resolve, pwmgrdlg));
 }
 
 function* editUsernamePromises(site, oldUsername, newUsername) {
--- a/toolkit/components/passwordmgr/test/chrome/notification_common.js
+++ b/toolkit/components/passwordmgr/test/chrome/notification_common.js
@@ -21,17 +21,17 @@ function getPopupNotifications(aWindow) 
     var Cc = SpecialPowers.Cc;
     ok(Ci != null, "Access Ci");
     ok(Cc != null, "Access Cc");
 
     var chromeWin = SpecialPowers.wrap(aWindow)
                                  .QueryInterface(Ci.nsIInterfaceRequestor)
                                  .getInterface(Ci.nsIWebNavigation)
                                  .QueryInterface(Ci.nsIDocShell)
-                                 .chromeEventHandler.ownerDocument.defaultView;
+                                 .chromeEventHandler.ownerGlobal;
 
     var popupNotifications = chromeWin.PopupNotifications;
     return popupNotifications;
 }
 
 
 /**
  * Checks if we have a password popup notification
@@ -95,17 +95,17 @@ function dumpNotifications() {
         ok(true, "#" + i + ": " + notes[i].id);
     }
 
     // Notification bars
     var chromeWin = SpecialPowers.wrap(window.top)
                            .QueryInterface(Ci.nsIInterfaceRequestor)
                            .getInterface(Ci.nsIWebNavigation)
                            .QueryInterface(Ci.nsIDocShell)
-                           .chromeEventHandler.ownerDocument.defaultView;
+                           .chromeEventHandler.ownerGlobal;
     var nb = chromeWin.getNotificationBox(window.top);
     notes = nb.allNotifications;
     ok(true, "Found " + notes.length + " notification bars.");
     for (let i = 0; i < notes.length; i++) {
         ok(true, "#" + i + ": " + notes[i].getAttribute("value"));
     }
   } catch (e) { todo(false, "WOAH! " + e); }
 }
--- a/toolkit/components/processsingleton/MainProcessSingleton.js
+++ b/toolkit/components/processsingleton/MainProcessSingleton.js
@@ -47,17 +47,17 @@ MainProcessSingleton.prototype = {
       Cu.reportError("Invalid argument passed to window.external.AddSearchProvider: " + ex);
 
       var searchBundle = Services.strings.createBundle("chrome://global/locale/search/search.properties");
       var brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties");
       var brandName = brandBundle.GetStringFromName("brandShortName");
       var title = searchBundle.GetStringFromName("error_invalid_engine_title");
       var msg = searchBundle.formatStringFromName("error_invalid_engine_msg",
                                                   [brandName], 1);
-      Services.ww.getNewPrompter(browser.ownerDocument.defaultView).alert(title, msg);
+      Services.ww.getNewPrompter(browser.ownerGlobal).alert(title, msg);
       return;
     }
 
     Services.search.init(function(status) {
       if (status != Cr.NS_OK)
         return;
 
       Services.search.addEngine(engineURL.spec, null, iconURL ? iconURL.spec : null, true);
--- a/toolkit/components/prompts/src/nsPrompter.js
+++ b/toolkit/components/prompts/src/nsPrompter.js
@@ -294,18 +294,17 @@ var PromptUtilsTemp = {
             // Get the topmost window, in case we're in a frame.
             var promptWin = domWin.top;
 
             // Get the chrome window for the content window we're using.
             // (Unwrap because we need a non-IDL property below.)
             var chromeWin = promptWin.QueryInterface(Ci.nsIInterfaceRequestor)
                                      .getInterface(Ci.nsIWebNavigation)
                                      .QueryInterface(Ci.nsIDocShell)
-                                     .chromeEventHandler.ownerDocument
-                                     .defaultView.wrappedJSObject;
+                                     .chromeEventHandler.ownerGlobal.wrappedJSObject;
 
             if (chromeWin.getTabModalPromptBox)
                 promptBox = chromeWin.getTabModalPromptBox(promptWin);
         } catch (e) {
             // If any errors happen, just assume no tabmodal prompter.
         }
 
         return promptBox;
--- a/toolkit/components/satchel/AutoCompletePopup.jsm
+++ b/toolkit/components/satchel/AutoCompletePopup.jsm
@@ -139,17 +139,17 @@ this.AutoCompletePopup = {
   showPopupWithResults({ browser, rect, dir, results }) {
     if (!results.length || this.openedPopup) {
       // We shouldn't ever be showing an empty popup, and if we
       // already have a popup open, the old one needs to close before
       // we consider opening a new one.
       return;
     }
 
-    let window = browser.ownerDocument.defaultView;
+    let window = browser.ownerGlobal;
     let tabbrowser = window.gBrowser;
     if (Services.focus.activeWindow != window ||
         tabbrowser.selectedBrowser != browser) {
       // We were sent a message from a window or tab that went into the
       // background, so we'll ignore it for now.
       return;
     }
 
--- a/toolkit/components/satchel/nsFormAutoComplete.js
+++ b/toolkit/components/satchel/nsFormAutoComplete.js
@@ -42,17 +42,17 @@ function isAutocompleteDisabled(aField) 
  *
  *        inputName (string):
  *          The name of the input to do the FormHistory look-up
  *          with. If this is searchbar-history, then formField
  *          needs to be null, otherwise constructing will throw.
  */
 function FormHistoryClient({ formField, inputName }) {
     if (formField && inputName != this.SEARCHBAR_ID) {
-        let window = formField.ownerDocument.defaultView;
+        let window = formField.ownerGlobal;
         let topDocShell = window.QueryInterface(Ci.nsIInterfaceRequestor)
                              .getInterface(Ci.nsIDocShell)
                              .sameTypeRootTreeItem
                              .QueryInterface(Ci.nsIDocShell);
         this.mm = topDocShell.QueryInterface(Ci.nsIInterfaceRequestor)
                              .getInterface(Ci.nsIContentFrameMessageManager);
     } else {
         if (inputName == this.SEARCHBAR_ID) {
--- a/toolkit/components/tooltiptext/TooltipTextProvider.js
+++ b/toolkit/components/tooltiptext/TooltipTextProvider.js
@@ -14,17 +14,17 @@ TooltipTextProvider.prototype = {
     // Don't show the tooltip if the tooltip node is a document, browser, or disconnected.
     if (!tipElement || !tipElement.ownerDocument ||
         tipElement.localName == "browser" ||
         (tipElement.ownerDocument.compareDocumentPosition(tipElement) &
          tipElement.ownerDocument.DOCUMENT_POSITION_DISCONNECTED)) {
       return false;
     }
 
-    var defView = tipElement.ownerDocument.defaultView;
+    var defView = tipElement.ownerGlobal;
     // XXX Work around bug 350679:
     // "Tooltips can be fired in documents with no view".
     if (!defView)
       return false;
 
     const XLinkNS = "http://www.w3.org/1999/xlink";
     const XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
 
--- a/toolkit/content/browser-content.js
+++ b/toolkit/content/browser-content.js
@@ -79,20 +79,20 @@ var ClickEventHandler = {
       // do not use overflow based autoscroll for <html> and <body>
       // Elements or non-html elements such as svg or Document nodes
       // also make sure to skip select elements that are not multiline
       if (!(this._scrollable instanceof content.HTMLElement) ||
           ((this._scrollable instanceof content.HTMLSelectElement) && !this._scrollable.multiple)) {
         continue;
       }
 
-      var overflowx = this._scrollable.ownerDocument.defaultView
+      var overflowx = this._scrollable.ownerGlobal
                           .getComputedStyle(this._scrollable)
                           .getPropertyValue("overflow-x");
-      var overflowy = this._scrollable.ownerDocument.defaultView
+      var overflowy = this._scrollable.ownerGlobal
                           .getComputedStyle(this._scrollable)
                           .getPropertyValue("overflow-y");
       // we already discarded non-multiline selects so allow vertical
       // scroll for multiline ones directly without checking for a
       // overflow property
       var scrollVert = this._scrollable.scrollTopMax &&
         (this._scrollable instanceof content.HTMLSelectElement ||
          scrollingAllowed.indexOf(overflowy) >= 0);
@@ -106,17 +106,17 @@ var ClickEventHandler = {
         break;
       } else if (scrollVert) {
         this._scrolldir = "NS";
         break;
       }
     }
 
     if (!this._scrollable) {
-      this._scrollable = aNode.ownerDocument.defaultView;
+      this._scrollable = aNode.ownerGlobal;
       if (this._scrollable.scrollMaxX != this._scrollable.scrollMinX) {
         this._scrolldir = this._scrollable.scrollMaxY !=
                           this._scrollable.scrollMinY ? "NSEW" : "EW";
       } else if (this._scrollable.scrollMaxY != this._scrollable.scrollMinY) {
         this._scrolldir = "NS";
       } else if (this._scrollable.frameElement) {
         this.findNearestScrollableElement(this._scrollable.frameElement);
       } else {
@@ -931,17 +931,17 @@ addMessageListener("WebChannelMessageToC
     let eventTarget = e.objects.eventTarget || content;
 
     // Use nodePrincipal if available, otherwise fallback to document principal.
     let targetPrincipal = eventTarget instanceof Ci.nsIDOMWindow ? eventTarget.document.nodePrincipal : eventTarget.nodePrincipal;
 
     if (e.principal.subsumes(targetPrincipal)) {
       // If eventTarget is a window, use it as the targetWindow, otherwise
       // find the window that owns the eventTarget.
-      let targetWindow = eventTarget instanceof Ci.nsIDOMWindow ? eventTarget : eventTarget.ownerDocument.defaultView;
+      let targetWindow = eventTarget instanceof Ci.nsIDOMWindow ? eventTarget : eventTarget.ownerGlobal;
 
       eventTarget.dispatchEvent(new targetWindow.CustomEvent("WebChannelMessageToContent", {
         detail: Cu.cloneInto({
           id: e.data.id,
           message: e.data.message,
         }, targetWindow),
       }));
     } else {
@@ -1235,17 +1235,17 @@ var ViewSelectionSource = {
 
   /**
    * Reformat the source of a MathML node to highlight the node that was targetted.
    *
    * @param node
    *        Some element within the fragment of interest.
    */
   getMathMLSelection(node) {
-    var Node = node.ownerDocument.defaultView.Node;
+    var Node = node.ownerGlobal.Node;
     this._lineCount = 0;
     this._startTargetLine = 0;
     this._endTargetLine = 0;
     this._targetNode = node;
     if (this._targetNode && this._targetNode.nodeType == Node.TEXT_NODE)
       this._targetNode = this._targetNode.parentNode;
 
     // walk up the tree to the top-level element (e.g., <math>, <svg>)
@@ -1292,17 +1292,17 @@ var ViewSelectionSource = {
     var str = "";
     for (var i = 0; i < node.childNodes.length; i++) {
       str += this.getOuterMarkup(node.childNodes.item(i), indent);
     }
     return str;
   },
 
   getOuterMarkup(node, indent) {
-    var Node = node.ownerDocument.defaultView.Node;
+    var Node = node.ownerGlobal.Node;
     var newline = "";
     var padding = "";
     var str = "";
     if (node == this._targetNode) {
       this._startTargetLine = this._lineCount;
       str += '</pre><pre id="target">';
     }
 
@@ -1541,17 +1541,17 @@ let AutoCompletePopup = {
   },
 
   openAutocompletePopup(input, element) {
     if (this._popupOpen || !input) {
       return;
     }
 
     let rect = BrowserUtils.getElementBoundingScreenRect(element);
-    let window = element.ownerDocument.defaultView;
+    let window = element.ownerGlobal;
     let dir = window.getComputedStyle(element).direction;
     let results = this.getResultsFromController(input);
 
     sendAsyncMessage("FormAutoComplete:MaybeOpenPopup",
                      { results, rect, dir });
     this._input = input;
   },
 
@@ -1662,17 +1662,17 @@ let DateTimePickerListener = {
     removeMessageListener("FormDateTime:PickerValueChanged", this);
     removeMessageListener("FormDateTime:PickerClosed", this);
   },
 
   /**
    * Helper function that returns the CSS direction property of the element.
    */
   getComputedDirection(aElement) {
-    return aElement.ownerDocument.defaultView.getComputedStyle(aElement)
+    return aElement.ownerGlobal.getComputedStyle(aElement)
       .getPropertyValue("direction");
   },
 
   /**
    * Helper function that returns the rect of the element, which is the position
    * relative to the left/top of the content area.
    */
   getBoundingContentRect(aElement) {
--- a/toolkit/content/customizeToolbar.js
+++ b/toolkit/content/customizeToolbar.js
@@ -792,12 +792,12 @@ function isUnwantedDragEvent(aEvent) {
   /* Discard drag events that originated from a separate window to
      prevent content->chrome privilege escalations. */
   let mozSourceNode = aEvent.dataTransfer.mozSourceNode;
   // mozSourceNode is null in the dragStart event handler or if
   // the drag event originated in an external application.
   if (!mozSourceNode) {
     return true;
   }
-  let sourceWindow = mozSourceNode.ownerDocument.defaultView;
+  let sourceWindow = mozSourceNode.ownerGlobal;
   return sourceWindow != window && sourceWindow != gToolboxDocument.defaultView;
 }
 
--- a/toolkit/content/tests/chrome/test_arrowpanel.xul
+++ b/toolkit/content/tests/chrome/test_arrowpanel.xul
@@ -223,17 +223,17 @@ function setScale(win, scale)
   zoomFactor = scale;
 }
 
 function checkPanelPosition(panel)
 {
   let anchor = panel.anchorNode;
   let adj = 0, hwinpos = 0, vwinpos = 0;
   if (anchor.ownerDocument != document) {
-    var framerect = anchor.ownerDocument.defaultView.frameElement.getBoundingClientRect();
+    var framerect = anchor.ownerGlobal.frameElement.getBoundingClientRect();
     hwinpos = framerect.left;
     vwinpos = framerect.top;
   }
 
   // Positions are reversed in rtl yet the coordinates used in the computations
   // are not, so flip the expected label side and anchor edge.
   var isRTL = (window.getComputedStyle(panel).direction == "rtl");
   if (isRTL) {
--- a/toolkit/content/tests/chrome/window_browser_drop.xul
+++ b/toolkit/content/tests/chrome/window_browser_drop.xul
@@ -67,17 +67,17 @@ function* expectLink(browser, expectedLi
       }
       lastLinks = links;
       resolve(links);
     };
   });
 
   function dropOnBrowserSync() {
     let dropEl = onbody ? browser.contentDocument.body : browser;
-    synthesizeDrop(dropEl, dropEl, data, "", dropEl.ownerDocument.defaultView);
+    synthesizeDrop(dropEl, dropEl, data, "", dropEl.ownerGlobal);
   }
   let links;
   if (browser.isRemoteBrowser) {
     let remoteLinks = yield dropOnRemoteBrowserAsync(browser, data, expectedLinks.length != 0);
     is(remoteLinks.length, expectedLinks.length, testid + " remote links length");
     for (let i = 0, length = remoteLinks.length; i < length; i++) {
       is(remoteLinks[i].url, expectedLinks[i].url, testid + "[" + i + "] remote link");
       is(remoteLinks[i].name, expectedLinks[i].name, testid + "[" + i + "] remote name");
--- a/toolkit/content/tests/widgets/test_popupreflows.xul
+++ b/toolkit/content/tests/widgets/test_popupreflows.xul
@@ -46,17 +46,17 @@ let observer = {
 };
 
 // A test utility that counts the reflows caused by a test function.  If the
 // count of reflows isn't what is expected, it causes a test failure and logs
 // the stack trace of all seen reflows.
 function countReflows(testfn, expected) {
   let deferred = Promise.defer();
   observer.reflows = [];
-  let docShell = panel.ownerDocument.defaultView
+  let docShell = panel.ownerGlobal
                   .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                   .getInterface(Components.interfaces.nsIWebNavigation)
                   .QueryInterface(Components.interfaces.nsIDocShell);
   docShell.addWeakReflowObserver(observer);
   testfn().then(() => {
     docShell.removeWeakReflowObserver(observer);
     SimpleTest.is(observer.reflows.length, expected, "correct number of reflows");
     if (observer.reflows.length != expected) {
--- a/toolkit/content/widgets/autocomplete.xml
+++ b/toolkit/content/widgets/autocomplete.xml
@@ -838,25 +838,25 @@
             this.mInput = aInput;
             this.view = aInput.controller.QueryInterface(Components.interfaces.nsITreeView);
             this.invalidate();
 
             this.showCommentColumn = this.mInput.showCommentColumn;
             this.showImageColumn = this.mInput.showImageColumn;
 
             var rect = aElement.getBoundingClientRect();
-            var nav = aElement.ownerDocument.defaultView.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
+            var nav = aElement.ownerGlobal.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                               .getInterface(Components.interfaces.nsIWebNavigation);
             var docShell = nav.QueryInterface(Components.interfaces.nsIDocShell);
             var docViewer = docShell.contentViewer;
             var width = (rect.right - rect.left) * docViewer.fullZoom;
             this.setAttribute("width", width > 100 ? width : 100);
 
             // Adjust the direction of the autocomplete popup list based on the textbox direction, bug 649840
-            var popupDirection = aElement.ownerDocument.defaultView.getComputedStyle(aElement).direction;
+            var popupDirection = aElement.ownerGlobal.getComputedStyle(aElement).direction;
             this.style.direction = popupDirection;
 
             this.openPopup(aElement, "after_start", 0, 0, false, false);
           }
         ]]></body>
       </method>
 
       <method name="invalidate">
--- a/toolkit/content/widgets/button.xml
+++ b/toolkit/content/widgets/button.xml
@@ -77,17 +77,17 @@
                 onget="return this.getAttribute('autoCheck') == 'true';"
                 onset="this.setAttribute('autoCheck', val); return val;"/>
 
       <method name ="filterButtons">
         <parameter name="node"/>
         <body>
         <![CDATA[
           // if the node isn't visible, don't descend into it.
-          var cs = node.ownerDocument.defaultView.getComputedStyle(node);
+          var cs = node.ownerGlobal.getComputedStyle(node);
           if (cs.visibility != "visible" || cs.display == "none") {
             return NodeFilter.FILTER_REJECT;
           }
           // but it may be a popup element, in which case we look at "state"...
           if (cs.display == "-moz-popup" && node.state != "open") {
             return NodeFilter.FILTER_REJECT;
           }
           // OK - the node seems visible, so it is a candidate.
--- a/toolkit/content/widgets/popup.xml
+++ b/toolkit/content/widgets/popup.xml
@@ -665,17 +665,17 @@
           }
         ]]>
         </body>
       </method>
       <method name="_clearScrollTimer">
         <body>
         <![CDATA[
           if (this._scrollTimer) {
-            this.ownerDocument.defaultView.clearInterval(this._scrollTimer);
+            this.ownerGlobal.clearInterval(this._scrollTimer);
             this._scrollTimer = 0;
           }
         ]]>
         </body>
       </method>
     </implementation>
     <handlers>
       <handler event="popupshown">
@@ -739,17 +739,17 @@
             }
           }
 
           if (this._draggingState == this.DRAG_OVER_POPUP &&
               (event.screenY <= popupRect.top || event.screenY >= popupRect.bottom)) {
             let scrollAmount = event.screenY <= popupRect.top ? -1 : 1;
             this.scrollBox.scrollByIndex(scrollAmount);
 
-            let win = this.ownerDocument.defaultView;
+            let win = this.ownerGlobal;
             this._scrollTimer = win.setInterval(() => {
               this.scrollBox.scrollByIndex(scrollAmount);
             }, this.AUTOSCROLL_INTERVAL);
           }
         }
       ]]>
       </handler>
     </handlers>
--- a/toolkit/modules/BrowserUtils.jsm
+++ b/toolkit/modules/BrowserUtils.jsm
@@ -154,25 +154,25 @@ this.BrowserUtils = {
   /**
    * For a given DOM element, returns its position as an offset from the topmost
    * window. In a content process, the coordinates returned will be relative to
    * the left/top of the topmost content area. If aInScreenCoords is true,
    * screen coordinates will be returned instead.
    */
   getElementBoundingRect(aElement, aInScreenCoords) {
     let rect = aElement.getBoundingClientRect();
-    let win = aElement.ownerDocument.defaultView;
+    let win = aElement.ownerGlobal;
 
     let x = rect.left, y = rect.top;
 
     // We need to compensate for any iframes that might shift things
     // over. We also need to compensate for zooming.
     let parentFrame = win.frameElement;
     while (parentFrame) {
-      win = parentFrame.ownerDocument.defaultView;
+      win = parentFrame.ownerGlobal;
       let cstyle = win.getComputedStyle(parentFrame);
 
       let framerect = parentFrame.getBoundingClientRect();
       x += framerect.left + parseFloat(cstyle.borderLeftWidth) + parseFloat(cstyle.paddingLeft);
       y += framerect.top + parseFloat(cstyle.borderTopWidth) + parseFloat(cstyle.paddingTop);
 
       parentFrame = win.frameElement;
     }
--- a/toolkit/modules/DateTimePickerHelper.jsm
+++ b/toolkit/modules/DateTimePickerHelper.jsm
@@ -114,17 +114,17 @@ this.DateTimePickerHelper = {
     this._anchor.left = rect.left;
     this._anchor.top = rect.top;
     this._anchor.width = rect.width;
     this._anchor.height = rect.height;
     this._anchor.hidden = false;
 
     debug("Opening picker with details: " + JSON.stringify(detail));
 
-    let window = aBrowser.ownerDocument.defaultView;
+    let window = aBrowser.ownerGlobal;
     let tabbrowser = window.gBrowser;
     if (Services.focus.activeWindow != window ||
         tabbrowser.selectedBrowser != aBrowser) {
       // We were sent a message from a window or tab that went into the
       // background, so we'll ignore it for now.
       return;
     }
 
--- a/toolkit/modules/Finder.jsm
+++ b/toolkit/modules/Finder.jsm
@@ -352,17 +352,17 @@ Finder.prototype = {
   },
 
   keyPress(aEvent) {
     let controller = this._getSelectionController(this._getWindow());
 
     switch (aEvent.keyCode) {
       case Ci.nsIDOMKeyEvent.DOM_VK_RETURN:
         if (this._fastFind.foundLink) {
-          let view = this._fastFind.foundLink.ownerDocument.defaultView;
+          let view = this._fastFind.foundLink.ownerGlobal;
           this._fastFind.foundLink.dispatchEvent(new view.MouseEvent("click", {
             view,
             cancelable: true,
             bubbles: true,
             ctrlKey: aEvent.ctrlKey,
             altKey: aEvent.altKey,
             shiftKey: aEvent.shiftKey,
             metaKey: aEvent.metaKey
--- a/toolkit/modules/FinderHighlighter.jsm
+++ b/toolkit/modules/FinderHighlighter.jsm
@@ -276,17 +276,17 @@ FinderHighlighter.prototype = {
    * Add a range to the find selection, i.e. highlight it, and if it's inside an
    * editable node, track it.
    *
    * @param {nsIDOMRange} range Range object to be highlighted
    */
   highlightRange(range) {
     let node = range.startContainer;
     let editableNode = this._getEditableNode(node);
-    let window = node.ownerDocument.defaultView;
+    let window = node.ownerGlobal;
     let controller = this.finder._getSelectionController(window);
     if (editableNode) {
       controller = editableNode.editor.selectionController;
     }
 
     if (this._modal) {
       this._modalHighlight(range, controller, window);
     } else {
@@ -637,17 +637,17 @@ FinderHighlighter.prototype = {
    *
    * @param  {nsIDOMRange} range Range to fetch style info from.
    * @return {Object} Dictionary consisting of the styles that were found.
    */
   _getRangeFontStyle(range) {
     let node = range.startContainer;
     while (node.nodeType != 1)
       node = node.parentNode;
-    let style = node.ownerDocument.defaultView.getComputedStyle(node);
+    let style = node.ownerGlobal.getComputedStyle(node);
     let props = {};
     for (let prop of kFontPropsCamelCase) {
       if (prop in style && style[prop])
         props[prop] = style[prop];
     }
     return props;
   },
 
@@ -787,17 +787,17 @@ FinderHighlighter.prototype = {
    * for use by the drawing function of the highlighter.
    *
    * @param  {nsIDOMRange} range  Range to fetch the rectangles from
    * @param  {Object}      [dict] Dictionary of properties belonging to
    *                              the currently active window
    * @return {Set}         Set of rects that were found for the range
    */
   _getRangeRectsAndTexts(range, dict = null) {
-    let window = range.startContainer.ownerDocument.defaultView;
+    let window = range.startContainer.ownerGlobal;
     let bounds;
     // If the window is part of a frameset, try to cache the bounds query.
     if (dict && dict.frames.has(window)) {
       bounds = dict.frames.get(window);
       if (!bounds) {
         bounds = this._getRootBounds(window);
         dict.frames.set(window, bounds);
       }
@@ -831,17 +831,17 @@ FinderHighlighter.prototype = {
    *                                        is dynamic as per the rules in
    *                                        `_isInDynamicContainer()`. Optional,
    *                                        defaults to `true`
    * @param  {Object}      [dict]           Dictionary of properties belonging to
    *                                        the currently active window
    * @return {Set}         Set of rects that were found for the range
    */
   _updateRangeRects(range, checkIfDynamic = true, dict = null) {
-    let window = range.startContainer.ownerDocument.defaultView;
+    let window = range.startContainer.ownerGlobal;
     let rectsAndTexts = this._getRangeRectsAndTexts(range, dict);
 
     // Only fetch the rect at this point, if not passed in as argument.
     dict = dict || this.getForWindow(window.top);
     let oldRectsAndTexts = dict.modalHighlightRectsMap.get(range);
     dict.modalHighlightRectsMap.set(range, rectsAndTexts);
     // Check here if we suddenly went down to zero rects from more than zero before,
     // which indicates that we should re-iterate the document.
@@ -894,17 +894,17 @@ FinderHighlighter.prototype = {
     // 1. No outline nodes were built before, or
     // 2. When the amount of rectangles to draw is different from before, or
     // 3. When there's more than one rectangle to draw, because it's impossible
     //    to animate that consistently with AnonymousContent nodes.
     let rebuildOutline = (!outlineAnonNode || rectCount !== previousRectCount ||
       rectCount != 1);
     dict.previousRangeRectsAndTexts = rectsAndTexts;
 
-    let window = range.startContainer.ownerDocument.defaultView.top;
+    let window = range.startContainer.ownerGlobal.top;
     let document = window.document;
     // First see if we need to and can remove the previous outline nodes.
     if (rebuildOutline)
       this._removeRangeOutline(window);
 
     // Abort when there's no text to highlight OR when it's the exact same range
     // as the previous call and isn't inside a dynamic container.
     if (!rectsAndTexts.textList.length ||
--- a/toolkit/modules/FinderIterator.jsm
+++ b/toolkit/modules/FinderIterator.jsm
@@ -608,17 +608,17 @@ this.FinderIterator = {
    *                                     Range, from which the owner window will
    *                                     be queried.
    * @return {nsIDocShell}
    */
   _getDocShell(windowOrRange) {
     let window = windowOrRange;
     // Ranges may also be passed in, so fetch its window.
     if (windowOrRange instanceof Ci.nsIDOMRange)
-      window = windowOrRange.startContainer.ownerDocument.defaultView;
+      window = windowOrRange.startContainer.ownerGlobal;
     return window.QueryInterface(Ci.nsIInterfaceRequestor)
                  .getInterface(Ci.nsIWebNavigation)
                  .QueryInterface(Ci.nsIDocShell);
   },
 
   /**
    * Internal; determines whether a range is inside a link.
    *
--- a/toolkit/modules/InlineSpellChecker.jsm
+++ b/toolkit/modules/InlineSpellChecker.jsm
@@ -224,17 +224,17 @@ InlineSpellChecker.prototype = {
       if (curlang == sortedList[i].id) {
         item.setAttribute("checked", "true");
       } else {
         var callback = function(me, val, dictName) {
           return function(evt) {
             me.selectDictionary(val);
             // Notify change of dictionary, especially for Thunderbird,
             // which is otherwise not notified any more.
-            var view = menu.ownerDocument.defaultView;
+            var view = menu.ownerGlobal;
             var spellcheckChangeEvent = new view.CustomEvent(
                   "spellcheck-changed", {detail: { dictionary: dictName}});
             menu.ownerDocument.dispatchEvent(spellcheckChangeEvent);
           }
         };
         item.addEventListener("command", callback(this, i, sortedList[i].id), true);
       }
       if (insertBefore)
@@ -430,18 +430,17 @@ var SpellCheckHelper = {
     // POST     multipart/form-data               NO
     // POST     everything else                   YES
     return (method == "GET" || method == "") ||
            (form.enctype != "text/plain") && (form.enctype != "multipart/form-data");
   },
 
   // Returns the computed style attribute for the given element.
   getComputedStyle(aElem, aProp) {
-    return aElem.ownerDocument
-                .defaultView
+    return aElem.ownerGlobal
                 .getComputedStyle(aElem).getPropertyValue(aProp);
   },
 
   isEditable(element, window) {
     var flags = 0;
     if (element instanceof window.HTMLInputElement) {
       flags |= this.INPUT;
 
@@ -466,17 +465,17 @@ var SpellCheckHelper = {
     } else if (element instanceof window.HTMLTextAreaElement) {
       flags |= this.TEXTINPUT | this.TEXTAREA;
       if (!element.readOnly) {
         flags |= this.EDITABLE;
       }
     }
 
     if (!(flags & this.EDITABLE)) {
-      var win = element.ownerDocument.defaultView;
+      var win = element.ownerGlobal;
       if (win) {
         var isEditable = false;
         try {
           var editingSession = win.QueryInterface(Ci.nsIInterfaceRequestor)
                                   .getInterface(Ci.nsIWebNavigation)
                                   .QueryInterface(Ci.nsIInterfaceRequestor)
                                   .getInterface(Ci.nsIEditingSession);
           if (editingSession.windowIsEditable(win) &&
--- a/toolkit/modules/InlineSpellCheckerContent.jsm
+++ b/toolkit/modules/InlineSpellCheckerContent.jsm
@@ -17,17 +17,17 @@ var InlineSpellCheckerContent = {
   _manager: null,
 
   initContextMenu(event, editFlags, messageManager) {
     this._manager = messageManager;
 
     let spellChecker;
     if (!(editFlags & (SpellCheckHelper.TEXTAREA | SpellCheckHelper.INPUT))) {
       // Get the editor off the window.
-      let win = event.target.ownerDocument.defaultView;
+      let win = event.target.ownerGlobal;
       let editingSession = win.QueryInterface(Ci.nsIInterfaceRequestor)
                               .getInterface(Ci.nsIWebNavigation)
                               .QueryInterface(Ci.nsIInterfaceRequestor)
                               .getInterface(Ci.nsIEditingSession);
       spellChecker = this._spellChecker =
         new InlineSpellChecker(editingSession.getEditorForWindow(win));
     } else {
       // Use the element's editor.
--- a/toolkit/modules/PageMenu.jsm
+++ b/toolkit/modules/PageMenu.jsm
@@ -156,17 +156,17 @@ PageMenu.prototype = {
     let target = event.target;
     if (type == "command" && target.hasAttribute(this.GENERATEDITEMID_ATTR)) {
       // If a builder is assigned, call click on it directly. Otherwise, this is
       // likely a menu with data from another process, so send a message to the
       // browser to execute the menuitem.
       if (this._builder) {
         this._builder.click(target.getAttribute(this.GENERATEDITEMID_ATTR));
       } else if (this._browser) {
-        let win = target.ownerDocument.defaultView;
+        let win = target.ownerGlobal;
         let windowUtils = win.QueryInterface(Ci.nsIInterfaceRequestor)
                              .getInterface(Ci.nsIDOMWindowUtils);
         this._browser.messageManager.sendAsyncMessage("ContextMenu:DoCustomCommand", {
           generatedItemId: target.getAttribute(this.GENERATEDITEMID_ATTR),
           handlingUserInput: windowUtils.isHandlingUserInput
         });
       }
     } else if (type == "popuphidden" && this._popup == target) {
--- a/toolkit/modules/PopupNotifications.jsm
+++ b/toolkit/modules/PopupNotifications.jsm
@@ -83,17 +83,17 @@ function Notification(id, message, ancho
   this.options = options || {};
 
   this._dismissed = false;
   // Will become a boolean when manually toggled by the user.
   this._checkboxChecked = null;
   this.wasDismissed = false;
   this.recordedTelemetryStats = new Set();
   this.isPrivate = PrivateBrowsingUtils.isWindowPrivate(
-                                        this.browser.ownerDocument.defaultView);
+                                        this.browser.ownerGlobal);
   this.timeCreated = this.owner.window.performance.now();
 }
 
 Notification.prototype = {
 
   id: null,
   message: null,
   anchorID: null,
@@ -206,17 +206,17 @@ Notification.prototype = {
 this.PopupNotifications = function PopupNotifications(tabbrowser, panel, iconBox) {
   if (!(tabbrowser instanceof Ci.nsIDOMXULElement))
     throw "Invalid tabbrowser";
   if (iconBox && !(iconBox instanceof Ci.nsIDOMXULElement))
     throw "Invalid iconBox";
   if (!(panel instanceof Ci.nsIDOMXULElement))
     throw "Invalid panel";
 
-  this.window = tabbrowser.ownerDocument.defaultView;
+  this.window = tabbrowser.ownerGlobal;
   this.panel = panel;
   this.tabbrowser = tabbrowser;
   this.iconBox = iconBox;
   this.buttonDelay = Services.prefs.getIntPref(PREF_SECURITY_DELAY);
 
   this.panel.addEventListener("popuphidden", this, true);
   this.panel.classList.add("popup-notification-panel");
 
@@ -1226,17 +1226,17 @@ PopupNotifications.prototype = {
     }
   },
 
   _swapBrowserNotifications: function PopupNotifications_swapBrowserNoficications(ourBrowser, otherBrowser) {
     // When swaping browser docshells (e.g. dragging tab to new window) we need
     // to update our notification map.
 
     let ourNotifications = this._getNotificationsForBrowser(ourBrowser);
-    let other = otherBrowser.ownerDocument.defaultView.PopupNotifications;
+    let other = otherBrowser.ownerGlobal.PopupNotifications;
     if (!other) {
       if (ourNotifications.length > 0)
         Cu.reportError("unable to swap notifications: otherBrowser doesn't support notifications");
       return;
     }
     let otherNotifications = other._getNotificationsForBrowser(otherBrowser);
     if (ourNotifications.length < 1 && otherNotifications.length < 1) {
       // No notification to swap.
--- a/toolkit/modules/PrivateBrowsingUtils.jsm
+++ b/toolkit/modules/PrivateBrowsingUtils.jsm
@@ -29,17 +29,17 @@ this.PrivateBrowsingUtils = {
   },
 
   // This should be used only in frame scripts.
   isContentWindowPrivate: function pbu_isWindowPrivate(aWindow) {
     return this.privacyContextFromWindow(aWindow).usePrivateBrowsing;
   },
 
   isBrowserPrivate(aBrowser) {
-    let chromeWin = aBrowser.ownerDocument.defaultView;
+    let chromeWin = aBrowser.ownerGlobal;
     if (chromeWin.gMultiProcessBrowser) {
       // In e10s we have to look at the chrome window's private
       // browsing status since the only alternative is to check the
       // content window, which is in another process.
       return this.isWindowPrivate(chromeWin);
     }
     return this.privacyContextFromWindow(aBrowser.contentWindow).usePrivateBrowsing;
   },
--- a/toolkit/modules/RemoteController.jsm
+++ b/toolkit/modules/RemoteController.jsm
@@ -45,17 +45,17 @@ RemoteController.prototype = {
       cmd: aCommand,
       params: null
     };
     if (aCommand == "cmd_lookUpDictionary") {
       // Although getBoundingClientRect of the element is logical pixel, but
       // x and y parameter of cmd_lookUpDictionary are device pixel.
       // So we need calculate child process's coordinate using correct unit.
       let rect = this._browser.getBoundingClientRect();
-      let scale = this._browser.ownerDocument.defaultView.devicePixelRatio;
+      let scale = this._browser.ownerGlobal.devicePixelRatio;
       cmd.params = {
         x:  {
           type: "long",
           value: aCommandParams.getLongValue("x") - rect.left * scale
         },
         y: {
           type: "long",
           value: aCommandParams.getLongValue("y") - rect.top * scale
@@ -85,11 +85,11 @@ RemoteController.prototype = {
     for (let c = 0; c < aEnabledLength; c++) {
       this._supportedCommands[aEnabledCommands[c]] = true;
     }
 
     for (let c = 0; c < aDisabledLength; c++) {
       this._supportedCommands[aDisabledCommands[c]] = false;
     }
 
-    this._browser.ownerDocument.defaultView.updateCommands(aAction);
+    this._browser.ownerGlobal.updateCommands(aAction);
   }
 };
--- a/toolkit/modules/SelectContentHelper.jsm
+++ b/toolkit/modules/SelectContentHelper.jsm
@@ -51,17 +51,17 @@ this.SelectContentHelper.prototype = {
   init() {
     this.global.addMessageListener("Forms:SelectDropDownItem", this);
     this.global.addMessageListener("Forms:DismissedDropDown", this);
     this.global.addMessageListener("Forms:MouseOver", this);
     this.global.addMessageListener("Forms:MouseOut", this);
     this.global.addMessageListener("Forms:MouseUp", this);
     this.global.addEventListener("pagehide", this);
     this.global.addEventListener("mozhidedropdown", this);
-    let MutationObserver = this.element.ownerDocument.defaultView.MutationObserver;
+    let MutationObserver = this.element.ownerGlobal.MutationObserver;
     this.mut = new MutationObserver(mutations => {
       // Something changed the <select> while it was open, so
       // we'll poke a DeferredTask to update the parent sometime
       // in the very near future.
       this._updateTimer.arm();
     });
     this.mut.observe(this.element, {childList: true, subtree: true});
   },
@@ -127,17 +127,17 @@ this.SelectContentHelper.prototype = {
       case "Forms:SelectDropDownItem":
         this.element.selectedIndex = message.data.value;
         this.closedWithEnter = message.data.closedWithEnter;
         break;
 
       case "Forms:DismissedDropDown":
         let selectedOption = this.element.item(this.element.selectedIndex);
         if (this.initialSelection != selectedOption) {
-          let win = this.element.ownerDocument.defaultView;
+          let win = this.element.ownerGlobal;
           // For ordering of events, we're using non-e10s as our guide here,
           // since the spec isn't exactly clear. In non-e10s, we fire:
           // mousedown, mouseup, input, change, click if the user clicks
           // on an element in the dropdown. If the user uses the keyboard
           // to select an element in the dropdown, we only fire input and
           // change events.
           if (!this.closedWithEnter) {
             this.dispatchMouseEvent(win, selectedOption, "mousedown");
@@ -167,17 +167,17 @@ this.SelectContentHelper.prototype = {
         DOMUtils.setContentState(this.element, kStateHover);
         break;
 
       case "Forms:MouseOut":
         DOMUtils.removeContentState(this.element, kStateHover);
         break;
 
       case "Forms:MouseUp":
-        let win = this.element.ownerDocument.defaultView;
+        let win = this.element.ownerGlobal;
         if (message.data.onAnchor) {
           this.dispatchMouseEvent(win, this.element, "mouseup");
         }
         DOMUtils.removeContentState(this.element, kStateActive);
         if (message.data.onAnchor) {
           this.dispatchMouseEvent(win, this.element, "click");
         }
         break;
@@ -199,17 +199,17 @@ this.SelectContentHelper.prototype = {
         }
         break;
     }
   }
 
 }
 
 function getComputedStyles(element) {
-  return element.ownerDocument.defaultView.getComputedStyle(element);
+  return element.ownerGlobal.getComputedStyle(element);
 }
 
 function buildOptionListForChildren(node) {
   let result = [];
 
   for (let child of node.children) {
     let tagName = child.tagName.toUpperCase();
 
--- a/toolkit/modules/SelectParentHelper.jsm
+++ b/toolkit/modules/SelectParentHelper.jsm
@@ -35,17 +35,17 @@ this.SelectParentHelper = {
 
   open(browser, menulist, rect, isOpenedViaTouch) {
     menulist.hidden = false;
     currentBrowser = browser;
     closedWithEnter = false;
     selectRect = rect;
     this._registerListeners(browser, menulist.menupopup);
 
-    let win = browser.ownerDocument.defaultView;
+    let win = browser.ownerGlobal;
 
     // Set the maximum height to show exactly MAX_ROWS items.
     let menupopup = menulist.menupopup;
     let firstItem = menupopup.firstChild;
     while (firstItem && firstItem.hidden) {
       firstItem = firstItem.nextSibling;
     }
 
@@ -143,44 +143,44 @@ this.SelectParentHelper = {
     }
   },
 
   _registerListeners(browser, popup) {
     popup.addEventListener("command", this);
     popup.addEventListener("popuphidden", this);
     popup.addEventListener("mouseover", this);
     popup.addEventListener("mouseout", this);
-    browser.ownerDocument.defaultView.addEventListener("mouseup", this, true);
-    browser.ownerDocument.defaultView.addEventListener("keydown", this, true);
-    browser.ownerDocument.defaultView.addEventListener("fullscreen", this, true);
+    browser.ownerGlobal.addEventListener("mouseup", this, true);
+    browser.ownerGlobal.addEventListener("keydown", this, true);
+    browser.ownerGlobal.addEventListener("fullscreen", this, true);
     browser.messageManager.addMessageListener("Forms:UpdateDropDown", this);
   },
 
   _unregisterListeners(browser, popup) {
     popup.removeEventListener("command", this);
     popup.removeEventListener("popuphidden", this);
     popup.removeEventListener("mouseover", this);
     popup.removeEventListener("mouseout", this);
-    browser.ownerDocument.defaultView.removeEventListener("mouseup", this, true);
-    browser.ownerDocument.defaultView.removeEventListener("keydown", this, true);
-    browser.ownerDocument.defaultView.removeEventListener("fullscreen", this, true);
+    browser.ownerGlobal.removeEventListener("mouseup", this, true);
+    browser.ownerGlobal.removeEventListener("keydown", this, true);
+    browser.ownerGlobal.removeEventListener("fullscreen", this, true);
     browser.messageManager.removeMessageListener("Forms:UpdateDropDown", this);
   },
 
 };
 
 function populateChildren(menulist, options, selectedIndex, zoom,
                           parentElement = null, isGroupDisabled = false,
                           adjustedTextSize = -1, addSearch = true) {
   let element = menulist.menupopup;
 
   // -1 just means we haven't calculated it yet. When we recurse through this function
   // we will pass in adjustedTextSize to save on recalculations.
   if (adjustedTextSize == -1) {
-    let win = element.ownerDocument.defaultView;
+    let win = element.ownerGlobal;
 
     // Grab the computed text size and multiply it by the remote browser's fullZoom to ensure
     // the popup's text size is matched with the content's. We can't just apply a CSS transform
     // here as the popup's preferred size is calculated pre-transform.
     let textSize = win.getComputedStyle(element).getPropertyValue("font-size");
     adjustedTextSize = (zoom * parseFloat(textSize, 10)) + "px";
   }
 
--- a/toolkit/modules/SpatialNavigation.jsm
+++ b/toolkit/modules/SpatialNavigation.jsm
@@ -107,17 +107,17 @@ function _onInputKeyPress(event, callbac
   // If it is not using the modifiers it should, return.
   if (!event.altKey && PrefObserver["modifierAlt"] ||
       !event.shiftKey && PrefObserver["modifierShift"] ||
       !event.crtlKey && PrefObserver["modifierCtrl"]) {
     return;
   }
 
   let currentlyFocused = event.target;
-  let currentlyFocusedWindow = currentlyFocused.ownerDocument.defaultView;
+  let currentlyFocusedWindow = currentlyFocused.ownerGlobal;
   let bestElementToFocus = null;
 
   // If currentlyFocused is an nsIDOMHTMLBodyElement then the page has just been
   // loaded, and this is the first keypress in the page.
   if (currentlyFocused instanceof Ci.nsIDOMHTMLBodyElement) {
     focusManager.moveFocus(currentlyFocusedWindow, null, focusManager.MOVEFOCUS_FIRST, 0);
     event.stopPropagation();
     event.preventDefault();
--- a/toolkit/modules/WindowDraggingUtils.jsm
+++ b/toolkit/modules/WindowDraggingUtils.jsm
@@ -5,17 +5,17 @@
 Components.utils.import("resource://gre/modules/AppConstants.jsm");
 
 const HAVE_CSS_WINDOW_DRAG_SUPPORT = ["win", "macosx"].includes(AppConstants.platform);
 
 this.EXPORTED_SYMBOLS = [ "WindowDraggingElement" ];
 
 this.WindowDraggingElement = function WindowDraggingElement(elem) {
   this._elem = elem;
-  this._window = elem.ownerDocument.defaultView;
+  this._window = elem.ownerGlobal;
   if (HAVE_CSS_WINDOW_DRAG_SUPPORT && !this.isPanel()) {
     return;
   }
 
   this._elem.addEventListener("mousedown", this);
 };
 
 WindowDraggingElement.prototype = {
@@ -28,17 +28,17 @@ WindowDraggingElement.prototype = {
         this._window.fullScreen ||
         !this.mouseDownCheck.call(this._elem, aEvent) ||
         aEvent.defaultPrevented)
       return false;
 
     let target = aEvent.originalTarget, parent = aEvent.originalTarget;
 
     // The target may be inside an embedded iframe or browser. (bug 615152)
-    if (target.ownerDocument.defaultView != this._window)
+    if (target.ownerGlobal != this._window)
       return false;
 
     while (parent != this._elem) {
       let mousethrough = parent.getAttribute("mousethrough");
       if (mousethrough == "always")
         target = parent.parentNode;
       else if (mousethrough == "never")
         break;
--- a/toolkit/modules/addons/WebNavigation.jsm
+++ b/toolkit/modules/addons/WebNavigation.jsm
@@ -261,17 +261,17 @@ var Manager = {
         this.onContentClick(target, data);
         break;
     }
   },
 
   onContentClick(target, data) {
     // We are interested only on clicks to links which are not "add to bookmark" commands
     if (data.href && !data.bookmark) {
-      let ownerWin = target.ownerDocument.defaultView;
+      let ownerWin = target.ownerGlobal;
       let where = ownerWin.whereToOpenLink(data);
       if (where == "current") {
         this.setRecentTabTransitionData({link: true});
       }
     }
   },
 
   onStateChange(browser, data) {
--- a/toolkit/mozapps/extensions/AddonManager.jsm
+++ b/toolkit/mozapps/extensions/AddonManager.jsm
@@ -2157,17 +2157,17 @@ var AddonManagerInternal = {
                                  Cr.NS_ERROR_INVALID_ARG);
 
     // When a chrome in-content UI has loaded a <browser> inside to host a
     // website we want to do our security checks on the inner-browser but
     // notify front-end that install events came from the outer-browser (the
     // main tab's browser). Check this by seeing if the browser we've been
     // passed is in a content type docshell and if so get the outer-browser.
     let topBrowser = aBrowser;
-    let docShell = aBrowser.ownerDocument.defaultView
+    let docShell = aBrowser.ownerGlobal
                            .QueryInterface(Ci.nsIInterfaceRequestor)
                            .getInterface(Ci.nsIDocShell)
                            .QueryInterface(Ci.nsIDocShellTreeItem);
     if (docShell.itemType == Ci.nsIDocShellTreeItem.typeContent)
       topBrowser = docShell.chromeEventHandler;
 
     try {
       if (!this.isInstallEnabled(aMimetype)) {
@@ -2913,24 +2913,24 @@ var AddonManagerInternal = {
         try {
           Cc["@mozilla.org/base/telemetry;1"].
                        getService(Ci.nsITelemetry).
                        getHistogramById("SECURITY_UI").
                        add(Ci.nsISecurityUITelemetry.WARNING_CONFIRM_ADDON_INSTALL);
           let parentWindow = null;
           if (browser) {
             // Find the outer browser
-            let docShell = browser.ownerDocument.defaultView
+            let docShell = browser.ownerGlobal
                                   .QueryInterface(Ci.nsIInterfaceRequestor)
                                   .getInterface(Ci.nsIDocShell)
                                   .QueryInterface(Ci.nsIDocShellTreeItem);
             if (docShell.itemType == Ci.nsIDocShellTreeItem.typeContent)
               browser = docShell.chromeEventHandler;
 
-            parentWindow = browser.ownerDocument.defaultView;
+            parentWindow = browser.ownerGlobal;
             PromptUtils.fireDialogEvent(parentWindow, "DOMWillOpenModalDialog", browser);
           }
 
           // Ugh modal dialogs...
           let reallyReject = reject;
           let cancelled = false;
           reject = () => {
             cancelled = true;
--- a/toolkit/mozapps/extensions/amContentHandler.js
+++ b/toolkit/mozapps/extensions/amContentHandler.js
@@ -63,17 +63,17 @@ amContentHandler.prototype = {
 
     if (Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) {
       // When running in the main process this might be a frame inside an
       // in-content UI page, walk up to find the first frame element in a chrome
       // privileged document
       let element = window.frameElement;
       let ssm = Services.scriptSecurityManager;
       while (element && !ssm.isSystemPrincipal(element.ownerDocument.nodePrincipal))
-        element = element.ownerDocument.defaultView.frameElement;
+        element = element.ownerGlobal.frameElement;
 
       if (element) {
         let listener = Cc["@mozilla.org/addons/integration;1"].
                        getService(Ci.nsIMessageListener);
         listener.wrappedJSObject.receiveMessage({
           name: MSG_INSTALL_ADDON,
           target: element,
           data: install
--- a/toolkit/mozapps/extensions/amInstallTrigger.js
+++ b/toolkit/mozapps/extensions/amInstallTrigger.js
@@ -77,17 +77,17 @@ RemoteMediator.prototype = {
 
     if (Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) {
       // When running in the main process this might be a frame inside an
       // in-content UI page, walk up to find the first frame element in a chrome
       // privileged document
       let element = window.frameElement;
       let ssm = Services.scriptSecurityManager;
       while (element && !ssm.isSystemPrincipal(element.ownerDocument.nodePrincipal))
-        element = element.ownerDocument.defaultView.frameElement;
+        element = element.ownerGlobal.frameElement;
 
       if (element) {
         let listener = Cc["@mozilla.org/addons/integration;1"].
                        getService(Ci.nsIMessageListener);
         return listener.wrappedJSObject.receiveMessage({
           name: MSG_INSTALL_ADDON,
           target: element,
           data: install,
--- a/toolkit/mozapps/extensions/internal/XPIProvider.jsm
+++ b/toolkit/mozapps/extensions/internal/XPIProvider.jsm
@@ -6447,17 +6447,17 @@ class DownloadAddonInstall extends Addon
       }
     });
   }
 
   getInterface(iid) {
     if (iid.equals(Ci.nsIAuthPrompt2)) {
       let win = null;
       if (this.browser) {
-        win = this.browser.contentWindow || this.browser.ownerDocument.defaultView;
+        win = this.browser.contentWindow || this.browser.ownerGlobal;
       }
 
       let factory = Cc["@mozilla.org/prompter;1"].
                     getService(Ci.nsIPromptFactory);
       let prompt = factory.getPrompt(win, Ci.nsIAuthPrompt2);
 
       if (this.browser && prompt instanceof Ci.nsILoginManagerPrompter)
         prompt.browser = this.browser;
--- a/toolkit/mozapps/extensions/test/browser/head.js
+++ b/toolkit/mozapps/extensions/test/browser/head.js
@@ -227,17 +227,17 @@ function run_next_test() {
   else
     info("Running test " + gTestsRun);
 
   gTestStart = Date.now();
   executeSoon(() => log_exceptions(test));
 }
 
 var get_tooltip_info = Task.async(function*(addon) {
-  let managerWindow = addon.ownerDocument.defaultView;
+  let managerWindow = addon.ownerGlobal;
 
   // The popup code uses a triggering event's target to set the
   // document.tooltipNode property.
   let nameNode = addon.ownerDocument.getAnonymousElementByAttribute(addon, "anonid", "name");
   let event = new managerWindow.CustomEvent("TriggerEvent");
   nameNode.dispatchEvent(event);
 
   let tooltip = managerWindow.document.getElementById("addonitem-tooltip");
@@ -505,17 +505,17 @@ function formatDate(aDate) {
   const locale = Cc["@mozilla.org/chrome/chrome-registry;1"]
                  .getService(Ci.nsIXULChromeRegistry)
                  .getSelectedLocale("global", true);
   const dtOptions = { year: "numeric", month: "long", day: "numeric" };
   return aDate.toLocaleDateString(locale, dtOptions);
 }
 
 function is_hidden(aElement) {
-  var style = aElement.ownerDocument.defaultView.getComputedStyle(aElement);
+  var style = aElement.ownerGlobal.getComputedStyle(aElement);
   if (style.display == "none")
     return true;
   if (style.visibility != "visible")
     return true;
 
   // Hiding a parent element will hide all its children
   if (aElement.parentNode != aElement.ownerDocument)
     return is_hidden(aElement.parentNode);
--- a/widget/tests/test_keycodes.xul
+++ b/widget/tests/test_keycodes.xul
@@ -87,17 +87,17 @@ function isModifierKeyEvent(aEvent)
  */
 function clearInfobars()
 {
   var Ci = Components.interfaces;
 
   var browser = window.top.QueryInterface(Ci.nsIInterfaceRequestor)
                   .getInterface(Ci.nsIWebNavigation)
                   .QueryInterface(Ci.nsIDocShell).chromeEventHandler;
-  var chromeWin = browser.ownerDocument.defaultView;
+  var chromeWin = browser.ownerGlobal;
   var nb = chromeWin.gBrowser.getNotificationBox(browser);
   for (let n of nb.allNotifications) {
     nb.removeNotification(n, true);
   }
 }
 
 function eventToString(aEvent)
 {
--- a/xpfe/components/autocomplete/resources/content/autocomplete.xml
+++ b/xpfe/components/autocomplete/resources/content/autocomplete.xml
@@ -1491,29 +1491,27 @@
         <body><![CDATA[
           if (!this.input) {
             this.tree.view = aInput.controller;
             this.view = this.tree.view;
             this.showCommentColumn = aInput.showCommentColumn;
             this.maxRows = aInput.maxRows;
             this.invalidate();
 
-            var viewer = aElement
-                .ownerDocument
-                .defaultView
+            var viewer = aElement.ownerGlobal
                 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                 .getInterface(Components.interfaces.nsIWebNavigation)
                 .QueryInterface(Components.interfaces.nsIDocShell)
                 .contentViewer;
             var rect = aElement.getBoundingClientRect();
             var width = Math.round((rect.right - rect.left) * viewer.fullZoom);
             this.setAttribute("width", width > 100 ? width : 100);
             // Adjust the direction (which is not inherited) of the autocomplete
             // popup list, based on the textbox direction. (Bug 707039)
-            this.style.direction = aElement.ownerDocument.defaultView
+            this.style.direction = aElement.ownerGlobal
                                            .getComputedStyle(aElement)
                                            .direction;
             this.popupBoxObject.setConsumeRollupEvent(aInput.consumeRollupEvent
               ? PopupBoxObject.ROLLUP_CONSUME
               : PopupBoxObject.ROLLUP_NO_CONSUME);
             this.openPopup(aElement, "after_start", 0, 0, false, false);
             if (this.state != "closed")
               this.input = aInput;