contentDocument for an iframe

前端 未结 3 1103
盖世英雄少女心
盖世英雄少女心 2020-11-29 09:18

What exactly does \"contentDocument\" represent for an iframe (or even the old \"frame\" element)? Is it equivalent to the \"html\" element or the \"body\" element ? What is

相关标签:
3条回答
  • 2020-11-29 10:11

    contentDocument is the standardized way to get hold of the iframe or frame's Document object. It is the same object as JavaScript running within the iframe would access via document.

    As noted in other answers, IE didn't support it until version 8 but did support access to the iframe's Window object via contentWindow. A cross-browser way of getting hold of an iframe's <body> element is therefore:

    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
    var iframeBody = iframeDoc.body;
    

    Note that if the iframe is not served from the same domain as the main document, browser security restrictions will prevent access to its document object in this or any other way.

    0 讨论(0)
  • 2020-11-29 10:13

    w3.org

    contentDocument of type Document, readonly, introduced in DOM Level 2 The document this frame contains, if there is any and it is available, or null otherwise.

    MDN

    From the DOM iframe element, scripts can get access to the window object of the included HTML page via the contentWindow property. The contentDocument property refers to the document element inside the iframe (this is equivalent to contentWindow.document), but is not supported by Internet Explorer versions before IE8.

    msdn

    the document this page or frame contains
    This property is new in Windows Internet Explorer 8

    So to get the innerHTML of the body element you could use

    iframe.contentDocument.getElementsByTagName("body")[0]

    or

    iframe.contentDocument.body

    in todays browsers.

    0 讨论(0)
  • 2020-11-29 10:20

    contentDocument represents the document of an iframe (DOM object). It is not equivalent to html since documents have their own properties, however if you type:

    myFrame.contentDocument.body 
    

    You will get the body itself.

    It is supported in all the browsers, with a tiny modification: for Internet Explorer use

    myFrame.contentWindow.document
    

    Enjoy, Nili

    0 讨论(0)
提交回复
热议问题