2011-09-27 49 views
2

是否可以直接從Javascript中的文檔對象訪問窗口對象?如何從文檔對象訪問窗口對象

例如:

// window.frames[0] returns the document object of the first frame or iframe found on the page 
myFunc(window.frames[0]); 

function myFunc(doc) { 
    // I want to do something along these lines: 
    var wnd = doc.getWindow(); 
    alert("Found frame: " + wnd.name); 
    for (var i=0; i<wnd.frames.length; i++) { 
    myFunc(wnd.frames[i]); 
    } 
} 

我不能使用jQuery這個,對不起。

回答

0

根據MDN documentation您應該已經開始使用window.frames[0]了。如果您想要實際的文檔,您需要抓取實際的框架元素並挖掘文檔。

var firstFrame = document.getElementsByTagName("iframe")[ 0 ]; 
firstFrame.contentWindow; // The window 
firstFrame.contentWindow.document; // The document 

注:我相信contentWindow是不是在Safari(預3.0 IIRC)

+0

的非常早期的版本支持不幸的是並非如此。嘗試使用'contentWindow'在我的問題中給出的示例代碼,您會發現它不起作用,當然不是在所有瀏覽器中。 –

+0

根據MDN文檔@NickBrunt,'windows.frames [0]'的結果應該是'contentWindow'。 'window.frames [0]'和'document.getElementsByTagName(「iframe」)[0]' – JaredPar

+0

之間有區別*應該發生什麼和發生什麼有很大的區別。自己嘗試一下。 –