简体   繁体   中英

Read IFrame content using JavaScript

Ok, This is my first time dealing seriously with IFrames and I cant seem to understand a few things:

First the sample code I am testing with:

<head>
<script type="text/javascript">
function init(){
  console.log("IFrame content: " + window.frames['i1'].document.getElementsByTagName('body')[0].innerHTML);
}
</script>
</head>
<body onload="init();">
<iframe name="i1" src="foo.txt"/>
</body>

the file "foo.txt" looks like this:

sample text file

Questions:

1) The iframe seems to be behaving as a HTML document and the file text is actually part of the body instead. Why ? Is it a rule for an IFrame to be a HTML document. Is it not possible for the content of an iframe to be just plain text ??

2) The file content gets wrapped inside a pre tag for some reason. Why is this so ? Is it always the case?

3) My access method in the javascript is working but is there any other alternative? [native js solutions please] If the content is wrapped in a pre tag always then I will actually have to lookup inside the pre tag rather than lookup the innerHTML

I was having a hard time getting the contents of a TXT file that was the src of an iframe. This is my solution:

document.getElementById( 'iframeID' ).contentWindow.document.body.innerText

innerHTML does not return the exact content of an element, its a non-standardized method that returns HTML which is equivalent to the real content, and in HTML the equivalent to plain text is <pre>foo...</pre> .

You might have better luck with the innerText property..

1) The iframe seems to be behaving as a HTML document and the file text is actually part of the body instead. Why ?

you're using the DOM/JS interface. this will only work, if the content is treated as HTML/XML.

That's how browsers treat text files, because they 'look better' this way (not only inside iframe). Browsers can process lot's of file types, and it's unreasonable to expect them to show everything in raw form, right? Because browser pages (and iframes) are about presentation, nobody really uses iframes for configuration or to read raw data from the disk.

If you want to have full control over presentation, just change file type to html and it will be treated like html. (in particular, it will solve 'pre' problem)

Will this answer your questions?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM