2
<html>
    <body>
    <!-- <iframe id="iff" srcdoc="<div>ok</div>"></iframe> -->
    <iframe id="iff" src="data:text/html;charset=utf-8,%3Cdiv%3Eok%3C%2Fdiv%3E"></iframe>
    <script>
        console.log(document.getElementById('iff').contentWindow.document)
    </script>
    </body>
</html>
  1. I set srcdoc (tried src also) of <iframe>, but cannot access the real document of the iframe (tried iframeElement.contentDocument also). Chrome outputs (also tried Firefox): result

I see in Get IFrame's document, from JavaScript in main document that I cannot get the document of a cross-domain iframe, and also learned from Which is the difference between srcdoc="..." and src="data:text/html,..." in an <iframe>? that src and srcdoc behaves different about cross-domain behavior. But I tried both, none works.

2. When I append a child to the document body of an iframe (with src attribute set), the DOM updates but it doesnt show on screen.

lsdsjy
  • 63
  • 8
  • What is in console is not what it actually is with DOM concerning iframes. – zer00ne Mar 15 '19 at 16:24
  • @zer00ne but I cant manipulate the iframe's DOM (with src set) either, such as appendChild – lsdsjy Mar 17 '19 at 06:19
  • If you have an iframe with srcdoc and you want to get content from it to the parent page use `importNode()` to copy or `adoptNode()` to move. – zer00ne Mar 17 '19 at 08:38
  • @zer00ne Well that could work so thanks! But I still wonder if there is an explanation for this behavior in W3C documents? – lsdsjy Mar 18 '19 at 11:48
  • The conflicts you are experiencing is due to a slew of security measures, the very environment that you are testing in determines different behavior from the next. **Do not believe what the Developer Tools show you when it involves accessing the iframe it will LIE** – zer00ne Mar 18 '19 at 11:56
  • Now that makes sense. Much thanks! – lsdsjy Mar 19 '19 at 15:06

1 Answers1

0

Try something like:

window.frames['iff'].document.myvar;

This can be useful if you look for the iframe with the url:

var x=getIframeID("cool.php");
x.contentWindow.callafunction();

function getIframeID(iframeurl) {
    var iFs = top.document.getElementsByTagName('iframe');
    var x, i = iFs.length;
    while ( i-- ){
        x = iFs[i];
        if(iframeurl.indexOf(x.src)>=0) return (x.id);
        if (x.src == iframeurl)         return (x.id);
    }
    return("");
}
gtryonp
  • 397
  • 5
  • 13