Bug 1286854 - Replace ownerDocument.defaultView with ownerGlobal in browser/. r=dao
authorPushpankar <pushpankark@gmail.com>
Sat, 16 Jul 2016 10:20:04 +0200
changeset 305301 98e3e1a81859a64dfa625d1d40d3d0043a46941c
parent 305132 fb5fa9e3a52bf056d922c36f38d4ab8a55380307
child 305302 ce145f8f4c4a7d08b107f6796f1f03deb1d41ff6
push id30459
push usercbook@mozilla.com
push dateMon, 18 Jul 2016 15:07:13 +0000
treeherdermozilla-central@9d95b275e2cf [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersdao
bugs1286854
milestone50.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 1286854 - Replace ownerDocument.defaultView with ownerGlobal in browser/. r=dao
browser/base/content/browser-fullScreenAndPointerLock.js
browser/base/content/browser-places.js
browser/base/content/browser-social.js
browser/base/content/browser.js
browser/base/content/content.js
browser/base/content/nsContextMenu.js
browser/base/content/test/general/browser_bug431826.js
browser/base/content/test/general/browser_trackingUI_1.js
browser/base/content/test/general/browser_trackingUI_2.js
browser/base/content/test/general/browser_trackingUI_5.js
browser/base/content/test/general/contextmenu_common.js
browser/base/content/test/general/head.js
browser/base/content/test/urlbar/head.js
browser/base/content/test/webrtc/head.js
browser/base/content/webrtcIndicator.js
browser/components/contextualidentity/test/browser/browser_broadcastchannel.js
browser/components/contextualidentity/test/browser/browser_favicon.js
browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js
browser/components/contextualidentity/test/browser/browser_serviceworkers.js
browser/components/contextualidentity/test/browser/browser_usercontext.js
browser/components/customizableui/CustomizableUI.jsm
browser/components/customizableui/CustomizableWidgets.jsm
browser/components/customizableui/CustomizeMode.jsm
browser/components/customizableui/DragPositionManager.jsm
browser/components/customizableui/test/head.js
browser/components/extensions/ext-browserAction.js
browser/components/extensions/ext-commands.js
browser/components/extensions/ext-contextMenus.js
browser/components/extensions/ext-pageAction.js
browser/components/extensions/ext-tabs.js
browser/components/extensions/ext-utils.js
browser/components/newtab/NewTabSearchProvider.jsm
browser/components/nsBrowserGlue.js
browser/components/places/PlacesUIUtils.jsm
browser/components/places/content/controller.js
browser/components/places/tests/browser/browser_library_middleclick.js
browser/components/places/tests/browser/head.js
browser/components/preferences/in-content/subdialogs.js
browser/components/preferences/in-content/tests/head.js
browser/components/safebrowsing/content/test/browser_whitelisted.js
browser/components/search/test/browser_oneOffHeader.js
browser/components/search/test/browser_searchbar_openpopup.js
browser/components/sessionstore/SessionStore.jsm
browser/components/sessionstore/TabState.jsm
browser/components/sessionstore/content/content-sessionStore.js
browser/components/sessionstore/test/browser_463206.js
browser/components/sessionstore/test/browser_sessionStoreContainer.js
browser/components/sessionstore/test/content-forms.js
browser/components/syncedtabs/test/browser/browser_sidebar_syncedtabslist.js
browser/components/uitour/UITour.jsm
browser/components/uitour/test/head.js
browser/extensions/pocket/content/Pocket.jsm
browser/modules/AboutHome.jsm
browser/modules/CaptivePortalWatcher.jsm
browser/modules/CastingApps.jsm
browser/modules/ContentClick.jsm
browser/modules/ContentCrashHandlers.jsm
browser/modules/ContentLinkHandler.jsm
browser/modules/ContentSearch.jsm
browser/modules/FormSubmitObserver.jsm
browser/modules/FormValidationHandler.jsm
browser/modules/NetworkPrioritizer.jsm
browser/modules/PluginContent.jsm
browser/modules/ProcessHangMonitor.jsm
browser/modules/ReaderParent.jsm
browser/modules/RemotePrompt.jsm
browser/modules/webrtcUI.jsm
--- a/browser/base/content/browser-fullScreenAndPointerLock.js
+++ b/browser/base/content/browser-fullScreenAndPointerLock.js
@@ -358,17 +358,17 @@ var FullScreen = {
         // target would be the browser which was the parameter of
         // `remoteFrameFullscreenChanged` call. If the fullscreen
         // request was initiated from an in-process browser, we need
         // to get its corresponding browser here.
         let browser;
         if (event.target == gBrowser) {
           browser = event.originalTarget;
         } else {
-          let topWin = event.target.ownerDocument.defaultView.top;
+          let topWin = event.target.ownerGlobal.top;
           browser = gBrowser.getBrowserForContentWindow(topWin);
         }
         TelemetryStopwatch.start("FULLSCREEN_CHANGE_MS");
         this.enterDomFullscreen(browser);
         break;
       }
       case "MozDOMFullscreen:Exited":
         TelemetryStopwatch.start("FULLSCREEN_CHANGE_MS");
--- a/browser/base/content/browser-places.js
+++ b/browser/base/content/browser-places.js
@@ -1161,17 +1161,17 @@ var PlacesToolbarHelper = {
       element = element.parentNode;
     }
     return null;
   },
 
   onWidgetUnderflow: function(aNode, aContainer) {
     // The view gets broken by being removed and reinserted by the overflowable
     // toolbar, so we have to force an uninit and reinit.
-    let win = aNode.ownerDocument.defaultView;
+    let win = aNode.ownerGlobal;
     if (aNode.id == "personal-bookmarks" && win == window) {
       this._resetView();
     }
   },
 
   onWidgetAdded: function(aWidgetId, aArea, aPosition) {
     if (aWidgetId == "personal-bookmarks" && !this._isCustomizing) {
       // It's possible (with the "Add to Menu", "Add to Toolbar" context
@@ -1904,33 +1904,33 @@ var BookmarkingUI = {
       gNavigatorBundle.getString("starButtonOverflowed.label");
   },
   get _starButtonOverflowedStarredLabel() {
     delete this._starButtonOverflowedStarredLabel;
     return this._starButtonOverflowedStarredLabel =
       gNavigatorBundle.getString("starButtonOverflowedStarred.label");
   },
   onWidgetOverflow: function(aNode, aContainer) {
-    let win = aNode.ownerDocument.defaultView;
+    let win = aNode.ownerGlobal;
     if (aNode.id != this.BOOKMARK_BUTTON_ID || win != window)
       return;
 
     let currentLabel = aNode.getAttribute("label");
     if (!this._starButtonLabel)
       this._starButtonLabel = currentLabel;
 
     if (currentLabel == this._starButtonLabel) {
       let desiredLabel = this._itemIds.length > 0 ? this._starButtonOverflowedStarredLabel
                                                  : this._starButtonOverflowedLabel;
       aNode.setAttribute("label", desiredLabel);
     }
   },
 
   onWidgetUnderflow: function(aNode, aContainer) {
-    let win = aNode.ownerDocument.defaultView;
+    let win = aNode.ownerGlobal;
     if (aNode.id != this.BOOKMARK_BUTTON_ID || win != window)
       return;
 
     // The view gets broken by being removed and reinserted. Uninit
     // here so popupshowing will generate a new one:
     this._uninitView();
 
     if (aNode.getAttribute("label") != this._starButtonLabel)
--- a/browser/base/content/browser-social.js
+++ b/browser/base/content/browser-social.js
@@ -178,17 +178,17 @@ SocialUI = {
   },
 
   closeSocialPanelForLinkTraversal: function (target, linkNode) {
     // No need to close the panel if this traversal was not retargeted
     if (target == "" || target == "_self")
       return;
 
     // Check to see whether this link traversal was in a social panel
-    let win = linkNode.ownerDocument.defaultView;
+    let win = linkNode.ownerGlobal;
     let container = win.QueryInterface(Ci.nsIInterfaceRequestor)
                                   .getInterface(Ci.nsIWebNavigation)
                                   .QueryInterface(Ci.nsIDocShell)
                                   .chromeEventHandler;
     let containerParent = container.parentNode;
     if (containerParent.classList.contains("social-panel") &&
         containerParent instanceof Ci.nsIDOMXULPopupElement) {
       // allow the link traversal to finish before closing the panel
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -4405,17 +4405,17 @@ var XULBrowserWindow = {
     let pageTooltip = document.getElementById("aHTMLTooltip");
     let tooltipNode = pageTooltip.triggerNode;
     if (tooltipNode) {
       // Optimise for the common case
       if (aWebProgress.isTopLevel) {
         pageTooltip.hidePopup();
       }
       else {
-        for (let tooltipWindow = tooltipNode.ownerDocument.defaultView;
+        for (let tooltipWindow = tooltipNode.ownerGlobal;
              tooltipWindow != tooltipWindow.parent;
              tooltipWindow = tooltipWindow.parent) {
           if (tooltipWindow == aWebProgress.DOMWindow) {
             pageTooltip.hidePopup();
             break;
           }
         }
       }
@@ -6036,17 +6036,17 @@ var IndexedDBPromptHelper = {
   function IndexedDBPromptHelper_observe(subject, topic, data) {
     if (topic != this._permissionsPrompt) {
       throw new Error("Unexpected topic!");
     }
 
     var requestor = subject.QueryInterface(Ci.nsIInterfaceRequestor);
 
     var browser = requestor.getInterface(Ci.nsIDOMNode);
-    if (browser.ownerDocument.defaultView != window) {
+    if (browser.ownerGlobal != window) {
       // Only listen for notifications for browsers in our chrome window.
       return;
     }
 
     var host = browser.currentURI.asciiHost;
 
     var message;
     var responseTopic;
--- a/browser/base/content/content.js
+++ b/browser/base/content/content.js
@@ -199,32 +199,32 @@ var showContentContextMenu = function (e
         InlineSpellCheckerContent.initContextMenu(event, editFlags, this);
     }
 
     // Set the event target first as the copy image command needs it to
     // determine what was context-clicked on. Then, update the state of the
     // commands on the context menu.
     docShell.contentViewer.QueryInterface(Ci.nsIContentViewerEdit)
             .setCommandNode(event.target);
-    event.target.ownerDocument.defaultView.updateCommands("contentcontextmenu");
+    event.target.ownerGlobal.updateCommands("contentcontextmenu");
 
     let customMenuItems = PageMenuChild.build(event.target);
     let principal = doc.nodePrincipal;
     sendRpcMessage("contextmenu",
                    { editFlags, spellInfo, customMenuItems, addonInfo,
                      principal, docLocation, charSet, baseURI, referrer,
                      referrerPolicy, contentType, contentDisposition,
                      frameOuterWindowID, selectionInfo, disableSetDesktopBg,
                      loginFillInfo, parentAllowsMixedContent },
                    { event, popupNode: event.target });
   }
   else {
     // Break out to the parent window and pass the add-on info along
     let browser = docShell.chromeEventHandler;
-    let mainWin = browser.ownerDocument.defaultView;
+    let mainWin = browser.ownerGlobal;
     mainWin.gContextMenuContentData = {
       isRemote: false,
       event: event,
       popupNode: event.target,
       browser: browser,
       addonInfo: addonInfo,
       documentURIObject: doc.documentURIObject,
       docLocation: docLocation,
@@ -910,17 +910,17 @@ var LightWeightThemeWebInstallListener =
         });
         break;
       }
       case "PreviewBrowserTheme": {
         sendAsyncMessage("LightWeightThemeWebInstaller:Preview", {
           baseURI: event.target.baseURI,
           themeData: event.target.getAttribute("data-browsertheme"),
         });
-        this._previewWindow = event.target.ownerDocument.defaultView;
+        this._previewWindow = event.target.ownerGlobal;
         this._previewWindow.addEventListener("pagehide", this, true);
         break;
       }
       case "pagehide": {
         sendAsyncMessage("LightWeightThemeWebInstaller:ResetPreview");
         this._resetPreviewWindow();
         break;
       }
@@ -1165,17 +1165,17 @@ var PageInfoListener = {
     }
     // Send that page info media fetching has finished.
     sendAsyncMessage("PageInfo:mediaData", {isComplete: true});
   },
 
   getMediaItems: function(document, strings, elem)
   {
     // Check for images defined in CSS (e.g. background, borders)
-    let computedStyle = elem.ownerDocument.defaultView.getComputedStyle(elem, "");
+    let computedStyle = elem.ownerGlobal.getComputedStyle(elem);
     // A node can have multiple media items associated with it - for example,
     // multiple background images.
     let mediaItems = [];
 
     let addImage = (url, type, alt, elem, isBg) => {
       let element = this.serializeElementInfo(document, url, type, alt, elem, isBg);
       mediaItems.push([url, type, alt, element, isBg]);
     };
--- a/browser/base/content/nsContextMenu.js
+++ b/browser/base/content/nsContextMenu.js
@@ -582,17 +582,17 @@ nsContextMenu.prototype = {
   },
 
   openPasswordManager: function() {
     LoginHelper.openPasswordManager(window, gContextMenuContentData.documentURIObject.host);
   },
 
   inspectNode: function() {
     let {devtools} = Cu.import("resource://devtools/shared/Loader.jsm", {});
-    let gBrowser = this.browser.ownerDocument.defaultView.gBrowser;
+    let gBrowser = this.browser.ownerGlobal.gBrowser;
     let target = devtools.TargetFactory.forTab(gBrowser.selectedTab);
 
     return gDevTools.showToolbox(target, "inspector").then(toolbox => {
       let inspector = toolbox.getCurrentPanel();
 
       // new-node-front tells us when the node has been selected, whether the
       // browser is remote or not.
       let onNewNode = inspector.selection.once("new-node-front");
--- a/browser/base/content/test/general/browser_bug431826.js
+++ b/browser/base/content/test/general/browser_bug431826.js
@@ -20,33 +20,33 @@ add_task(function* () {
   });
 
   let advancedDiv, advancedDivVisibility, technicalDivCollapsed;
 
   yield remote(() => {
     let div = content.document.getElementById("badCertAdvancedPanel");
     // Confirm that the expert section is collapsed
     Assert.ok(div, "Advanced content div should exist");
-    Assert.equal(div.ownerDocument.defaultView.getComputedStyle(div, "").display,
+    Assert.equal(div.ownerGlobal.getComputedStyle(div).display,
       "none", "Advanced content should not be visible by default");
   });
 
   // Tweak the expert mode pref
   gPrefService.setBoolPref("browser.xul.error_pages.expert_bad_cert", true);
 
   promise = remote(function () {
     return ContentTaskUtils.waitForEvent(this, "DOMContentLoaded", true);
   });
   gBrowser.reload();
   yield promise;
 
   yield remote(() => {
     let div = content.document.getElementById("badCertAdvancedPanel");
     Assert.ok(div, "Advanced content div should exist");
-    Assert.equal(div.ownerDocument.defaultView.getComputedStyle(div, "").display,
+    Assert.equal(div.ownerGlobal.getComputedStyle(div).display,
       "block", "Advanced content should be visible by default");
   });
 
   // Clean up
   gBrowser.removeCurrentTab();
   if (gPrefService.prefHasUserValue("browser.xul.error_pages.expert_bad_cert"))
     gPrefService.clearUserPref("browser.xul.error_pages.expert_bad_cert");
 });
--- a/browser/base/content/test/general/browser_trackingUI_1.js
+++ b/browser/base/content/test/general/browser_trackingUI_1.js
@@ -108,29 +108,29 @@ function testTrackingPageUnblocked() {
 
 function* testTrackingProtectionForTab(tab) {
   info("Load a test page not containing tracking elements");
   yield promiseTabLoadEvent(tab, BENIGN_PAGE);
   testBenignPage();
 
   info("Load a test page containing tracking elements");
   yield promiseTabLoadEvent(tab, TRACKING_PAGE);
-  testTrackingPage(tab.ownerDocument.defaultView);
+  testTrackingPage(tab.ownerGlobal);
 
   info("Disable TP for the page (which reloads the page)");
   let tabReloadPromise = promiseTabLoadEvent(tab);
   clickButton("#tracking-action-unblock");
   yield tabReloadPromise;
   testTrackingPageUnblocked();
 
   info("Re-enable TP for the page (which reloads the page)");
   tabReloadPromise = promiseTabLoadEvent(tab);
   clickButton("#tracking-action-block");
   yield tabReloadPromise;
-  testTrackingPage(tab.ownerDocument.defaultView);
+  testTrackingPage(tab.ownerGlobal);
 }
 
 add_task(function* testNormalBrowsing() {
   yield UrlClassifierTestUtils.addTestTrackers();
 
   tabbrowser = gBrowser;
   let tab = tabbrowser.selectedTab = tabbrowser.addTab();
 
--- a/browser/base/content/test/general/browser_trackingUI_2.js
+++ b/browser/base/content/test/general/browser_trackingUI_2.js
@@ -20,17 +20,17 @@ registerCleanupFunction(function() {
   Services.prefs.clearUserPref(PREF);
   Services.prefs.clearUserPref(PB_PREF);
   while (gBrowser.tabs.length > 1) {
     gBrowser.removeCurrentTab();
   }
 });
 
 function hidden(el) {
-  let win = el.ownerDocument.defaultView;
+  let win = el.ownerGlobal;
   let display = win.getComputedStyle(el).getPropertyValue("display", null);
   let opacity = win.getComputedStyle(el).getPropertyValue("opacity", null);
 
   return display === "none" || opacity === "0";
 }
 
 add_task(function* testNormalBrowsing() {
   yield UrlClassifierTestUtils.addTestTrackers();
--- a/browser/base/content/test/general/browser_trackingUI_5.js
+++ b/browser/base/content/test/general/browser_trackingUI_5.js
@@ -80,17 +80,17 @@ add_task(function* testExceptionAddition
   TrackingProtection = browser.ownerGlobal.TrackingProtection;
   yield pushPrefs([PB_PREF, true]);
 
   ok(TrackingProtection.enabled, "TP is enabled after setting the pref");
 
   info("Load a test page containing tracking elements");
   yield promiseTabLoadEvent(tab, TRACKING_PAGE);
 
-  testTrackingPage(tab.ownerDocument.defaultView);
+  testTrackingPage(tab.ownerGlobal);
 
   info("Disable TP for the page (which reloads the page)");
   let tabReloadPromise = promiseTabLoadEvent(tab);
   clickButton("#tracking-action-unblock");
   is(identityPopupState(), "closed", "foobar");
 
   yield tabReloadPromise;
   testTrackingPageUnblocked();
@@ -112,17 +112,17 @@ add_task(function* testExceptionPersiste
   let tab = browser.selectedTab = browser.addTab();
 
   TrackingProtection = browser.ownerGlobal.TrackingProtection;
   ok(TrackingProtection.enabled, "TP is still enabled");
 
   info("Load a test page containing tracking elements");
   yield promiseTabLoadEvent(tab, TRACKING_PAGE);
 
-  testTrackingPage(tab.ownerDocument.defaultView);
+  testTrackingPage(tab.ownerGlobal);
 
   info("Disable TP for the page (which reloads the page)");
   let tabReloadPromise = promiseTabLoadEvent(tab);
   clickButton("#tracking-action-unblock");
   is(identityPopupState(), "closed", "foobar");
 
   yield tabReloadPromise;
   testTrackingPageUnblocked();
--- a/browser/base/content/test/general/contextmenu_common.js
+++ b/browser/base/content/test/general/contextmenu_common.js
@@ -8,17 +8,17 @@ function openContextMenuFor(element, shi
       lastElement.blur();
     element.focus();
 
     // Some elements need time to focus and spellcheck before any tests are
     // run on them.
     function actuallyOpenContextMenuFor() {
       lastElement = element;
       var eventDetails = { type : "contextmenu", button : 2, shiftKey : shiftkey };
-      synthesizeMouse(element, 2, 2, eventDetails, element.ownerDocument.defaultView);
+      synthesizeMouse(element, 2, 2, eventDetails, element.ownerGlobal);
     }
 
     if (waitForSpellCheck) {
       var { onSpellCheck } = SpecialPowers.Cu.import("resource://gre/modules/AsyncSpellCheckTestHelper.jsm", {});
       onSpellCheck(element, actuallyOpenContextMenuFor);
     }
     else {
       actuallyOpenContextMenuFor();
--- a/browser/base/content/test/general/head.js
+++ b/browser/base/content/test/general/head.js
@@ -693,17 +693,17 @@ function assertMixedContentBlockingState
   }
 
   let {passiveLoaded,activeLoaded,activeBlocked} = states;
   let {gIdentityHandler} = tabbrowser.ownerGlobal;
   let doc = tabbrowser.ownerDocument;
   let identityBox = gIdentityHandler._identityBox;
   let classList = identityBox.classList;
   let connectionIcon = doc.getElementById("connection-icon");
-  let connectionIconImage = tabbrowser.ownerGlobal.getComputedStyle(connectionIcon, "").
+  let connectionIconImage = tabbrowser.ownerGlobal.getComputedStyle(connectionIcon).
                          getPropertyValue("list-style-image");
 
   let stateSecure = gIdentityHandler._state & Ci.nsIWebProgressListener.STATE_IS_SECURE;
   let stateBroken = gIdentityHandler._state & Ci.nsIWebProgressListener.STATE_IS_BROKEN;
   let stateInsecure = gIdentityHandler._state & Ci.nsIWebProgressListener.STATE_IS_INSECURE;
   let stateActiveBlocked = gIdentityHandler._state & Ci.nsIWebProgressListener.STATE_BLOCKED_MIXED_ACTIVE_CONTENT;
   let stateActiveLoaded = gIdentityHandler._state & Ci.nsIWebProgressListener.STATE_LOADED_MIXED_ACTIVE_CONTENT;
   let statePassiveLoaded = gIdentityHandler._state & Ci.nsIWebProgressListener.STATE_LOADED_MIXED_DISPLAY_CONTENT;
@@ -770,19 +770,19 @@ function assertMixedContentBlockingState
   is(popupAttr.includes("passive-loaded"), passiveLoaded,
       "identity-popup has expected attr for passiveLoaded");
   is(bodyAttr.includes("passive-loaded"), passiveLoaded,
       "securityView-body has expected attr for passiveLoaded");
 
   // Make sure the correct icon is visible in the Control Center.
   // This logic is controlled with CSS, so this helps prevent regressions there.
   let securityView = doc.getElementById("identity-popup-securityView");
-  let securityViewBG = tabbrowser.ownerGlobal.getComputedStyle(securityView, "").
+  let securityViewBG = tabbrowser.ownerGlobal.getComputedStyle(securityView).
                        getPropertyValue("background-image");
-  let securityContentBG = tabbrowser.ownerGlobal.getComputedStyle(securityView, "").
+  let securityContentBG = tabbrowser.ownerGlobal.getComputedStyle(securityView).
                           getPropertyValue("background-image");
 
   if (stateInsecure) {
     is(securityViewBG, "url(\"chrome://browser/skin/controlcenter/conn-not-secure.svg\")",
       "CC using 'not secure' icon");
     is(securityContentBG, "url(\"chrome://browser/skin/controlcenter/conn-not-secure.svg\")",
       "CC using 'not secure' icon");
   }
@@ -826,33 +826,33 @@ function assertMixedContentBlockingState
   // Wait for the panel to be closed before continuing. The promisePopupHidden
   // function cannot be used because it's unreliable unless promisePopupShown is
   // also called before closing the panel. This cannot be done until all callers
   // are made asynchronous (bug 1221114).
   return new Promise(resolve => executeSoon(resolve));
 }
 
 function is_hidden(element) {
-  var style = element.ownerDocument.defaultView.getComputedStyle(element, "");
+  var style = element.ownerGlobal.getComputedStyle(element);
   if (style.display == "none")
     return true;
   if (style.visibility != "visible")
     return true;
   if (style.display == "-moz-popup")
     return ["hiding","closed"].indexOf(element.state) != -1;
 
   // Hiding a parent element will hide all its children
   if (element.parentNode != element.ownerDocument)
     return is_hidden(element.parentNode);
 
   return false;
 }
 
 function is_visible(element) {
-  var style = element.ownerDocument.defaultView.getComputedStyle(element, "");
+  var style = element.ownerGlobal.getComputedStyle(element);
   if (style.display == "none")
     return false;
   if (style.visibility != "visible")
     return false;
   if (style.display == "-moz-popup" && element.state != "open")
     return false;
 
   // Hiding a parent element will hide all its children
@@ -892,17 +892,17 @@ function promisePopupShown(popup) {
   return promisePopupEvent(popup, "shown");
 }
 
 function promisePopupHidden(popup) {
   return promisePopupEvent(popup, "hidden");
 }
 
 function promiseNotificationShown(notification) {
-  let win = notification.browser.ownerDocument.defaultView;
+  let win = notification.browser.ownerGlobal;
   if (win.PopupNotifications.panel.state == "open") {
     return Promise.resolve();
   }
   let panelPromise = promisePopupShown(win.PopupNotifications.panel);
   notification.reshow();
   return panelPromise;
 }
 
--- a/browser/base/content/test/urlbar/head.js
+++ b/browser/base/content/test/urlbar/head.js
@@ -245,33 +245,33 @@ function makeActionURI(action, params) {
   for (let key in params) {
     encodedParams[key] = encodeURIComponent(params[key]);
   }
   let url = "moz-action:" + action + "," + JSON.stringify(encodedParams);
   return NetUtil.newURI(url);
 }
 
 function is_hidden(element) {
-  var style = element.ownerDocument.defaultView.getComputedStyle(element, "");
+  var style = element.ownerGlobal.getComputedStyle(element);
   if (style.display == "none")
     return true;
   if (style.visibility != "visible")
     return true;
   if (style.display == "-moz-popup")
     return ["hiding","closed"].indexOf(element.state) != -1;
 
   // Hiding a parent element will hide all its children
   if (element.parentNode != element.ownerDocument)
     return is_hidden(element.parentNode);
 
   return false;
 }
 
 function is_visible(element) {
-  var style = element.ownerDocument.defaultView.getComputedStyle(element, "");
+  var style = element.ownerGlobal.getComputedStyle(element);
   if (style.display == "none")
     return false;
   if (style.visibility != "visible")
     return false;
   if (style.display == "-moz-popup" && element.state != "open")
     return false;
 
   // Hiding a parent element will hide all its children
--- a/browser/base/content/test/webrtc/head.js
+++ b/browser/base/content/test/webrtc/head.js
@@ -160,17 +160,17 @@ function promisePopupEvent(popup, eventS
     popup.removeEventListener(eventType, onPopupShown);
     deferred.resolve();
   });
 
   return deferred.promise;
 }
 
 function promiseNotificationShown(notification) {
-  let win = notification.browser.ownerDocument.defaultView;
+  let win = notification.browser.ownerGlobal;
   if (win.PopupNotifications.panel.state == "open") {
     return Promise.resolve();
   }
   let panelPromise = promisePopupEvent(win.PopupNotifications.panel, "shown");
   notification.reshow();
   return panelPromise;
 }
 
--- a/browser/base/content/webrtcIndicator.js
+++ b/browser/base/content/webrtcIndicator.js
@@ -121,17 +121,17 @@ function onPopupMenuCommand(event) {
   let item = event.target;
   webrtcUI.showSharingDoorhanger(item.stream,
                                  item.parentNode.getAttribute("type"));
 }
 
 function onFirefoxButtonClick(event) {
   event.target.blur();
   let activeStreams = webrtcUI.getActiveStreams(true, true, true);
-  activeStreams[0].browser.ownerDocument.defaultView.focus();
+  activeStreams[0].browser.ownerGlobal.focus();
 }
 
 var PositionHandler = {
   positionCustomized: false,
   threshold: 10,
   adjustPosition: function() {
     if (!this.positionCustomized) {
       // Center the window horizontally on the screen (not the available area).
--- a/browser/components/contextualidentity/test/browser/browser_broadcastchannel.js
+++ b/browser/components/contextualidentity/test/browser/browser_broadcastchannel.js
@@ -7,17 +7,17 @@ const URI = BASE_ORIGIN +
 // 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, browser};
 }
 
 add_task(function* setup() {
   // make sure userContext is enabled.
--- a/browser/components/contextualidentity/test/browser/browser_favicon.js
+++ b/browser/components/contextualidentity/test/browser/browser_favicon.js
@@ -32,17 +32,17 @@ function getIconFile() {
 }
 
 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 loadIndexHandler(metadata, response) {
   response.setStatusLine(metadata.httpVersion, 200, "Ok");
--- a/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js
+++ b/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js
@@ -56,17 +56,17 @@ function loadImagePageHandler(metadata, 
 }
 
 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 getCookiesForOA(host, userContextId) {
   return Services.cookies.getCookiesFromHost(host, {userContextId});
--- a/browser/components/contextualidentity/test/browser/browser_serviceworkers.js
+++ b/browser/components/contextualidentity/test/browser/browser_serviceworkers.js
@@ -11,17 +11,17 @@ const NUM_USER_CONTEXTS = 3;
 // 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();
 
   return tab;
 }
 
 add_task(function* setup() {
   // make sure userContext is enabled.
   yield new Promise(resolve => {
     SpecialPowers.pushPrefEnv({"set": [
--- a/browser/components/contextualidentity/test/browser/browser_usercontext.js
+++ b/browser/components/contextualidentity/test/browser/browser_usercontext.js
@@ -15,17 +15,17 @@ const BASE_URI = "http://mochi.test:8888
 // 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();
 
   return tab;
 }
 
 add_task(function* setup() {
   // make sure userContext is enabled.
   yield new Promise(resolve => {
     SpecialPowers.pushPrefEnv({"set": [
--- a/browser/components/customizableui/CustomizableUI.jsm
+++ b/browser/components/customizableui/CustomizableUI.jsm
@@ -814,27 +814,27 @@ var CustomizableUIInternal = {
     } finally {
       this.endBatchUpdate();
     }
   },
 
   addPanelCloseListeners: function(aPanel) {
     gELS.addSystemEventListener(aPanel, "click", this, false);
     gELS.addSystemEventListener(aPanel, "keypress", this, false);
-    let win = aPanel.ownerDocument.defaultView;
+    let win = aPanel.ownerGlobal;
     if (!gPanelsForWindow.has(win)) {
       gPanelsForWindow.set(win, new Set());
     }
     gPanelsForWindow.get(win).add(this._getPanelForNode(aPanel));
   },
 
   removePanelCloseListeners: function(aPanel) {
     gELS.removeSystemEventListener(aPanel, "click", this, false);
     gELS.removeSystemEventListener(aPanel, "keypress", this, false);
-    let win = aPanel.ownerDocument.defaultView;
+    let win = aPanel.ownerGlobal;
     let panels = gPanelsForWindow.get(win);
     if (panels) {
       panels.delete(this._getPanelForNode(aPanel));
     }
   },
 
   ensureButtonContextMenu: function(aNode, aAreaNode) {
     const kPanelItemContextMenu = "customizationPanelItemContextMenu";
@@ -955,17 +955,17 @@ var CustomizableUIInternal = {
     let area = gAreas.get(aArea);
     let isToolbar = area.get("type") == CustomizableUI.TYPE_TOOLBAR;
     let isOverflowable = isToolbar && area.get("overflowable");
     let showInPrivateBrowsing = gPalette.has(aWidgetId)
                               ? gPalette.get(aWidgetId).showInPrivateBrowsing
                               : true;
 
     for (let areaNode of areaNodes) {
-      let window = areaNode.ownerDocument.defaultView;
+      let window = areaNode.ownerGlobal;
       if (!showInPrivateBrowsing &&
           PrivateBrowsingUtils.isWindowPrivate(window)) {
         continue;
       }
 
       let container = areaNode.customizationTarget;
       let widgetNode = window.document.getElementById(aWidgetId);
       if (widgetNode && isOverflowable) {
@@ -1015,17 +1015,17 @@ var CustomizableUIInternal = {
 
   onCustomizeEnd: function(aWindow) {
     this._clearPreviousUIState();
   },
 
   registerBuildArea: function(aArea, aNode) {
     // We ensure that the window is registered to have its customization data
     // cleaned up when unloading.
-    let window = aNode.ownerDocument.defaultView;
+    let window = aNode.ownerGlobal;
     if (window.closed) {
       return;
     }
     this.registerBuildWindow(window);
 
     // Also register this build area's toolbox.
     if (aNode.toolbox) {
       gBuildWindows.get(window).add(aNode.toolbox);
@@ -1133,17 +1133,17 @@ var CustomizableUIInternal = {
     // Go through each of the nodes associated with this area and move the
     // widget to the requested location.
     for (let areaNode of areaNodes) {
       this.insertNodeInWindow(aWidgetId, areaNode, isNew);
     }
   },
 
   insertNodeInWindow: function(aWidgetId, aAreaNode, isNew) {
-    let window = aAreaNode.ownerDocument.defaultView;
+    let window = aAreaNode.ownerGlobal;
     let showInPrivateBrowsing = gPalette.has(aWidgetId)
                               ? gPalette.get(aWidgetId).showInPrivateBrowsing
                               : true;
 
     if (!showInPrivateBrowsing && PrivateBrowsingUtils.isWindowPrivate(window)) {
       return;
     }
 
@@ -1493,17 +1493,17 @@ var CustomizableUIInternal = {
         }
       } else {
         //XXXunf Need to think this through more, and formalize.
         Services.obs.notifyObservers(aNode,
                                      "customizedui-widget-command",
                                      aWidget.id);
       }
     } else if (aWidget.type == "view") {
-      let ownerWindow = aNode.ownerDocument.defaultView;
+      let ownerWindow = aNode.ownerGlobal;
       let area = this.getPlacementOfWidget(aNode.id).area;
       let anchor = aNode;
       if (area != CustomizableUI.AREA_PANEL) {
         let wrapper = this.wrapWidget(aWidget.id).forWindow(ownerWindow);
         if (wrapper && wrapper.anchor) {
           this.hidePanelForNode(aNode);
           anchor = wrapper.anchor;
         }
@@ -1713,17 +1713,17 @@ var CustomizableUIInternal = {
       }
     }
 
     // If we get here, we can actually hide the popup:
     this.hidePanelForNode(aEvent.target);
   },
 
   getUnusedWidgets: function(aWindowPalette) {
-    let window = aWindowPalette.ownerDocument.defaultView;
+    let window = aWindowPalette.ownerGlobal;
     let isWindowPrivate = PrivateBrowsingUtils.isWindowPrivate(window);
     // We use a Set because there can be overlap between the widgets in
     // gPalette and the items in the palette, especially after the first
     // customization, since programmatically generated widgets will remain
     // in the toolbox palette.
     let widgets = new Set();
 
     // It's possible that some widgets have been defined programmatically and
@@ -2493,17 +2493,17 @@ var CustomizableUIInternal = {
 
   getCustomizeTargetForArea: function(aArea, aWindow) {
     let buildAreaNodes = gBuildAreas.get(aArea);
     if (!buildAreaNodes) {
       return null;
     }
 
     for (let node of buildAreaNodes) {
-      if (node.ownerDocument.defaultView === aWindow) {
+      if (node.ownerGlobal == aWindow) {
         return node.customizationTarget ? node.customizationTarget : node;
       }
     }
 
     return null;
   },
 
   reset: function() {
@@ -2579,17 +2579,17 @@ var CustomizableUIInternal = {
       let placements = gPlacements.get(areaId);
       let isFirstChangedToolbar = true;
       for (let areaNode of areaNodes) {
         this.buildArea(areaId, placements, areaNode);
 
         let area = gAreas.get(areaId);
         if (area.get("type") == CustomizableUI.TYPE_TOOLBAR) {
           let defaultCollapsed = area.get("defaultCollapsed");
-          let win = areaNode.ownerDocument.defaultView;
+          let win = areaNode.ownerGlobal;
           if (defaultCollapsed !== null) {
             win.setToolbarVisibility(areaNode, !defaultCollapsed, isFirstChangedToolbar);
           }
         }
         isFirstChangedToolbar = false;
       }
     }
   },
@@ -2705,17 +2705,17 @@ var CustomizableUIInternal = {
     let placement = this.getPlacementOfWidget(aWidgetId);
     if (!placement) {
       return false;
     }
     let areaNodes = gBuildAreas.get(placement.area);
     if (!areaNodes) {
       return false;
     }
-    let container = [...areaNodes].filter((n) => n.ownerDocument.defaultView == aWindow);
+    let container = [...areaNodes].filter((n) => n.ownerGlobal == aWindow);
     if (!container.length) {
       return false;
     }
     let existingNode = container[0].getElementsByAttribute("id", aWidgetId)[0];
     if (existingNode) {
       return true;
     }
 
@@ -3808,17 +3808,17 @@ function WidgetGroupWrapper(aWidget) {
     if (!placement) {
       return [];
     }
     let area = placement.area;
     let buildAreas = gBuildAreas.get(area);
     if (!buildAreas) {
       return [];
     }
-    return Array.from(buildAreas, (node) => this.forWindow(node.ownerDocument.defaultView));
+    return Array.from(buildAreas, (node) => this.forWindow(node.ownerGlobal));
   });
 
   this.__defineGetter__("areaType", function() {
     let areaProps = gAreas.get(aWidget.currentArea);
     return areaProps && areaProps.get("type");
   });
 
   Object.freeze(this);
@@ -3952,17 +3952,17 @@ function XULWidgetSingleWrapper(aWidgetI
       return null;
     }
     if (aNode) {
       // Return the last known node if it's still in the DOM...
       if (aNode.ownerDocument.contains(aNode)) {
         return aNode;
       }
       // ... or the toolbox
-      let toolbox = aNode.ownerDocument.defaultView.gNavToolbox;
+      let toolbox = aNode.ownerGlobal.gNavToolbox;
       if (toolbox && toolbox.palette && aNode.parentNode == toolbox.palette) {
         return aNode;
       }
       // If it isn't, clear the cached value and fall through to the "slow" case:
       aNode = null;
     }
 
     let doc = weakDoc.get();
@@ -4013,31 +4013,31 @@ function OverflowableToolbar(aToolbarNod
 
   this._toolbar.setAttribute("overflowable", "true");
   let doc = this._toolbar.ownerDocument;
   this._target = this._toolbar.customizationTarget;
   this._list = doc.getElementById(this._toolbar.getAttribute("overflowtarget"));
   this._list.toolbox = this._toolbar.toolbox;
   this._list.customizationTarget = this._list;
 
-  let window = this._toolbar.ownerDocument.defaultView;
+  let window = this._toolbar.ownerGlobal;
   if (window.gBrowserInit.delayedStartupFinished) {
     this.init();
   } else {
     Services.obs.addObserver(this, "browser-delayed-startup-finished", false);
   }
 }
 
 OverflowableToolbar.prototype = {
   initialized: false,
   _forceOnOverflow: false,
 
   observe: function(aSubject, aTopic, aData) {
     if (aTopic == "browser-delayed-startup-finished" &&
-        aSubject == this._toolbar.ownerDocument.defaultView) {
+        aSubject == this._toolbar.ownerGlobal) {
       Services.obs.removeObserver(this, "browser-delayed-startup-finished");
       this.init();
     }
   },
 
   init: function() {
     let doc = this._toolbar.ownerDocument;
     let window = doc.defaultView;
@@ -4074,17 +4074,17 @@ OverflowableToolbar.prototype = {
 
     if (!this.initialized) {
       Services.obs.removeObserver(this, "browser-delayed-startup-finished");
       return;
     }
 
     this._disable();
 
-    let window = this._toolbar.ownerDocument.defaultView;
+    let window = this._toolbar.ownerGlobal;
     window.removeEventListener("resize", this);
     window.gNavToolbox.removeEventListener("customizationstarting", this);
     window.gNavToolbox.removeEventListener("aftercustomization", this);
     this._chevron.removeEventListener("command", this);
     this._chevron.removeEventListener("dragover", this);
     this._chevron.removeEventListener("dragend", this);
     this._panel.removeEventListener("popuphiding", this);
     CustomizableUI.removeListener(this);
@@ -4185,17 +4185,17 @@ OverflowableToolbar.prototype = {
         if (!this._toolbar.hasAttribute("overflowing")) {
           CustomizableUI.addListener(this);
         }
         this._toolbar.setAttribute("overflowing", "true");
       }
       child = prevChild;
     }
 
-    let win = this._target.ownerDocument.defaultView;
+    let win = this._target.ownerGlobal;
     win.UpdateUrlbarSearchSplitterState();
   },
 
   _onResize: function(aEvent) {
     if (!this._lazyResizeHandler) {
       this._lazyResizeHandler = new DeferredTask(this._onLazyResize.bind(this),
                                                  LAZY_RESIZE_INTERVAL_MS);
     }
@@ -4234,17 +4234,17 @@ OverflowableToolbar.prototype = {
       if (!inserted) {
         this._target.appendChild(child);
       }
       child.removeAttribute("cui-anchorid");
       child.removeAttribute("overflowedItem");
       CustomizableUIInternal.notifyListeners("onWidgetUnderflow", child, this._target);
     }
 
-    let win = this._target.ownerDocument.defaultView;
+    let win = this._target.ownerGlobal;
     win.UpdateUrlbarSearchSplitterState();
 
     if (!this._collapsed.size) {
       this._toolbar.removeAttribute("overflowing");
       CustomizableUI.removeListener(this);
     }
   },
 
@@ -4393,17 +4393,17 @@ OverflowableToolbar.prototype = {
       return this._list;
     }
     return this._target;
   },
 
   _hideTimeoutId: null,
   _showWithTimeout: function() {
     this.show().then(function () {
-      let window = this._toolbar.ownerDocument.defaultView;
+      let window = this._toolbar.ownerGlobal;
       if (this._hideTimeoutId) {
         window.clearTimeout(this._hideTimeoutId);
       }
       this._hideTimeoutId = window.setTimeout(() => {
         if (!this._panel.firstChild.matches(":hover")) {
           this._panel.hidePopup();
         }
       }, OVERFLOW_PANEL_HIDE_DELAY_MS);
--- a/browser/components/customizableui/CustomizableWidgets.jsm
+++ b/browser/components/customizableui/CustomizableWidgets.jsm
@@ -499,58 +499,53 @@ const CustomizableWidgets = [
       });
       return item;
     },
   }, {
     id: "privatebrowsing-button",
     shortcutId: "key_privatebrowsing",
     defaultArea: CustomizableUI.AREA_PANEL,
     onCommand: function(e) {
-      if (e.target && e.target.ownerDocument && e.target.ownerDocument.defaultView) {
-        let win = e.target.ownerDocument.defaultView;
-        if (typeof win.OpenBrowserWindow == "function") {
-          win.OpenBrowserWindow({private: true});
-        }
+      let win = e.target && e.target.ownerGlobal;
+      if (win && typeof win.OpenBrowserWindow == "function") {
+        win.OpenBrowserWindow({private: true});
       }
     }
   }, {
     id: "save-page-button",
     shortcutId: "key_savePage",
     tooltiptext: "save-page-button.tooltiptext3",
     defaultArea: CustomizableUI.AREA_PANEL,
     onCommand: function(aEvent) {
       let win = aEvent.target &&
-                aEvent.target.ownerDocument &&
-                aEvent.target.ownerDocument.defaultView;
+                aEvent.target.ownerGlobal;
       if (win && typeof win.saveBrowser == "function") {
         win.saveBrowser(win.gBrowser.selectedBrowser);
       }
     }
   }, {
     id: "find-button",
     shortcutId: "key_find",
     tooltiptext: "find-button.tooltiptext3",
     defaultArea: CustomizableUI.AREA_PANEL,
     onCommand: function(aEvent) {
       let win = aEvent.target &&
-                aEvent.target.ownerDocument &&
-                aEvent.target.ownerDocument.defaultView;
+                aEvent.target.ownerGlobal;
       if (win && win.gFindBar) {
         win.gFindBar.onFindCommand();
       }
     }
   }, {
     id: "open-file-button",
     shortcutId: "openFileKb",
     tooltiptext: "open-file-button.tooltiptext3",
     defaultArea: CustomizableUI.AREA_PANEL,
     onCommand: function(aEvent) {
       let win = aEvent.target
-                && aEvent.target.ownerDocument
-                && aEvent.target.ownerDocument.defaultView;
+                && aEvent.target.ownerGlobal;
       if (win && typeof win.BrowserOpenFileWindow == "function") {
         win.BrowserOpenFileWindow();
       }
     }
   }, {
     id: "sidebar-button",
     type: "view",
     viewId: "PanelUI-sidebar",
@@ -618,18 +613,17 @@ const CustomizableWidgets = [
     }
   }, {
     id: "add-ons-button",
     shortcutId: "key_openAddons",
     tooltiptext: "add-ons-button.tooltiptext3",
     defaultArea: CustomizableUI.AREA_PANEL,
     onCommand: function(aEvent) {
       let win = aEvent.target &&
-                aEvent.target.ownerDocument &&
-                aEvent.target.ownerDocument.defaultView;
+                aEvent.target.ownerGlobal;
       if (win && typeof win.BrowserOpenAddonsMgr == "function") {
         win.BrowserOpenAddonsMgr();
       }
     }
   }, {
     id: "zoom-controls",
     type: "custom",
     tooltiptext: "zoom-controls.tooltiptext2",
@@ -895,17 +889,17 @@ const CustomizableWidgets = [
   },
   {
     id: "feed-button",
     type: "view",
     viewId: "PanelUI-feeds",
     tooltiptext: "feed-button.tooltiptext2",
     defaultArea: CustomizableUI.AREA_PANEL,
     onClick: function(aEvent) {
-      let win = aEvent.target.ownerDocument.defaultView;
+      let win = aEvent.target.ownerGlobal;
       let feeds = win.gBrowser.selectedBrowser.feeds;
 
       // Here, we only care about the case where we have exactly 1 feed and the
       // user clicked...
       let isClick = (aEvent.button == 0 || aEvent.button == 1);
       if (feeds && feeds.length == 1 && isClick) {
         aEvent.preventDefault();
         aEvent.stopPropagation();
@@ -921,17 +915,17 @@ const CustomizableWidgets = [
       // For no feeds or only a single one, don't show the panel.
       if (!gotView) {
         aEvent.preventDefault();
         aEvent.stopPropagation();
         return;
       }
     },
     onCreated: function(node) {
-      let win = node.ownerDocument.defaultView;
+      let win = node.ownerGlobal;
       let selectedBrowser = win.gBrowser.selectedBrowser;
       let feeds = selectedBrowser && selectedBrowser.feeds;
       if (!feeds || !feeds.length) {
         node.setAttribute("disabled", "true");
       }
     }
   }, {
     id: "characterencoding-button",
@@ -1022,17 +1016,17 @@ const CustomizableWidgets = [
       this.updateCurrentCharset(document);
     },
     onCommand: function(aEvent) {
       let node = aEvent.target;
       if (!node.hasAttribute || !node.section) {
         return;
       }
 
-      let window = node.ownerDocument.defaultView;
+      let window = node.ownerGlobal;
       let section = node.section;
       let value = node.value;
 
       // The behavior as implemented here is directly based off of the
       // `MultiplexHandler()` method in browser.js.
       if (section != "detectors") {
         window.BrowserSetForcedCharacterSet(value);
       } else {
@@ -1156,18 +1150,17 @@ if (Services.prefs.getBoolPref("privacy.
   });
 }
 
 let preferencesButton = {
   id: "preferences-button",
   defaultArea: CustomizableUI.AREA_PANEL,
   onCommand: function(aEvent) {
     let win = aEvent.target &&
-              aEvent.target.ownerDocument &&
-              aEvent.target.ownerDocument.defaultView;
+              aEvent.target.ownerGlobal;
     if (win && typeof win.openPreferences == "function") {
       win.openPreferences();
     }
   }
 };
 if (AppConstants.platform == "win") {
   preferencesButton.label = "preferences-button.labelWin";
   preferencesButton.tooltiptext = "preferences-button.tooltipWin2";
--- a/browser/components/customizableui/CustomizeMode.jsm
+++ b/browser/components/customizableui/CustomizeMode.jsm
@@ -1238,34 +1238,34 @@ CustomizeMode.prototype = {
     this._onUIChange();
   },
 
   onWidgetRemoved: function(aWidgetId, aArea) {
     this._onUIChange();
   },
 
   onWidgetBeforeDOMChange: function(aNodeToChange, aSecondaryNode, aContainer) {
-    if (aContainer.ownerDocument.defaultView != this.window || this.resetting) {
+    if (aContainer.ownerGlobal != this.window || this.resetting) {
       return;
     }
     if (aContainer.id == CustomizableUI.AREA_PANEL) {
       this._removePanelCustomizationPlaceholders();
     }
     // If we get called for widgets that aren't in the window yet, they might not have
     // a parentNode at all.
     if (aNodeToChange.parentNode) {
       this.unwrapToolbarItem(aNodeToChange.parentNode);
     }
     if (aSecondaryNode) {
       this.unwrapToolbarItem(aSecondaryNode.parentNode);
     }
   },
 
   onWidgetAfterDOMChange: function(aNodeToChange, aSecondaryNode, aContainer) {
-    if (aContainer.ownerDocument.defaultView != this.window || this.resetting) {
+    if (aContainer.ownerGlobal != this.window || this.resetting) {
       return;
     }
     // If the node is still attached to the container, wrap it again:
     if (aNodeToChange.parentNode) {
       let place = CustomizableUI.getPlaceForItem(aNodeToChange);
       this.wrapToolbarItem(aNodeToChange, place);
       if (aSecondaryNode) {
         this.wrapToolbarItem(aSecondaryNode, place);
@@ -1692,17 +1692,17 @@ CustomizeMode.prototype = {
                                          targetParent.lastChild;
         dragValue = "after";
       } else {
         dragOverItem = targetParent.children[position];
         if (!targetIsToolbar) {
           dragValue = "before";
         } else {
           // Check if the aDraggedItem is hovered past the first half of dragOverItem
-          let window = dragOverItem.ownerDocument.defaultView;
+          let window = dragOverItem.ownerGlobal;
           let direction = window.getComputedStyle(dragOverItem, null).direction;
           let itemRect = dragOverItem.getBoundingClientRect();
           let dropTargetCenter = itemRect.left + (itemRect.width / 2);
           let existingDir = dragOverItem.getAttribute("dragover");
           if ((existingDir == "before") == (direction == "ltr")) {
             dropTargetCenter += (parseInt(dragOverItem.style.borderLeftWidth) || 0) / 2;
           } else {
             dropTargetCenter -= (parseInt(dragOverItem.style.borderRightWidth) || 0) / 2;
@@ -1981,28 +1981,28 @@ CustomizeMode.prototype = {
     }
 
     /* 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.
     return !mozSourceNode ||
-           mozSourceNode.ownerDocument.defaultView != this.window;
+           mozSourceNode.ownerGlobal != this.window;
   },
 
   _setDragActive: function(aItem, aValue, aDraggedItemId, aInToolbar) {
     if (!aItem) {
       return;
     }
 
     if (aItem.getAttribute("dragover") != aValue) {
       aItem.setAttribute("dragover", aValue);
 
-      let window = aItem.ownerDocument.defaultView;
+      let window = aItem.ownerGlobal;
       let draggedItem = window.document.getElementById(aDraggedItemId);
       if (!aInToolbar) {
         this._setGridDragActive(aItem, draggedItem, aValue);
       } else {
         let targetArea = this._getCustomizableParent(aItem);
         this._updateToolbarCustomizationOutline(window, targetArea);
         let makeSpaceImmediately = false;
         if (!gDraggingInToolbars.has(targetArea.id)) {
@@ -2033,17 +2033,17 @@ CustomizeMode.prototype = {
           // Force a layout flush:
           aItem.getBoundingClientRect();
           aItem.removeAttribute("notransition");
         }
       }
     }
   },
   _cancelDragActive: function(aItem, aNextItem, aNoTransition) {
-    this._updateToolbarCustomizationOutline(aItem.ownerDocument.defaultView);
+    this._updateToolbarCustomizationOutline(aItem.ownerGlobal);
     let currentArea = this._getCustomizableParent(aItem);
     if (!currentArea) {
       return;
     }
     let isToolbar = CustomizableUI.getAreaType(currentArea.id) == "toolbar";
     if (isToolbar) {
       if (aNoTransition) {
         aItem.setAttribute("notransition", "true");
--- a/browser/components/customizableui/DragPositionManager.jsm
+++ b/browser/components/customizableui/DragPositionManager.jsm
@@ -10,17 +10,17 @@ var gManagers = new WeakMap();
 
 const kPaletteId = "customization-palette";
 const kPlaceholderClass = "panel-customization-placeholder";
 
 this.EXPORTED_SYMBOLS = ["DragPositionManager"];
 
 function AreaPositionManager(aContainer) {
   // Caching the direction and bounds of the container for quick access later:
-  let window = aContainer.ownerDocument.defaultView;
+  let window = aContainer.ownerGlobal;
   this._dir = window.getComputedStyle(aContainer).direction;
   let containerRect = aContainer.getBoundingClientRect();
   this._containerInfo = {
     left: containerRect.left,
     right: containerRect.right,
     top: containerRect.top,
     width: containerRect.width
   };
@@ -29,17 +29,17 @@ function AreaPositionManager(aContainer)
   this.update(aContainer);
 }
 
 AreaPositionManager.prototype = {
   _nodePositionStore: null,
   _wideCache: null,
 
   update: function(aContainer) {
-    let window = aContainer.ownerDocument.defaultView;
+    let window = aContainer.ownerGlobal;
     this._nodePositionStore = new WeakMap();
     this._wideCache = new Set();
     let last = null;
     let singleItemHeight;
     for (let child of aContainer.children) {
       if (child.hidden) {
         continue;
       }
--- a/browser/components/customizableui/test/head.js
+++ b/browser/components/customizableui/test/head.js
@@ -296,32 +296,32 @@ function promisePanelElementHidden(win, 
 }
 
 function isPanelUIOpen() {
   return PanelUI.panel.state == "open" || PanelUI.panel.state == "showing";
 }
 
 function subviewShown(aSubview) {
   let deferred = Promise.defer();
-  let win = aSubview.ownerDocument.defaultView;
+  let win = aSubview.ownerGlobal;
   let timeoutId = win.setTimeout(() => {
     deferred.reject("Subview (" + aSubview.id + ") did not show within 20 seconds.");
   }, 20000);
   function onViewShowing(e) {
     aSubview.removeEventListener("ViewShowing", onViewShowing);
     win.clearTimeout(timeoutId);
     deferred.resolve();
   }
   aSubview.addEventListener("ViewShowing", onViewShowing);
   return deferred.promise;
 }
 
 function subviewHidden(aSubview) {
   let deferred = Promise.defer();
-  let win = aSubview.ownerDocument.defaultView;
+  let win = aSubview.ownerGlobal;
   let timeoutId = win.setTimeout(() => {
     deferred.reject("Subview (" + aSubview.id + ") did not hide within 20 seconds.");
   }, 20000);
   function onViewHiding(e) {
     aSubview.removeEventListener("ViewHiding", onViewHiding);
     win.clearTimeout(timeoutId);
     deferred.resolve();
   }
@@ -471,17 +471,17 @@ function popupHidden(aPopup) {
  *   yield popupShownPromise;
  *
  *  let popupHiddenPromise = promisePopupEvent(somePopup, "hidden");
  *  // ... something that hides a popup
  *  yield popupHiddenPromise;
  */
 function promisePopupEvent(aPopup, aEventSuffix) {
   let deferred = Promise.defer();
-  let win = aPopup.ownerDocument.defaultView;
+  let win = aPopup.ownerGlobal;
   let eventType = "popup" + aEventSuffix;
 
   function onPopupEvent(e) {
     aPopup.removeEventListener(eventType, onPopupEvent);
     deferred.resolve();
   }
 
   aPopup.addEventListener(eventType, onPopupEvent);
--- a/browser/components/extensions/ext-browserAction.js
+++ b/browser/components/extensions/ext-browserAction.js
@@ -109,17 +109,17 @@ BrowserAction.prototype = {
           // with the fewest complications.
           event.preventDefault();
           this.emit("click");
         }
       },
     });
 
     this.tabContext.on("tab-select", // eslint-disable-line mozilla/balanced-listeners
-                       (evt, tab) => { this.updateWindow(tab.ownerDocument.defaultView); });
+                       (evt, tab) => { this.updateWindow(tab.ownerGlobal); });
 
     this.widget = widget;
   },
 
   // Update the toolbar button |node| with the tab context data
   // in |tabData|.
   updateButton(node, tabData) {
     let title = tabData.title || this.extension.name;
@@ -191,17 +191,17 @@ BrowserAction.prototype = {
   },
 
   // Update the toolbar button when the extension changes the icon,
   // title, badge, etc. If it only changes a parameter for a single
   // tab, |tab| will be that tab. Otherwise it will be null.
   updateOnChange(tab) {
     if (tab) {
       if (tab.selected) {
-        this.updateWindow(tab.ownerDocument.defaultView);
+        this.updateWindow(tab.ownerGlobal);
       }
     } else {
       for (let window of WindowListManager.browserWindows()) {
         this.updateWindow(window);
       }
     }
   },
 
--- a/browser/components/extensions/ext-commands.js
+++ b/browser/components/extensions/ext-commands.js
@@ -119,17 +119,17 @@ 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 {
         this.emit("command", name);
       }
     });
     /* eslint-enable mozilla/balanced-listeners */
 
     return keyElement;
--- a/browser/components/extensions/ext-contextMenus.js
+++ b/browser/components/extensions/ext-contextMenus.js
@@ -46,17 +46,17 @@ var gMenuBuilder = {
         // the root menu item itself either.
         continue;
       }
       rootElement.setAttribute("ext-type", "top-level-menu");
       rootElement = this.removeTopLevelMenuIfNeeded(rootElement);
 
       // Display the extension icon on the root element.
       if (root.extension.manifest.icons) {
-        let parentWindow = contextData.menu.ownerDocument.defaultView;
+        let parentWindow = contextData.menu.ownerGlobal;
         let extension = root.extension;
 
         let {icon} = IconDetails.getPreferredIcon(extension.manifest.icons, extension,
                                                   16 * parentWindow.devicePixelRatio);
 
         // The extension icons in the manifest are not pre-resolved, since
         // they're sometimes used by the add-on manager when the extension is
         // not enabled, and its URLs are not resolvable.
--- a/browser/components/extensions/ext-pageAction.js
+++ b/browser/components/extensions/ext-pageAction.js
@@ -59,17 +59,17 @@ PageAction.prototype = {
   setProperty(tab, prop, value) {
     if (value != null) {
       this.tabContext.get(tab)[prop] = value;
     } else {
       delete this.tabContext.get(tab)[prop];
     }
 
     if (tab.selected) {
-      this.updateButton(tab.ownerDocument.defaultView);
+      this.updateButton(tab.ownerGlobal);
     }
   },
 
   // Updates the page action button in the given window to reflect the
   // properties of the currently selected tab:
   //
   // Updates "tooltiptext" and "aria-label" to match "title" property.
   // Updates "image" to match the "icon" property.
@@ -178,17 +178,17 @@ PageAction.prototype = {
       this.emit("click", tab);
     }
   },
 
   handleLocationChange(eventType, tab, fromBrowse) {
     if (fromBrowse) {
       this.tabContext.clear(tab);
     }
-    this.updateButton(tab.ownerDocument.defaultView);
+    this.updateButton(tab.ownerGlobal);
   },
 
   shutdown() {
     this.tabContext.shutdown();
 
     for (let window of WindowListManager.browserWindows()) {
       if (this.buttons.has(window)) {
         this.buttons.get(window).remove();
--- a/browser/components/extensions/ext-tabs.js
+++ b/browser/components/extensions/ext-tabs.js
@@ -21,17 +21,17 @@ var {
 
 // This function is pretty tightly tied to Extension.jsm.
 // Its job is to fill in the |tab| property of the sender.
 function getSender(context, target, sender) {
   // The message was sent from a content script to a <browser> element.
   // We can just get the |tab| from |target|.
   if (target instanceof Ci.nsIDOMXULElement) {
     // The message came from a content script.
-    let tabbrowser = target.ownerDocument.defaultView.gBrowser;
+    let tabbrowser = target.ownerGlobal.gBrowser;
     if (!tabbrowser) {
       return;
     }
     let tab = tabbrowser.getTabForBrowser(target);
 
     sender.tab = TabManager.convert(context.extension, tab);
   } else if ("tabId" in sender) {
     // The message came from an ExtensionContext. In that case, it should
@@ -49,17 +49,17 @@ var pageDataMap = new WeakMap();
 // This listener fires whenever an extension page opens in a tab
 // (either initiated by the extension or the user). Its job is to fill
 // in some tab-specific details and keep data around about the
 // ExtensionContext.
 extensions.on("page-load", (type, page, params, sender, delegate) => {
   if (params.type == "tab" || params.type == "popup") {
     let browser = params.docShell.chromeEventHandler;
 
-    let parentWindow = browser.ownerDocument.defaultView;
+    let parentWindow = browser.ownerGlobal;
     page.windowId = WindowManager.getId(parentWindow);
 
     let tab = parentWindow.gBrowser.getTabForBrowser(browser);
     if (tab) {
       sender.tabId = TabManager.getId(tab);
       page.tabId = TabManager.getId(tab);
     }
 
@@ -201,35 +201,35 @@ let tabListener = {
         this.emitDetached(tab, this.adoptedTabs.get(tab));
       } else {
         this.emitRemoved(tab, true);
       }
     }
   },
 
   emitAttached(tab) {
-    let newWindowId = WindowManager.getId(tab.ownerDocument.defaultView);
+    let newWindowId = WindowManager.getId(tab.ownerGlobal);
     let tabId = TabManager.getId(tab);
 
     this.emit("tab-attached", {tab, tabId, newWindowId, newPosition: tab._tPos});
   },
 
   emitDetached(tab, adoptedBy) {
-    let oldWindowId = WindowManager.getId(tab.ownerDocument.defaultView);
+    let oldWindowId = WindowManager.getId(tab.ownerGlobal);
     let tabId = TabManager.getId(tab);
 
     this.emit("tab-detached", {tab, adoptedBy, tabId, oldWindowId, oldPosition: tab._tPos});
   },
 
   emitCreated(tab) {
     this.emit("tab-created", {tab});
   },
 
   emitRemoved(tab, isWindowClosing) {
-    let windowId = WindowManager.getId(tab.ownerDocument.defaultView);
+    let windowId = WindowManager.getId(tab.ownerGlobal);
     let tabId = TabManager.getId(tab);
 
     this.emit("tab-removed", {tab, tabId, windowId, isWindowClosing});
   },
 
   tabReadyInitialized: false,
   tabReadyPromises: new WeakMap(),
 
@@ -238,17 +238,17 @@ let tabListener = {
       AllWindowEvents.addListener("progress", this);
 
       this.tabReadyInitialized = true;
     }
   },
 
   onLocationChange(browser, webProgress, request, locationURI, flags) {
     if (webProgress.isTopLevel) {
-      let gBrowser = browser.ownerDocument.defaultView.gBrowser;
+      let gBrowser = browser.ownerGlobal.gBrowser;
       let tab = gBrowser.getTabForBrowser(browser);
 
       let deferred = this.tabReadyPromises.get(tab);
       if (deferred) {
         deferred.resolve(tab);
         this.tabReadyPromises.delete(tab);
       }
     }
@@ -262,17 +262,17 @@ let tabListener = {
 };
 
 extensions.registerSchemaAPI("tabs", (extension, context) => {
   let self = {
     tabs: {
       onActivated: new WindowEventManager(context, "tabs.onActivated", "TabSelect", (fire, event) => {
         let tab = event.originalTarget;
         let tabId = TabManager.getId(tab);
-        let windowId = WindowManager.getId(tab.ownerDocument.defaultView);
+        let windowId = WindowManager.getId(tab.ownerGlobal);
         fire({tabId, windowId});
       }).api(),
 
       onCreated: new EventManager(context, "tabs.onCreated", fire => {
         let listener = (eventName, event) => {
           fire(TabManager.convert(extension, event.tab));
         };
 
@@ -287,17 +287,17 @@ extensions.registerSchemaAPI("tabs", (ex
        * Since multiple tabs currently can't be highlighted, onHighlighted
        * essentially acts an alias for self.tabs.onActivated but returns
        * the tabId in an array to match the API.
        * @see  https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/Tabs/onHighlighted
       */
       onHighlighted: new WindowEventManager(context, "tabs.onHighlighted", "TabSelect", (fire, event) => {
         let tab = event.originalTarget;
         let tabIds = [TabManager.getId(tab)];
-        let windowId = WindowManager.getId(tab.ownerDocument.defaultView);
+        let windowId = WindowManager.getId(tab.ownerGlobal);
         fire({tabIds, windowId});
       }).api(),
 
       onAttached: new EventManager(context, "tabs.onAttached", fire => {
         let listener = (eventName, event) => {
           fire(event.tabId, {newWindowId: event.newWindowId, newPosition: event.newPosition});
         };
 
@@ -358,17 +358,17 @@ extensions.registerSchemaAPI("tabs", (ex
           let tab = event.originalTarget;
 
           if (ignoreNextMove.has(tab)) {
             ignoreNextMove.delete(tab);
             return;
           }
 
           fire(TabManager.getId(tab), {
-            windowId: WindowManager.getId(tab.ownerDocument.defaultView),
+            windowId: WindowManager.getId(tab.ownerGlobal),
             fromIndex: event.detail,
             toIndex: tab._tPos,
           });
         };
 
         AllWindowEvents.addListener("TabMove", moveListener);
         AllWindowEvents.addListener("TabOpen", openListener);
         return () => {
@@ -388,17 +388,17 @@ extensions.registerSchemaAPI("tabs", (ex
             }
           }
           return [nonempty, result];
         }
 
         let fireForBrowser = (browser, changed) => {
           let [needed, changeInfo] = sanitize(extension, changed);
           if (needed) {
-            let gBrowser = browser.ownerDocument.defaultView.gBrowser;
+            let gBrowser = browser.ownerGlobal.gBrowser;
             let tabElem = gBrowser.getTabForBrowser(browser);
 
             let tab = TabManager.convert(extension, tabElem);
             fire(tab.id, changeInfo, tab);
           }
         };
 
         let listener = event => {
@@ -545,30 +545,30 @@ extensions.registerSchemaAPI("tabs", (ex
 
       remove: function(tabs) {
         if (!Array.isArray(tabs)) {
           tabs = [tabs];
         }
 
         for (let tabId of tabs) {
           let tab = TabManager.getTab(tabId);
-          tab.ownerDocument.defaultView.gBrowser.removeTab(tab);
+          tab.ownerGlobal.gBrowser.removeTab(tab);
         }
 
         return Promise.resolve();
       },
 
       update: function(tabId, updateProperties) {
         let tab = tabId !== null ? TabManager.getTab(tabId) : TabManager.activeTab;
 
         if (!tab) {
           return Promise.reject({message: `No tab found with tabId: ${tabId}`});
         }
 
-        let tabbrowser = tab.ownerDocument.defaultView.gBrowser;
+        let tabbrowser = tab.ownerGlobal.gBrowser;
 
         if (updateProperties.url !== null) {
           let url = context.uri.resolve(updateProperties.url);
 
           if (!context.checkLoadURL(url, {dontReportErrors: true})) {
             return Promise.reject({message: `Illegal URL: ${url}`});
           }
 
@@ -876,17 +876,17 @@ extensions.registerSchemaAPI("tabs", (ex
         for (let tabId of tabIds) {
           let tab = TabManager.getTab(tabId);
           // Ignore invalid tab ids.
           if (!tab) {
             continue;
           }
 
           // If the window is not specified, use the window from the tab.
-          let window = destinationWindow || tab.ownerDocument.defaultView;
+          let window = destinationWindow || tab.ownerGlobal;
           let gBrowser = window.gBrowser;
 
           let insertionPoint = indexMap.get(window) || index;
           // If the index is -1 it should go to the end of the tabs.
           if (insertionPoint == -1) {
             insertionPoint = gBrowser.tabs.length;
           }
 
@@ -897,17 +897,17 @@ extensions.registerSchemaAPI("tabs", (ex
           let numPinned = gBrowser._numPinnedTabs;
           let ok = tab.pinned ? insertionPoint <= numPinned : insertionPoint >= numPinned;
           if (!ok) {
             continue;
           }
 
           indexMap.set(window, insertionPoint + 1);
 
-          if (tab.ownerDocument.defaultView !== window) {
+          if (tab.ownerGlobal != window) {
             // If the window we are moving the tab in is different, then move the tab
             // to the new window.
             tab = gBrowser.adoptTab(tab, insertionPoint, false);
           } else {
             // If the window we are moving is the same, just move the tab.
             gBrowser.moveTabTo(tab, insertionPoint);
           }
           tabsMoved.push(tab);
@@ -917,17 +917,17 @@ extensions.registerSchemaAPI("tabs", (ex
       },
 
       duplicate: function(tabId) {
         let tab = TabManager.getTab(tabId);
         if (!tab) {
           return Promise.reject({message: `Invalid tab ID: ${tabId}`});
         }
 
-        let gBrowser = tab.ownerDocument.defaultView.gBrowser;
+        let gBrowser = tab.ownerGlobal.gBrowser;
         let newTab = gBrowser.duplicateTab(tab);
 
         return new Promise(resolve => {
           // We need to use SSTabRestoring because any attributes set before
           // are ignored. SSTabRestored is too late and results in a jump in
           // the UI. See http://bit.ly/session-store-api for more information.
           newTab.addEventListener("SSTabRestoring", function listener() {
             // As the tab is restoring, move it to the correct position.
@@ -947,26 +947,26 @@ extensions.registerSchemaAPI("tabs", (ex
             return resolve(TabManager.convert(extension, newTab));
           });
         });
       },
 
       getZoom(tabId) {
         let tab = tabId ? TabManager.getTab(tabId) : TabManager.activeTab;
 
-        let {ZoomManager} = tab.ownerDocument.defaultView;
+        let {ZoomManager} = tab.ownerGlobal;
         let zoom = ZoomManager.getZoomForBrowser(tab.linkedBrowser);
 
         return Promise.resolve(zoom);
       },
 
       setZoom(tabId, zoom) {
         let tab = tabId ? TabManager.getTab(tabId) : TabManager.activeTab;
 
-        let {FullZoom, ZoomManager} = tab.ownerDocument.defaultView;
+        let {FullZoom, ZoomManager} = tab.ownerGlobal;
 
         if (zoom === 0) {
           // A value of zero means use the default zoom factor.
           return FullZoom.reset(tab.linkedBrowser);
         } else if (zoom >= ZoomManager.MIN && zoom <= ZoomManager.MAX) {
           FullZoom.setZoom(zoom, tab.linkedBrowser);
         } else {
           return Promise.reject({
@@ -975,17 +975,17 @@ extensions.registerSchemaAPI("tabs", (ex
         }
 
         return Promise.resolve();
       },
 
       _getZoomSettings(tabId) {
         let tab = tabId ? TabManager.getTab(tabId) : TabManager.activeTab;
 
-        let {FullZoom} = tab.ownerDocument.defaultView;
+        let {FullZoom} = tab.ownerGlobal;
 
         return {
           mode: "automatic",
           scope: FullZoom.siteSpecific ? "per-origin" : "per-tab",
           defaultZoomFactor: 1,
         };
       },
 
@@ -1001,17 +1001,17 @@ extensions.registerSchemaAPI("tabs", (ex
         if (!Object.keys(settings).every(key => settings[key] === currentSettings[key])) {
           return Promise.reject(`Unsupported zoom settings: ${JSON.stringify(settings)}`);
         }
         return Promise.resolve();
       },
 
       onZoomChange: new EventManager(context, "tabs.onZoomChange", fire => {
         let getZoomLevel = browser => {
-          let {ZoomManager} = browser.ownerDocument.defaultView;
+          let {ZoomManager} = browser.ownerGlobal;
 
           return ZoomManager.getZoomForBrowser(browser);
         };
 
         // Stores the last known zoom level for each tab's browser.
         // WeakMap[<browser> -> number]
         let zoomLevels = new WeakMap();
 
@@ -1035,17 +1035,17 @@ extensions.registerSchemaAPI("tabs", (ex
           // For non-remote browsers, this event is dispatched on the document
           // rather than on the <browser>.
           if (browser instanceof Ci.nsIDOMDocument) {
             browser = browser.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
                              .getInterface(Ci.nsIDocShell)
                              .chromeEventHandler;
           }
 
-          let {gBrowser} = browser.ownerDocument.defaultView;
+          let {gBrowser} = browser.ownerGlobal;
           let tab = gBrowser.getTabForBrowser(browser);
           if (!tab) {
             // We only care about zoom events in the top-level browser of a tab.
             return;
           }
 
           let oldZoomFactor = zoomLevels.get(browser);
           let newZoomFactor = getZoomLevel(browser);
--- a/browser/components/extensions/ext-utils.js
+++ b/browser/components/extensions/ext-utils.js
@@ -68,17 +68,17 @@ class BasePopup {
     Services.scriptSecurityManager.checkLoadURIWithPrincipal(
       extension.principal, popupURI,
       Services.scriptSecurityManager.DISALLOW_SCRIPT);
 
     this.extension = extension;
     this.popupURI = popupURI;
     this.viewNode = viewNode;
     this.browserStyle = browserStyle;
-    this.window = viewNode.ownerDocument.defaultView;
+    this.window = viewNode.ownerGlobal;
 
     this.contentReady = new Promise(resolve => {
       this._resolveContentReady = resolve;
     });
 
     this.viewNode.addEventListener(this.DESTROY_EVENT, this);
 
     this.browser = null;
@@ -323,17 +323,17 @@ TabContext.prototype = {
     if (event.type == "TabSelect") {
       let tab = event.target;
       this.emit("tab-select", tab);
       this.emit("location-change", tab);
     }
   },
 
   onLocationChange(browser, webProgress, request, locationURI, flags) {
-    let gBrowser = browser.ownerDocument.defaultView.gBrowser;
+    let gBrowser = browser.ownerGlobal.gBrowser;
     if (browser === gBrowser.selectedBrowser) {
       let tab = gBrowser.getTabForBrowser(browser);
       this.emit("location-change", tab, true);
     }
   },
 
   shutdown() {
     AllWindowEvents.removeListener("progress", this);
@@ -379,17 +379,17 @@ ExtensionTabManager.prototype = {
     return false;
   },
 
   hasTabPermission(tab) {
     return this.extension.hasPermission("tabs") || this.hasActiveTabPermission(tab);
   },
 
   convert(tab) {
-    let window = tab.ownerDocument.defaultView;
+    let window = tab.ownerGlobal;
     let browser = tab.linkedBrowser;
 
     let mutedInfo = {muted: tab.muted};
     if (tab.muteReason === null) {
       mutedInfo.reason = "user";
     } else if (tab.muteReason) {
       mutedInfo.reason = "extension";
       mutedInfo.extensionId = tab.muteReason;
@@ -490,17 +490,17 @@ global.TabManager = {
     this.initListener();
 
     let id = this._nextId++;
     this._tabs.set(tab, id);
     return id;
   },
 
   getBrowserId(browser) {
-    let gBrowser = browser.ownerDocument.defaultView.gBrowser;
+    let gBrowser = browser.ownerGlobal.gBrowser;
     // Some non-browser windows have gBrowser but not
     // getTabForBrowser!
     if (gBrowser && gBrowser.getTabForBrowser) {
       let tab = gBrowser.getTabForBrowser(browser);
       if (tab) {
         return this.getId(tab);
       }
     }
--- a/browser/components/newtab/NewTabSearchProvider.jsm
+++ b/browser/components/newtab/NewTabSearchProvider.jsm
@@ -66,17 +66,17 @@ SearchProvider.prototype = {
     return ContentSearch.searchSuggestionUIStrings;
   },
 
   removeFormHistory({browser}, suggestion) {
     ContentSearch.removeFormHistoryEntry({target: browser}, suggestion);
   },
 
   manageEngines(browser) {
-    const browserWin = browser.ownerDocument.defaultView;
+    const browserWin = browser.ownerGlobal;
     browserWin.openPreferences("paneSearch");
   },
 
   asyncGetState: Task.async(function*() {
     let state = yield ContentSearch.currentStateObj(true);
     return state;
   }),
 
--- a/browser/components/nsBrowserGlue.js
+++ b/browser/components/nsBrowserGlue.js
@@ -2552,17 +2552,17 @@ ContentPermissionPrompt.prototype = {
    *                               Permission is granted if action is null or ALLOW_ACTION.
    * @param aNotificationId        The id of the PopupNotification.
    * @param aAnchorId              The id for the PopupNotification anchor.
    * @param aOptions               Options for the PopupNotification
    */
   _showPrompt: function CPP_showPrompt(aRequest, aMessage, aPermission, aActions,
                                        aNotificationId, aAnchorId, aOptions) {
     var browser = this._getBrowserForRequest(aRequest);
-    var chromeWin = browser.ownerDocument.defaultView;
+    var chromeWin = browser.ownerGlobal;
     var requestPrincipal = aRequest.principal;
 
     // Transform the prompt actions into PopupNotification actions.
     var popupNotificationActions = [];
     for (var i = 0; i < aActions.length; i++) {
       let promptAction = aActions[i];
 
       // Don't offer action in PB mode if the action remembers permission for more than a session.
@@ -2755,17 +2755,17 @@ ContentPermissionPrompt.prototype = {
       return;
     }
 
     if (result == Ci.nsIPermissionManager.ALLOW_ACTION) {
       autoAllow = true;
     }
 
     var browser = this._getBrowserForRequest(request);
-    var chromeWin = browser.ownerDocument.defaultView;
+    var chromeWin = browser.ownerGlobal;
     if (!chromeWin.PopupNotifications)
       // Ignore requests from browsers hosted in windows that don't support
       // PopupNotifications.
       return;
 
     // Show the prompt.
     switch (perm.type) {
     case "geolocation":
--- a/browser/components/places/PlacesUIUtils.jsm
+++ b/browser/components/places/PlacesUIUtils.jsm
@@ -181,17 +181,17 @@ let InternalFaviconLoader = {
     Services.obs.addObserver(this, "inner-window-destroyed", false);
     Services.ppmm.addMessageListener("Toolkit:inner-window-destroyed", msg => {
       this.removeRequestsForInner(msg.data);
     });
   },
 
   loadFavicon(browser, principal, uri) {
     this.ensureInitialized();
-    let win = browser.ownerDocument.defaultView;
+    let win = browser.ownerGlobal;
     if (!gFaviconLoadDataMap.has(win)) {
       gFaviconLoadDataMap.set(win, []);
       let unloadHandler = event => {
         let doc = event.target;
         let eventWin = doc.defaultView;
         if (eventWin == win) {
           win.removeEventListener("unload", unloadHandler);
           this.onUnload(win);
--- a/browser/components/places/content/controller.js
+++ b/browser/components/places/content/controller.js
@@ -1596,17 +1596,17 @@ var PlacesControllerDragHelper = {
 
       let data = dt.mozGetDataAt(flavor, i);
       let unwrapped;
       if (flavor != TAB_DROP_TYPE) {
         // There's only ever one in the D&D case.
         unwrapped = PlacesUtils.unwrapNodes(data, flavor)[0];
       }
       else if (data instanceof XULElement && data.localName == "tab" &&
-               data.ownerDocument.defaultView instanceof ChromeWindow) {
+               data.ownerGlobal instanceof ChromeWindow) {
         let uri = data.linkedBrowser.currentURI;
         let spec = uri ? uri.spec : "about:blank";
         let title = data.label;
         unwrapped = { uri: spec,
                       title: data.label,
                       type: PlacesUtils.TYPE_X_MOZ_URL};
       }
       else
--- a/browser/components/places/tests/browser/browser_library_middleclick.js
+++ b/browser/components/places/tests/browser/browser_library_middleclick.js
@@ -23,17 +23,17 @@ var gTabsListener = {
       return;
 
     if (++this._openTabsCount == gCurrentTest.URIs.length) {
       is(gBrowser.tabs.length, gCurrentTest.URIs.length + 1,
          "We have opened " + gCurrentTest.URIs.length + " new tab(s)");
     }
 
     var tab = aEvent.target;
-    is(tab.ownerDocument.defaultView, window,
+    is(tab.ownerGlobal, window,
        "Tab has been opened in current browser window");
   },
 
   onLocationChange: function(aBrowser, aWebProgress, aRequest, aLocationURI,
                              aFlags) {
     var spec = aLocationURI.spec;
     ok(true, spec);
     // When a new tab is opened, location is first set to "about:blank", so
@@ -57,17 +57,17 @@ var gTabsListener = {
       this._openTabsCount = 0;
 
       executeSoon(function () {
         // Close all tabs.
         while (gBrowser.tabs.length > 1)
           gBrowser.removeCurrentTab();
 
         // Test finished.  This will move to the next one.
-        waitForFocus(gCurrentTest.finish, gBrowser.ownerDocument.defaultView);
+        waitForFocus(gCurrentTest.finish, gBrowser.ownerGlobal);
       });
     }
   }
 }
 
 //------------------------------------------------------------------------------
 // Open bookmark in a new tab.
 
--- a/browser/components/places/tests/browser/head.js
+++ b/browser/components/places/tests/browser/head.js
@@ -131,17 +131,17 @@ function synthesizeClickOnSelectedTreeCe
   let rowID = min.value;
   tbo.ensureRowIsVisible(rowID);
   // Calculate the click coordinates.
   var rect = tbo.getCoordsForCellItem(rowID, aTree.columns[0], "text");
   var x = rect.x + rect.width / 2;
   var y = rect.y + rect.height / 2;
   // Simulate the click.
   EventUtils.synthesizeMouse(aTree.body, x, y, aOptions || {},
-                             aTree.ownerDocument.defaultView);
+                             aTree.ownerGlobal);
 }
 
 /**
  * Asynchronously check a url is visited.
  *
  * @param aURI The URI.
  * @return {Promise}
  * @resolves When the check has been added successfully.
--- a/browser/components/preferences/in-content/subdialogs.js
+++ b/browser/components/preferences/in-content/subdialogs.js
@@ -331,17 +331,17 @@ var gSubDialog = {
     }
 
     let forward = !aEvent.shiftKey;
     // check if focus is leaving the frame (incl. the close button):
     if ((aEvent.target == this._closeButton && !forward) ||
         (isLastFocusableElement(aEvent.originalTarget) && forward)) {
       aEvent.preventDefault();
       aEvent.stopImmediatePropagation();
-      let parentWin = this._getBrowser().ownerDocument.defaultView;
+      let parentWin = this._getBrowser().ownerGlobal;
       if (forward) {
         fm.moveFocus(parentWin, null, fm.MOVEFOCUS_FIRST, fm.FLAG_BYKEY);
       } else {
         // Somehow, moving back 'past' the opening doc is not trivial. Cheat by doing it in 2 steps:
         fm.moveFocus(window, null, fm.MOVEFOCUS_ROOT, fm.FLAG_BYKEY);
         fm.moveFocus(parentWin, null, fm.MOVEFOCUS_BACKWARD, fm.FLAG_BYKEY);
       }
     }
--- a/browser/components/preferences/in-content/tests/head.js
+++ b/browser/components/preferences/in-content/tests/head.js
@@ -1,17 +1,17 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 Components.utils.import("resource://gre/modules/Promise.jsm");
 
 const kDefaultWait = 2000;
 
 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/browser/components/safebrowsing/content/test/browser_whitelisted.js
+++ b/browser/components/safebrowsing/content/test/browser_whitelisted.js
@@ -27,15 +27,15 @@ function testWhitelistedPage(window) {
 
 add_task(function* testNormalBrowsing() {
   tabbrowser = gBrowser;
   let tab = tabbrowser.selectedTab = tabbrowser.addTab();
 
   info("Load a test page that's whitelisted");
   Services.prefs.setCharPref(PREF_WHITELISTED_HOSTNAMES, "example.com,www.ItIsaTrap.org,example.net");
   yield promiseTabLoadEvent(tab, TEST_PAGE, "load");
-  testWhitelistedPage(tab.ownerDocument.defaultView);
+  testWhitelistedPage(tab.ownerGlobal);
 
   info("Load a test page that's no longer whitelisted");
   Services.prefs.setCharPref(PREF_WHITELISTED_HOSTNAMES, "");
   yield promiseTabLoadEvent(tab, TEST_PAGE, "AboutBlockedLoaded");
-  testBlockedPage(tab.ownerDocument.defaultView);
+  testBlockedPage(tab.ownerGlobal);
 });
--- a/browser/components/search/test/browser_oneOffHeader.js
+++ b/browser/components/search/test/browser_oneOffHeader.js
@@ -44,17 +44,17 @@ function getOneOffs() {
 }
 
 const msg = isMac ? 5 : 1;
 const utils = window.QueryInterface(Ci.nsIInterfaceRequestor)
                     .getInterface(Ci.nsIDOMWindowUtils);
 const scale = utils.screenPixelsPerCSSPixel;
 function* synthesizeNativeMouseMove(aElement) {
   let rect = aElement.getBoundingClientRect();
-  let win = aElement.ownerDocument.defaultView;
+  let win = aElement.ownerGlobal;
   let x = win.mozInnerScreenX + (rect.left + rect.right) / 2;
   let y = win.mozInnerScreenY + (rect.top + rect.bottom) / 2;
 
   // Wait for the mouseup event to occur before continuing.
   return new Promise((resolve, reject) => {
     function eventOccurred(e)
     {
       aElement.removeEventListener("mouseover", eventOccurred, true);
--- a/browser/components/search/test/browser_searchbar_openpopup.js
+++ b/browser/components/search/test/browser_searchbar_openpopup.js
@@ -19,17 +19,17 @@ const isWindows = Services.appinfo.OS ==
 const mouseDown = isWindows ? 2 : 1;
 const mouseUp = isWindows ? 4 : 2;
 const utils = window.QueryInterface(Ci.nsIInterfaceRequestor)
                     .getInterface(Ci.nsIDOMWindowUtils);
 const scale = utils.screenPixelsPerCSSPixel;
 
 function* synthesizeNativeMouseClick(aElement) {
   let rect = aElement.getBoundingClientRect();
-  let win = aElement.ownerDocument.defaultView;
+  let win = aElement.ownerGlobal;
   let x = win.mozInnerScreenX + (rect.left + rect.right) / 2;
   let y = win.mozInnerScreenY + (rect.top + rect.bottom) / 2;
 
   // Wait for the mouseup event to occur before continuing.
   return new Promise((resolve, reject) => {
     function eventOccurred(e)
     {
       aElement.removeEventListener("mouseup", eventOccurred, true);
--- a/browser/components/sessionstore/SessionStore.jsm
+++ b/browser/components/sessionstore/SessionStore.jsm
@@ -672,17 +672,17 @@ var SessionStoreInternal = {
    * This method handles incoming messages sent by the session store content
    * script via the Frame Message Manager or Parent Process Message Manager,
    * and thus enables communication with OOP tabs.
    */
   receiveMessage(aMessage) {
     // If we got here, that means we're dealing with a frame message
     // manager message, so the target will be a <xul:browser>.
     var browser = aMessage.target;
-    let win = browser.ownerDocument.defaultView;
+    let win = browser.ownerGlobal;
     let tab = win ? win.gBrowser.getTabForBrowser(browser) : null;
 
     // Ensure we receive only specific messages from <xul:browser>s that
     // have no tab or window assigned, e.g. the ones that preload
     // about:newtab pages, or windows that have closed.
     if (!tab && !NOTAB_MESSAGES.has(aMessage.name)) {
       throw new Error(`received unexpected message '${aMessage.name}' ` +
                       `from a browser that has no tab or window`);
@@ -885,17 +885,17 @@ var SessionStoreInternal = {
   },
 
   /* ........ Window Event Handlers .............. */
 
   /**
    * Implement nsIDOMEventListener for handling various window and tab events
    */
   handleEvent: function ssi_handleEvent(aEvent) {
-    let win = aEvent.currentTarget.ownerDocument.defaultView;
+    let win = aEvent.currentTarget.ownerGlobal;
     let target = aEvent.originalTarget;
     switch (aEvent.type) {
       case "TabOpen":
         this.onTabAdd(win);
         break;
       case "TabBrowserCreated":
         this.onTabBrowserCreated(win, target);
         break;
@@ -2046,17 +2046,17 @@ var SessionStoreInternal = {
     if (!aWindow.__SSi) {
       throw Components.Exception("Window is not tracked", Cr.NS_ERROR_INVALID_ARG);
     }
 
     this.restoreWindows(aWindow, aState, {overwriteTabs: aOverwrite});
   },
 
   getTabState: function ssi_getTabState(aTab) {
-    if (!aTab.ownerDocument.defaultView.__SSi) {
+    if (!aTab.ownerGlobal.__SSi) {
       throw Components.Exception("Default view is not tracked", Cr.NS_ERROR_INVALID_ARG);
     }
 
     let tabState = TabState.collect(aTab);
 
     return JSON.stringify(tabState);
   },
 
@@ -2071,30 +2071,30 @@ var SessionStoreInternal = {
     }
     if (typeof tabState != "object") {
       throw Components.Exception("Not an object", Cr.NS_ERROR_INVALID_ARG);
     }
     if (!("entries" in tabState)) {
       throw Components.Exception("Invalid state object: no entries", Cr.NS_ERROR_INVALID_ARG);
     }
 
-    let window = aTab.ownerDocument.defaultView;
+    let window = aTab.ownerGlobal;
     if (!("__SSi" in window)) {
       throw Components.Exception("Window is not tracked", Cr.NS_ERROR_INVALID_ARG);
     }
 
     if (aTab.linkedBrowser.__SS_restoreState) {
       this._resetTabRestoringState(aTab);
     }
 
     this.restoreTab(aTab, tabState);
   },
 
   duplicateTab: function ssi_duplicateTab(aWindow, aTab, aDelta = 0) {
-    if (!aTab.ownerDocument.defaultView.__SSi) {
+    if (!aTab.ownerGlobal.__SSi) {
       throw Components.Exception("Default view is not tracked", Cr.NS_ERROR_INVALID_ARG);
     }
     if (!aWindow.gBrowser) {
       throw Components.Exception("Invalid window object: no gBrowser", Cr.NS_ERROR_INVALID_ARG);
     }
 
     // Create a new tab.
     let userContextId = aTab.getAttribute("usercontextid");
@@ -2113,17 +2113,17 @@ var SessionStoreInternal = {
     // Flush to get the latest tab state to duplicate.
     let browser = aTab.linkedBrowser;
     TabStateFlusher.flush(browser).then(() => {
       // The new tab might have been closed in the meantime.
       if (newTab.closing || !newTab.linkedBrowser) {
         return;
       }
 
-      let window = newTab.ownerDocument && newTab.ownerDocument.defaultView;
+      let window = newTab.ownerGlobal;
 
       // The tab or its window might be gone.
       if (!window || !window.__SSi) {
         return;
       }
 
       // Update state with flushed data. We can't use TabState.clone() here as
       // the tab to duplicate may have already been closed. In that case we
@@ -2300,23 +2300,23 @@ var SessionStoreInternal = {
 
     // If the tab hasn't been restored, then set the data there, otherwise we
     // could lose newly added data.
     if (!aTab.__SS_extdata) {
       aTab.__SS_extdata = {};
     }
 
     aTab.__SS_extdata[aKey] = aStringValue;
-    this.saveStateDelayed(aTab.ownerDocument.defaultView);
+    this.saveStateDelayed(aTab.ownerGlobal);
   },
 
   deleteTabValue: function ssi_deleteTabValue(aTab, aKey) {
     if (aTab.__SS_extdata && aKey in aTab.__SS_extdata) {
       delete aTab.__SS_extdata[aKey];
-      this.saveStateDelayed(aTab.ownerDocument.defaultView);
+      this.saveStateDelayed(aTab.ownerGlobal);
     }
   },
 
   getGlobalValue: function ssi_getGlobalValue(aKey) {
     return this._globalState.get(aKey);
   },
 
   setGlobalValue: function ssi_setGlobalValue(aKey, aStringValue) {
@@ -2504,17 +2504,17 @@ var SessionStoreInternal = {
    * loaded in the parent and pages loaded in the child process.
    *
    * This method might be called multiple times before it has finished
    * flushing the browser tab. If that occurs, the loadArguments from
    * the most recent call to navigateAndRestore will be used once the
    * flush has finished.
    */
   navigateAndRestore(tab, loadArguments, historyIndex) {
-    let window = tab.ownerDocument.defaultView;
+    let window = tab.ownerGlobal;
     NS_ASSERT(window.__SSi, "tab's window must be tracked");
     let browser = tab.linkedBrowser;
 
     // Were we already waiting for a flush from a previous call to
     // navigateAndRestore on this tab?
     let alreadyRestoring =
       this._remotenessChangingBrowsers.has(browser.permanentKey);
 
@@ -2542,17 +2542,17 @@ var SessionStoreInternal = {
         this._remotenessChangingBrowsers.get(browser.permanentKey);
       this._remotenessChangingBrowsers.delete(browser.permanentKey);
 
       // The tab might have been closed/gone in the meantime.
       if (tab.closing || !tab.linkedBrowser) {
         return;
       }
 
-      let window = tab.ownerDocument && tab.ownerDocument.defaultView;
+      let window = tab.ownerGlobal;
 
       // The tab or its window might be gone.
       if (!window || !window.__SSi || window.closed) {
         return;
       }
 
       let tabState = TabState.clone(tab);
       let options = {restoreImmediately: true};
@@ -3205,17 +3205,17 @@ var SessionStoreInternal = {
   // Restores the given tab state for a given tab.
   restoreTab(tab, tabData, options = {}) {
     NS_ASSERT(!tab.linkedBrowser.__SS_restoreState,
               "must reset tab before calling restoreTab()");
 
     let restoreImmediately = options.restoreImmediately;
     let loadArguments = options.loadArguments;
     let browser = tab.linkedBrowser;
-    let window = tab.ownerDocument.defaultView;
+    let window = tab.ownerGlobal;
     let tabbrowser = window.gBrowser;
     let forceOnDemand = options.forceOnDemand;
 
     // Increase the busy state counter before modifying the tab.
     this._setWindowStateBusy(window);
 
     // It's important to set the window state to dirty so that
     // we collect their data for the first time when saving state.
@@ -3345,17 +3345,17 @@ var SessionStoreInternal = {
    *        its remoteness (out-of-process) state.
    */
   restoreTabContent: function (aTab, aLoadArguments = null) {
     if (aTab.hasAttribute("customizemode")) {
       return;
     }
 
     let browser = aTab.linkedBrowser;
-    let window = aTab.ownerDocument.defaultView;
+    let window = aTab.ownerGlobal;
     let tabbrowser = window.gBrowser;
     let tabData = TabState.clone(aTab);
     let activeIndex = tabData.index - 1;
     let activePageData = tabData.entries[activeIndex] || null;
     let uri = activePageData ? activePageData.url || null : null;
     if (aLoadArguments) {
       uri = aLoadArguments.uri;
     }
@@ -4140,17 +4140,17 @@ var SessionStoreInternal = {
    *
    * @param aTab
    *        The tab that will be "reset"
    */
   _resetLocalTabRestoringState: function (aTab) {
     NS_ASSERT(aTab.linkedBrowser.__SS_restoreState,
               "given tab is not restoring");
 
-    let window = aTab.ownerDocument.defaultView;
+    let window = aTab.ownerGlobal;
     let browser = aTab.linkedBrowser;
 
     // Keep the tab's previous state for later in this method
     let previousState = browser.__SS_restoreState;
 
     // The browser is no longer in any sort of restoring state.
     delete browser.__SS_restoreState;
 
--- a/browser/components/sessionstore/TabState.jsm
+++ b/browser/components/sessionstore/TabState.jsm
@@ -113,17 +113,17 @@ var TabStateInternal = {
 
     // After copyFromCache() was called we check for properties that are kept
     // in the cache only while the tab is pending or restoring. Once that
     // happened those properties will be removed from the cache and will
     // be read from the tab/browser every time we collect data.
 
     // Store the tab icon.
     if (!("image" in tabData)) {
-      let tabbrowser = tab.ownerDocument.defaultView.gBrowser;
+      let tabbrowser = tab.ownerGlobal.gBrowser;
       tabData.image = tabbrowser.getIcon(tab);
     }
 
     // If there is a userTypedValue set, then either the user has typed something
     // in the URL bar, or a new tab was opened with a URI to load.
     // If so, we also track whether we were still in the process of loading something.
     if (!("userTypedValue" in tabData) && browser.userTypedValue) {
       tabData.userTypedValue = browser.userTypedValue;
--- a/browser/components/sessionstore/content/content-sessionStore.js
+++ b/browser/components/sessionstore/content/content-sessionStore.js
@@ -413,18 +413,17 @@ var FormDataListener = {
   init: function () {
     addEventListener("input", this, true);
     addEventListener("change", this, true);
     gFrameTree.addObserver(this);
   },
 
   handleEvent: function (event) {
     let frame = event.target &&
-                event.target.ownerDocument &&
-                event.target.ownerDocument.defaultView;
+                event.target.ownerGlobal;
 
     // Don't collect form data for frames created at or after the load event
     // as SessionStore can't restore form data for those.
     if (frame && gFrameTree.contains(frame)) {
       MessageQueue.push("formdata", () => this.collect());
     }
   },
 
--- a/browser/components/sessionstore/test/browser_463206.js
+++ b/browser/components/sessionstore/test/browser_463206.js
@@ -13,17 +13,17 @@ add_task(function* () {
   yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
 
   // "Type in" some random values.
   yield ContentTask.spawn(tab.linkedBrowser, null, function* () {
     function typeText(aTextField, aValue) {
       aTextField.value = aValue;
 
       let event = aTextField.ownerDocument.createEvent("UIEvents");
-      event.initUIEvent("input", true, true, aTextField.ownerDocument.defaultView, 0);
+      event.initUIEvent("input", true, true, aTextField.ownerGlobal, 0);
       aTextField.dispatchEvent(event);
     }
 
     typeText(content.document.getElementById("out1"), Date.now());
     typeText(content.document.getElementsByName("1|#out2")[0], Math.random());
     typeText(content.frames[0].frames[1].document.getElementById("in1"), new Date());
   });
 
--- a/browser/components/sessionstore/test/browser_sessionStoreContainer.js
+++ b/browser/components/sessionstore/test/browser_sessionStoreContainer.js
@@ -72,17 +72,17 @@ add_task(function* () {
 // Opens "uri" in a new tab with the provided userContextId and focuses it.
 // Returns the newly opened tab.
 function* openTabInUserContext(userContextId) {
   // Open the tab in the correct userContextId.
   let tab = gBrowser.addTab("http://example.com", { 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 waitForNewCookie() {
   return new Promise(resolve => {
--- a/browser/components/sessionstore/test/content-forms.js
+++ b/browser/components/sessionstore/test/content-forms.js
@@ -33,17 +33,17 @@ function queryElement(data) {
     return doc.evaluate(data.xpath, doc, null, xptype, null).singleNodeValue;
   }
 
   throw new Error("couldn't query element");
 }
 
 function dispatchUIEvent(input, type) {
   let event = input.ownerDocument.createEvent("UIEvents");
-  event.initUIEvent(type, true, true, input.ownerDocument.defaultView, 0);
+  event.initUIEvent(type, true, true, input.ownerGlobal, 0);
   input.dispatchEvent(event);
 }
 
 function defineListener(type, cb) {
   addMessageListener("ss-test:" + type, function ({data}) {
     sendAsyncMessage("ss-test:" + type, cb(data));
   });
 }
--- a/browser/components/syncedtabs/test/browser/browser_sidebar_syncedtabslist.js
+++ b/browser/components/syncedtabs/test/browser/browser_sidebar_syncedtabslist.js
@@ -363,17 +363,17 @@ function checkItem(node, item) {
 
 function* testContextMenu(syncedTabsDeckComponent, contextSelector, triggerSelector, menuSelectors) {
   let contextMenu = document.querySelector(contextSelector);
   let triggerElement = syncedTabsDeckComponent._window.document.querySelector(triggerSelector);
   let isClosed = triggerElement.classList.contains("closed");
 
   let promisePopupShown = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
 
-  let chromeWindow = triggerElement.ownerDocument.defaultView.top;
+  let chromeWindow = triggerElement.ownerGlobal.top;
   let rect = triggerElement.getBoundingClientRect();
   let contentRect = chromeWindow.SidebarUI.browser.getBoundingClientRect();
   // The offsets in `rect` are relative to the content window, but
   // `synthesizeMouseAtPoint` calls `nsIDOMWindowUtils.sendMouseEvent`,
   // which interprets the offsets relative to the containing *chrome* window.
   // This means we need to account for the width and height of any elements
   // outside the `browser` element, like `sidebarheader`.
   let offsetX = contentRect.x + rect.x + (rect.width / 2);
--- a/browser/components/uitour/UITour.jsm
+++ b/browser/components/uitour/UITour.jsm
@@ -359,17 +359,17 @@ this.UITour = {
     let originalUrl = ReaderMode.getOriginalUrl(aLocation);
     if (this._readerViewTriggerRegEx.test(originalUrl)) {
       this.startSubTour("readinglist");
     }
   },
 
   onPageEvent: function(aMessage, aEvent) {
     let browser = aMessage.target;
-    let window = browser.ownerDocument.defaultView;
+    let window = browser.ownerGlobal;
 
     // Does the window have tabs? We need to make sure since windowless browsers do
     // not have tabs.
     if (!window.gBrowser) {
       // When using windowless browsers we don't have a valid |window|. If that's the case,
       // use the most recent window as a target for UITour functions (see Bug 1111022).
       window = Services.wm.getMostRecentWindow("navigator:browser");
     }
@@ -716,17 +716,17 @@ this.UITour = {
         break;
       }
 
       case "closeTab": {
         // Find the <tabbrowser> element of the <browser> for which the event
         // was generated originally. If the browser where the UI tour is loaded
         // is windowless, just ignore the request to close the tab. The request
         // is also ignored if this is the only tab in the window.
-        let tabBrowser = browser.ownerDocument.defaultView.gBrowser;
+        let tabBrowser = browser.ownerGlobal.gBrowser;
         if (tabBrowser && tabBrowser.browsers.length > 1) {
           tabBrowser.removeTab(tabBrowser.getTabForBrowser(browser));
         }
         break;
       }
     }
 
     this.initForBrowser(browser, window);
@@ -750,17 +750,17 @@ this.UITour = {
 
     window.addEventListener("SSWindowClosing", this);
   },
 
   handleEvent: function(aEvent) {
     log.debug("handleEvent: type =", aEvent.type, "event =", aEvent);
     switch (aEvent.type) {
       case "TabSelect": {
-        let window = aEvent.target.ownerDocument.defaultView;
+        let window = aEvent.target.ownerGlobal;
 
         // Teardown the browser of the tab we just switched away from.
         if (aEvent.detail && aEvent.detail.previousTab) {
           let previousTab = aEvent.detail.previousTab;
           let openTourWindows = this.tourBrowsersByWindow.get(window);
           if (openTourWindows.has(previousTab.linkedBrowser)) {
             this.teardownTourForBrowser(window, previousTab.linkedBrowser, false);
           }
@@ -967,17 +967,17 @@ this.UITour = {
 
   sendPageCallback: function(aMessageManager, aCallbackID, aData = {}) {
     let detail = {data: aData, callbackID: aCallbackID};
     log.debug("sendPageCallback", detail);
     aMessageManager.sendAsyncMessage("UITour:SendPageCallback", detail);
   },
 
   isElementVisible: function(aElement) {
-    let targetStyle = aElement.ownerDocument.defaultView.getComputedStyle(aElement);
+    let targetStyle = aElement.ownerGlobal.getComputedStyle(aElement);
     return !aElement.ownerDocument.hidden &&
              targetStyle.display != "none" &&
              targetStyle.visibility == "visible";
   },
 
   getTarget: function(aWindow, aTargetName, aSticky = false) {
     log.debug("getTarget:", aTargetName);
     let deferred = Promise.defer();
@@ -1820,17 +1820,17 @@ this.UITour = {
       panel.hidePopup();
     } else if (aMenuName == "loop") {
       let panel = aWindow.document.getElementById("loop-notification-panel");
       panel.hidePopup();
     }
   },
 
   hideAnnotationsForPanel: function(aEvent, aTargetPositionCallback) {
-    let win = aEvent.target.ownerDocument.defaultView;
+    let win = aEvent.target.ownerGlobal;
     let annotationElements = new Map([
       // [annotationElement (panel), method to hide the annotation]
       [win.document.getElementById("UITourHighlightContainer"), UITour.hideHighlight.bind(UITour)],
       [win.document.getElementById("UITourTooltip"), UITour.hideInfo.bind(UITour)],
     ]);
     annotationElements.forEach((hideMethod, annotationElement) => {
       if (annotationElement.state != "closed") {
         let targetName = annotationElement.getAttribute("targetName");
@@ -2058,17 +2058,17 @@ this.UITour = {
   },
 
   _addAnnotationPanelMutationObserver: function(aPanelEl) {
     if (AppConstants.platform == "linux") {
       let observer = this._annotationPanelMutationObservers.get(aPanelEl);
       if (observer) {
         return;
       }
-      let win = aPanelEl.ownerDocument.defaultView;
+      let win = aPanelEl.ownerGlobal;
       observer = new win.MutationObserver(this._annotationMutationCallback);
       this._annotationPanelMutationObservers.set(aPanelEl, observer);
       let observerOptions = {
         attributeFilter: ["height", "width"],
         attributes: true,
       };
       observer.observe(aPanelEl, observerOptions);
     }
--- a/browser/components/uitour/test/head.js
+++ b/browser/components/uitour/test/head.js
@@ -49,33 +49,33 @@ function taskify(fun) {
     return Task.spawn(fun).then(done, (reason) => {
       ok(false, reason);
       done();
     });
   };
 }
 
 function is_hidden(element) {
-  var style = element.ownerDocument.defaultView.getComputedStyle(element, "");
+  var style = element.ownerGlobal.getComputedStyle(element);
   if (style.display == "none")
     return true;
   if (style.visibility != "visible")
     return true;
   if (style.display == "-moz-popup")
     return ["hiding","closed"].indexOf(element.state) != -1;
 
   // Hiding a parent element will hide all its children
   if (element.parentNode != element.ownerDocument)
     return is_hidden(element.parentNode);
 
   return false;
 }
 
 function is_visible(element) {
-  var style = element.ownerDocument.defaultView.getComputedStyle(element, "");
+  var style = element.ownerGlobal.getComputedStyle(element);
   if (style.display == "none")
     return false;
   if (style.visibility != "visible")
     return false;
   if (style.display == "-moz-popup" && element.state != "open")
     return false;
 
   // Hiding a parent element will hide all its children
@@ -218,17 +218,17 @@ function promisePanelElementHidden(win, 
 }
 
 function is_element_hidden(element, msg) {
   isnot(element, null, "Element should not be null, when checking visibility");
   ok(is_hidden(element), msg);
 }
 
 function isTourBrowser(aBrowser) {
-  let chromeWindow = aBrowser.ownerDocument.defaultView;
+  let chromeWindow = aBrowser.ownerGlobal;
   return UITour.tourBrowsersByWindow.has(chromeWindow) &&
          UITour.tourBrowsersByWindow.get(chromeWindow).has(aBrowser);
 }
 
 function promisePageEvent() {
   return new Promise((resolve) => {
     Services.mm.addMessageListener("UITour:onPageEvent", function onPageEvent(aMessage) {
       Services.mm.removeMessageListener("UITour:onPageEvent", onPageEvent);
--- a/browser/extensions/pocket/content/Pocket.jsm
+++ b/browser/extensions/pocket/content/Pocket.jsm
@@ -60,17 +60,17 @@ var Pocket = {
     let window = document.defaultView;
     let iframe = window.pktUI.getPanelFrame();
 
     iframe.removeEventListener("load", Pocket.onFrameLoaded, true);
     window.pktUI.pocketPanelDidShow();
   },
 
   onPanelViewHiding(event) {
-    let window = event.target.ownerDocument.defaultView;
+    let window = event.target.ownerGlobal;
     window.pktUI.pocketPanelDidHide(event);
   },
 
   _urlToSave: null,
   _titleToSave: null,
   savePage(browser, url, title) {
     let document = browser.ownerDocument;
     let pocketWidget = document.getElementById("pocket-button");
--- a/browser/modules/AboutHome.jsm
+++ b/browser/modules/AboutHome.jsm
@@ -105,17 +105,17 @@ var AboutHome = {
     let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager);
 
     for (let msg of this.MESSAGES) {
       mm.addMessageListener(msg, this);
     }
   },
 
   receiveMessage: function(aMessage) {
-    let window = aMessage.target.ownerDocument.defaultView;
+    let window = aMessage.target.ownerGlobal;
 
     switch (aMessage.name) {
       case "AboutHome:RestorePreviousSession":
         let ss = Cc["@mozilla.org/browser/sessionstore;1"].
                  getService(Ci.nsISessionStore);
         if (ss.canRestoreLastSession) {
           ss.restoreLastSession();
         }
--- a/browser/modules/CaptivePortalWatcher.jsm
+++ b/browser/modules/CaptivePortalWatcher.jsm
@@ -160,17 +160,17 @@ this.CaptivePortalWatcher = {
     this._captivePortalTab = null;
 
     // Check parentNode in case the object hasn't been gc'd yet.
     if (!tab || tab.closing || !tab.parentNode) {
       // User has closed the tab already.
       return;
     }
 
-    let tabbrowser = tab.ownerDocument.defaultView.gBrowser;
+    let tabbrowser = tab.ownerGlobal.gBrowser;
 
     // If after the login, the captive portal has redirected to some other page,
     // leave it open if the tab has focus.
     if (tab.linkedBrowser.currentURI.spec != this.canonicalURL &&
         tabbrowser.selectedTab == tab) {
       return;
     }
 
--- a/browser/modules/CastingApps.jsm
+++ b/browser/modules/CastingApps.jsm
@@ -74,17 +74,17 @@ var CastingApps = {
       return;
     }
 
     // Make sure we have a player app for the given service
     let app = SimpleServiceDiscovery.findAppForService(service);
     if (!app)
       return;
 
-    video.title = videoElement.ownerDocument.defaultView.top.document.title;
+    video.title = videoElement.ownerGlobal.top.document.title;
     if (video.element) {
       // If the video is currently playing on the device, pause it
       if (!video.element.paused) {
         video.element.pause();
       }
     }
 
     app.stop(() => {
--- a/browser/modules/ContentClick.jsm
+++ b/browser/modules/ContentClick.jsm
@@ -27,17 +27,17 @@ var ContentClick = {
         this.contentAreaClick(message.json, message.target)
         break;
     }
   },
 
   contentAreaClick: function (json, browser) {
     // This is heavily based on contentAreaClick from browser.js (Bug 903016)
     // The json is set up in a way to look like an Event.
-    let window = browser.ownerDocument.defaultView;
+    let window = browser.ownerGlobal;
 
     if (!json.href) {
       // Might be middle mouse navigation.
       if (Services.prefs.getBoolPref("middlemouse.contentLoadURL") &&
           !Services.prefs.getBoolPref("general.autoScroll")) {
         window.middleMousePaste(json);
       }
       return;
--- a/browser/modules/ContentCrashHandlers.jsm
+++ b/browser/modules/ContentCrashHandlers.jsm
@@ -74,17 +74,17 @@ this.TabCrashHandler = {
 
         this.browserMap.set(browser.permanentKey, aSubject.childID);
         break;
     }
   },
 
   receiveMessage: function(message) {
     let browser = message.target.browser;
-    let gBrowser = browser.ownerDocument.defaultView.gBrowser;
+    let gBrowser = browser.ownerGlobal.gBrowser;
     let tab = gBrowser.getTabForBrowser(browser);
 
     switch(message.name) {
       case "Load": {
         this.onAboutTabCrashedLoad(message);
         break;
       }
 
--- a/browser/modules/ContentLinkHandler.jsm
+++ b/browser/modules/ContentLinkHandler.jsm
@@ -38,17 +38,17 @@ this.ContentLinkHandler = {
 
   onLinkEvent: function(event, chromeGlobal) {
     var link = event.originalTarget;
     var rel = link.rel && link.rel.toLowerCase();
     if (!link || !link.ownerDocument || !rel || !link.href)
       return;
 
     // Ignore sub-frames (bugs 305472, 479408).
-    let window = link.ownerDocument.defaultView;
+    let window = link.ownerGlobal;
     if (window != window.top)
       return;
 
     var feedAdded = false;
     var iconAdded = false;
     var searchAdded = false;
     var rels = {};
     for (let relString of rel.split(/\s+/))
--- a/browser/modules/ContentSearch.jsm
+++ b/browser/modules/ContentSearch.jsm
@@ -225,27 +225,22 @@ this.ContentSearch = {
       "engineName",
       "searchString",
       "healthReportKey",
       "searchPurpose",
     ]);
     let engine = Services.search.getEngineByName(data.engineName);
     let submission = engine.getSubmission(data.searchString, "", data.searchPurpose);
     let browser = msg.target;
-    let win;
-    try {
-      win = browser.ownerDocument.defaultView;
-    }
-    catch (err) {
+    let win = browser.ownerGlobal;
+    if (!win) {
       // The browser may have been closed between the time its content sent the
-      // message and the time we handle it.  In that case, trying to call any
-      // method on it will throw.
+      // message and the time we handle it.
       return;
     }
-
     let where = win.whereToOpenLink(data.originalEvent);
 
     // There is a chance that by the time we receive the search message, the user
     // has switched away from the tab that triggered the search. If, based on the
     // event, we need to load the search in the same tab that triggered it (i.e.
     // where === "current"), openUILinkIn will not work because that tab is no
     // longer the current one. For this case we manually load the URI.
     if (where === "current") {
@@ -419,17 +414,17 @@ this.ContentSearch = {
     this.performSearch(msg, data);
   },
 
   _onMessageSetCurrentEngine: function (msg, data) {
     Services.search.currentEngine = Services.search.getEngineByName(data);
   },
 
   _onMessageManageEngines: function (msg, data) {
-    let browserWin = msg.target.ownerDocument.defaultView;
+    let browserWin = msg.target.ownerGlobal;
     browserWin.openPreferences("paneSearch");
   },
 
   _onMessageGetSuggestions: Task.async(function* (msg, data) {
     this._ensureDataHasProperties(data, [
       "engineName",
       "searchString",
     ]);
--- a/browser/modules/FormSubmitObserver.jsm
+++ b/browser/modules/FormSubmitObserver.jsm
@@ -102,17 +102,17 @@ FormSubmitObserver.prototype =
     // panel attached to the element.
     if (!aInvalidElements.length) {
       return;
     }
 
     // Insure that this is the FormSubmitObserver associated with the
     // element / window this notification is about.
     let element = aInvalidElements.queryElementAt(0, Ci.nsISupports);
-    if (this._content != element.ownerDocument.defaultView.top.document.defaultView) {
+    if (this._content != element.ownerGlobal.top.document.defaultView) {
       return;
     }
 
     if (!(element instanceof HTMLInputElement ||
           element instanceof HTMLTextAreaElement ||
           element instanceof HTMLSelectElement ||
           element instanceof HTMLButtonElement)) {
       return;
@@ -196,17 +196,17 @@ FormSubmitObserver.prototype =
     // and where the content begin for the other elements.
     let offset = 0;
     let position = "";
 
     if (aElement.tagName == 'INPUT' &&
         (aElement.type == 'radio' || aElement.type == 'checkbox')) {
       panelData.position = "bottomcenter topleft";
     } else {
-      let win = aElement.ownerDocument.defaultView;
+      let win = aElement.ownerGlobal;
       let style = win.getComputedStyle(aElement, null);
       if (style.direction == 'rtl') {
         offset = parseInt(style.paddingRight) + parseInt(style.borderRightWidth);
       } else {
         offset = parseInt(style.paddingLeft) + parseInt(style.borderLeftWidth);
       }
       let zoomFactor = this._getWindowUtils().fullZoom;
       panelData.offset = Math.round(offset * zoomFactor);
--- a/browser/modules/FormValidationHandler.jsm
+++ b/browser/modules/FormValidationHandler.jsm
@@ -43,17 +43,17 @@ var FormValidationHandler =
     this._hidePopup();
   },
 
   /*
    * Events
    */
 
   receiveMessage: function (aMessage) {
-    let window = aMessage.target.ownerDocument.defaultView;
+    let window = aMessage.target.ownerGlobal;
     let json = aMessage.json;
     let tabBrowser = window.gBrowser;
     switch (aMessage.name) {
       case "FormValidation:ShowPopup":
         // target is the <browser>, make sure we're receiving a message
         // from the foreground tab.
         if (tabBrowser && aMessage.target != tabBrowser.selectedBrowser) {
           return;
--- a/browser/modules/NetworkPrioritizer.jsm
+++ b/browser/modules/NetworkPrioritizer.jsm
@@ -69,22 +69,22 @@ function _handleEvent(aEvent) {
 
 
 // Methods that impact a browser. Put into single object for organization.
 var BrowserHelper = {
   onOpen: function NP_BH_onOpen(aBrowser) {
     _priorityBackup.set(aBrowser.permanentKey, Ci.nsISupportsPriority.PRIORITY_NORMAL);
 
     // If the tab is in the focused window, leave priority as it is
-    if (aBrowser.ownerDocument.defaultView != _lastFocusedWindow)
+    if (aBrowser.ownerGlobal != _lastFocusedWindow)
       this.decreasePriority(aBrowser);
   },
 
   onSelect: function NP_BH_onSelect(aBrowser) {
-    let windowEntry = WindowHelper.getEntry(aBrowser.ownerDocument.defaultView);
+    let windowEntry = WindowHelper.getEntry(aBrowser.ownerGlobal);
     if (windowEntry.lastSelectedBrowser)
       this.decreasePriority(windowEntry.lastSelectedBrowser);
     this.increasePriority(aBrowser);
 
     windowEntry.lastSelectedBrowser = aBrowser;
   },
 
   onRemotenessChange: function (aBrowser) {
--- a/browser/modules/PluginContent.jsm
+++ b/browser/modules/PluginContent.jsm
@@ -242,17 +242,17 @@ PluginContent.prototype = {
                    [right, top],
                    [right, bottom],
                    [centerX, centerY]];
 
     if (right <= 0 || top <= 0) {
       return false;
     }
 
-    let contentWindow = plugin.ownerDocument.defaultView;
+    let contentWindow = plugin.ownerGlobal;
     let cwu = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor)
                            .getInterface(Ci.nsIDOMWindowUtils);
 
     for (let [x, y] of points) {
       let el = cwu.elementFromPoint(x, y, true, true);
       if (el !== plugin) {
         return false;
       }
@@ -521,17 +521,17 @@ PluginContent.prototype = {
     // if this isn't a known plugin, we can't activate it
     // (this also guards pluginHost.getPermissionStringForType against
     // unexpected input)
     if (!this.isKnownPlugin(objLoadingContent))
       return false;
 
     let pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost);
     let permissionString = pluginHost.getPermissionStringForType(objLoadingContent.actualType);
-    let principal = objLoadingContent.ownerDocument.defaultView.top.document.nodePrincipal;
+    let principal = objLoadingContent.ownerGlobal.top.document.nodePrincipal;
     let pluginPermission = Services.perms.testPermissionFromPrincipal(principal, permissionString);
 
     let isFallbackTypeValid =
       objLoadingContent.pluginFallbackType >= Ci.nsIObjectLoadingContent.PLUGIN_CLICK_TO_PLAY &&
       objLoadingContent.pluginFallbackType <= Ci.nsIObjectLoadingContent.PLUGIN_VULNERABLE_NO_UPDATE;
 
     return !objLoadingContent.activated &&
            pluginPermission != Ci.nsIPermissionManager.DENY_ACTION &&
@@ -607,17 +607,17 @@ PluginContent.prototype = {
     if (overlay) {
       overlay.addEventListener("click", this, true);
     }
   },
 
   onOverlayClick: function (event) {
     let document = event.target.ownerDocument;
     let plugin = document.getBindingParent(event.target);
-    let contentWindow = plugin.ownerDocument.defaultView.top;
+    let contentWindow = plugin.ownerGlobal.top;
     let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
     let overlay = this.getPluginUI(plugin, "main");
     // Have to check that the target is not the link to update the plugin
     if (!(event.originalTarget instanceof contentWindow.HTMLAnchorElement) &&
         (event.originalTarget.getAttribute('anonid') != 'closeIcon') &&
         !overlay.hasAttribute('dismissed') &&
         event.button == 0 &&
         event.isTrusted) {
--- a/browser/modules/ProcessHangMonitor.jsm
+++ b/browser/modules/ProcessHangMonitor.jsm
@@ -342,17 +342,17 @@ var ProcessHangMonitor = {
   },
 
   untrackWindow: function(win) {
     win.gBrowser.tabContainer.removeEventListener("TabSelect", this, true);
     win.gBrowser.tabContainer.removeEventListener("TabRemotenessChange", this, true);
   },
 
   handleEvent: function(event) {
-    let win = event.target.ownerDocument.defaultView;
+    let win = event.target.ownerGlobal;
 
     // If a new tab is selected or if a tab changes remoteness, then
     // we may need to show or hide a hang notification.
 
     if (event.type == "TabSelect" || event.type == "TabRemotenessChange") {
       this.updateWindow(win);
     }
   },
--- a/browser/modules/ReaderParent.jsm
+++ b/browser/modules/ReaderParent.jsm
@@ -76,17 +76,17 @@ var ReaderParent = {
         }
         this.updateReaderButton(browser);
         break;
       }
     }
   },
 
   updateReaderButton: function(browser) {
-    let win = browser.ownerDocument.defaultView;
+    let win = browser.ownerGlobal;
     if (browser != win.gBrowser.selectedBrowser) {
       return;
     }
 
     let button = win.document.getElementById("reader-mode-button");
     let command = win.document.getElementById("View:ReaderView");
     if (browser.currentURI.spec.startsWith("about:reader")) {
       button.setAttribute("readeractive", true);
@@ -129,28 +129,28 @@ var ReaderParent = {
   buttonClick(event) {
     if (event.button != 0) {
       return;
     }
     this.toggleReaderMode(event);
   },
 
   toggleReaderMode: function(event) {
-    let win = event.target.ownerDocument.defaultView;
+    let win = event.target.ownerGlobal;
     let browser = win.gBrowser.selectedBrowser;
     browser.messageManager.sendAsyncMessage("Reader:ToggleReaderMode");
   },
 
   /**
    * Shows an info panel from the UITour for Reader Mode.
    *
    * @param browser The <browser> that the tour should be started for.
    */
   showReaderModeInfoPanel(browser) {
-    let win = browser.ownerDocument.defaultView;
+    let win = browser.ownerGlobal;
     let targetPromise = UITour.getTarget(win, "readerMode-urlBar");
     targetPromise.then(target => {
       let browserBundle = Services.strings.createBundle("chrome://browser/locale/browser.properties");
       let icon = "chrome://browser/skin/";
       if (win.devicePixelRatio > 1) {
         icon += "reader-tour@2x.png";
       } else {
         icon += "reader-tour.png";
--- a/browser/modules/RemotePrompt.jsm
+++ b/browser/modules/RemotePrompt.jsm
@@ -30,17 +30,17 @@ var RemotePrompt = {
         } else {
           this.openTabPrompt(message.data, message.target)
         }
         break;
     }
   },
 
   openTabPrompt: function(args, browser) {
-    let window = browser.ownerDocument.defaultView;
+    let window = browser.ownerGlobal;
     let tabPrompt = window.gBrowser.getTabModalPromptBox(browser)
     let callbackInvoked = false;
     let newPrompt;
     let needRemove = false;
     let promptId = args._remoteId;
 
     function onPromptClose(forceCleanup) {
       // It's possible that we removed the prompt during the
@@ -89,17 +89,17 @@ var RemotePrompt = {
       // there's other stuff in nsWindowWatcher::OpenWindowInternal
       // that we might need to do here as well.
     } catch (ex) {
       onPromptClose(true);
     }
   },
 
   openModalWindow: function(args, browser) {
-    let window = browser.ownerDocument.defaultView;
+    let window = browser.ownerGlobal;
     try {
       PromptUtils.fireDialogEvent(window, "DOMWillOpenModalDialog", browser);
       let bag = PromptUtils.objectToPropBag(args);
 
       Services.ww.openWindow(window, args.uri, "_blank",
                              "centerscreen,chrome,modal,titlebar", bag);
 
       PromptUtils.propBagToObject(bag, args);
--- a/browser/modules/webrtcUI.jsm
+++ b/browser/modules/webrtcUI.jsm
@@ -109,32 +109,32 @@ this.webrtcUI = {
       return aCamera && state.camera ||
              aMicrophone && state.microphone ||
              aScreen && state.screen;
     }).map(aStream => {
       let state = aStream.state;
       let types = {camera: state.camera, microphone: state.microphone,
                    screen: state.screen};
       let browser = aStream.browser;
-      let browserWindow = browser.ownerDocument.defaultView;
+      let browserWindow = browser.ownerGlobal;
       let tab = browserWindow.gBrowser &&
                 browserWindow.gBrowser.getTabForBrowser(browser);
       return {uri: state.documentURI, tab: tab, browser: browser, types: types};
     });
   },
 
   swapBrowserForNotification: function(aOldBrowser, aNewBrowser) {
     for (let stream of this._streams) {
       if (stream.browser == aOldBrowser)
         stream.browser = aNewBrowser;
     }
   },
 
   showSharingDoorhanger: function(aActiveStream, aType) {
-    let browserWindow = aActiveStream.browser.ownerDocument.defaultView;
+    let browserWindow = aActiveStream.browser.ownerGlobal;
     if (aActiveStream.tab) {
       browserWindow.gBrowser.selectedTab = aActiveStream.tab;
     } else {
       aActiveStream.browser.focus();
     }
     browserWindow.focus();
     let PopupNotifications = browserWindow.PopupNotifications;
     let notif = PopupNotifications.getNotification("webRTC-sharing" + aType,
@@ -588,17 +588,17 @@ function prompt(aBrowser, aRequest) {
   notification =
     chromeWin.PopupNotifications.show(aBrowser, "webRTC-shareDevices", message,
                                       anchorId, mainAction, secondaryActions,
                                       options);
   notification.callID = aRequest.callID;
 }
 
 function removePrompt(aBrowser, aCallId) {
-  let chromeWin = aBrowser.ownerDocument.defaultView;
+  let chromeWin = aBrowser.ownerGlobal;
   let notification =
     chromeWin.PopupNotifications.getNotification("webRTC-shareDevices", aBrowser);
   if (notification && notification.callID == aCallId)
     notification.remove();
 }
 
 function getGlobalIndicator() {
   if (AppConstants.platform != "macosx") {
@@ -870,17 +870,17 @@ function updateIndicators(data, target) 
       gIndicatorWindow.updateIndicatorState();
   } else if (gIndicatorWindow) {
     gIndicatorWindow.close();
     gIndicatorWindow = null;
   }
 }
 
 function updateBrowserSpecificIndicator(aBrowser, aState) {
-  let chromeWin = aBrowser.ownerDocument.defaultView;
+  let chromeWin = aBrowser.ownerGlobal;
   let tabbrowser = chromeWin.gBrowser;
   if (tabbrowser) {
     let sharing;
     if (aState.screen) {
       sharing = "screen";
     } else if (aState.camera) {
       sharing = "camera";
     } else if (aState.microphone) {
@@ -1004,14 +1004,14 @@ function updateBrowserSpecificIndicator(
   screenSharingNotif =
     chromeWin.PopupNotifications.show(aBrowser, "webRTC-sharingScreen",
                                       stringBundle.getString(stringId + ".message"),
                                       "webRTC-sharingScreen-notification-icon",
                                       mainAction, secondaryActions, options);
 }
 
 function removeBrowserNotification(aBrowser, aNotificationId) {
-  let win = aBrowser.ownerDocument.defaultView;
+  let win = aBrowser.ownerGlobal;
   let notification =
     win.PopupNotifications.getNotification(aNotificationId, aBrowser);
   if (notification)
     win.PopupNotifications.remove(notification);
 }