2009-08-27 36 views
44

我可以得到window.document,但我怎樣才能得到document.window?我需要知道如何在所有瀏覽器中執行此操作。如何從Document對象獲取Window對象?

+2

敢問我爲什麼?窗口是一個始終可用的對象,並且窗口中總是不會超過1個文檔,可以說是1-1關係... – Colin 2009-08-27 00:10:50

+4

因爲我在多個iframe中使用原型,並且各種Element方法在IE中斷裂或Safari如果元素以某種方式在錯誤的範圍內擴展。我已經修改了一些東西來解決原型中的這個問題,但修復程序的一部分需要我找到一個元素所在的窗口。 – Joren 2009-08-27 18:19:44

+0

@Joren,請考慮更改爲接受的答案。 – kay 2016-02-09 15:41:27

回答

-1

The Window object is the top level object in the JavaScript hierarchy,所以才稱它爲窗口

編輯:前 原來的答覆Promote JS努力。 JavaScript technologies overview在Mozilla開發者網絡上說:

在瀏覽器環境中,這個全局對象是窗口對象。

編輯2: 閱讀作者的評論對他的問題(並獲得downvotes),這似乎與iframe的文檔窗口後。看看window.parentwindow.top,並可能比較它們以推斷您的文檔窗口。

if (window.parent != window.top) { 
    // we're deeper than one down 
} 
+7

在open()之後,新窗口的'window'是另一個'window',而不是'opener'。如果您從某個函數接收到「文檔」(或任何「節點」),則可能需要原始窗口。 (哇,這是非常古老的。) – Rudie 2013-03-21 18:08:55

77

您可以document.defaultView去,如果你確定它是一個窗口,它的好IE 9

+6

是的。請記住,根據規範,'document.defaultView'不必與'window'是同一個對象(事實上,它在一些較老的客戶端中是不同的,例如:Safari 2.x) – kangax 2009-08-27 02:40:35

+0

適用於XUL文檔在Firefox也!謝謝:) – macguru2000 2015-06-26 18:21:55

+1

doc.parentWindow || doc.defaultView,它在舊的IE和Safari – 2017-05-31 12:12:07

3

好之前跳過微軟的瀏覽器,這是我去解決。它有效,但我討厭它。

getScope : function(element) { 
    var iframes = top.$$('iframe'); 
    var iframe = iframes.find(function(element, i) { 
     return top[i.id] ? top[i.id].document == element.ownerDocument : false; 
    }.bind(this, element)); 
    return iframe ? top[iframe.id] : top; 
} 
+0

只有IE瀏覽器... – 2009-08-28 17:53:08

+0

什麼是IE瀏覽器只有它?似乎在FF \ Saf \ IE \ Chrome中正常工作。 但是,除了IE之外,它不是必需的,因爲其他瀏覽器都會在正確的範圍內自動擴展元素。 – Joren 2009-08-31 23:15:10

17

一個跨瀏覽器的解決方案是複雜的,這裏的道場是怎麼做的(從window.js ::得到()):

// In some IE versions (at least 6.0), document.parentWindow does not return a 
// reference to the real window object (maybe a copy), so we must fix it as well 
// We use IE specific execScript to attach the real window reference to 
// document._parentWindow for later use 
if(has("ie") && window !== document.parentWindow){ 
    /* 
    In IE 6, only the variable "window" can be used to connect events (others 
    may be only copies). 
    */ 
    doc.parentWindow.execScript("document._parentWindow = window;", "Javascript"); 
    //to prevent memory leak, unset it after use 
    //another possibility is to add an onUnload handler which seems overkill to me (liucougar) 
    var win = doc._parentWindow; 
    doc._parentWindow = null; 
    return win; // Window 
} 

return doc.parentWindow || doc.defaultView; // Window 

有( 「IE」)返回IE真(和否則爲假)

0

首先讓我們來清楚。當你使用框架,iframe和多個窗口時,這種事情通常是必要的,所以「窗口就是全局對象」是一個令人不滿意的答案,如果你有一個句柄是另一個窗口的文檔比你所在的地方還要多。

秒,遺憾的是沒有直接獲取窗口對象的方法。有間接的方式。

使用的主要機制是window.name。從某些父窗口創建窗口或框架時,通常可以給它一個唯一的名稱。該窗口內的任何腳本都可以在window.name中獲得。窗口外的任何腳本都可以獲取其所有子窗口的window.name。

要獲得更具體的比那需要更多的信息關於具體情況。但是在任何情況下,子腳本都可以與父腳本進行通信,反之亦然,它們總是可以通過名稱來識別對方,而這通常就足夠了。