Reading IFrame Content Using JavaScript

Well, this is my first time we take IFrames seriously, and I can't figure out a few things:

First, the sample code that 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" is as follows:

 sample text file 

Questions:

1) the iframe seems to behave like an HTML document, and the text of the file is actually part of the body. What for? Is the IFrame rule an HTML document. Is it not possible that the contents of an iframe are just text?

2) For some reason, the contents of the file are wrapped inside the pre tag. Why is this so? It's always like this?

3) My access method in javascript works, but is there any other alternative? [native js solutions please] If the content is wrapped in a pre tag, then I really need to search inside the pre tag and not look for innerHTML

+4
source share
4 answers

innerHTML does not return the exact content of the element, its non-standard method, which returns HTML equivalent to the real content, but in HTML the equivalent of plain text <pre>foo...</pre> .

You might be lucky with the innerText property.

+4
source

It was difficult for me to get the contents of a TXT file, which was an src iframe. This is my decision:

 document.getElementById( 'iframeID' ).contentWindow.document.body.innerText 
+6
source

1) the iframe seems to behave like an HTML document, and the text of the file is actually part of the body. What for?

you are using the DOM / JS interface. this will only work if the content is processed as HTML / XML.

0
source

The way browsers handle text files because they "look better" this way (not just inside the iframe). Browsers can handle many types of files, and it is unreasonable to expect them to show everything in raw form, right? Since browser pages (and iframes) are related to presentation, no one uses an iframe to configure or to read raw data from disk.

If you want to have full control over the presentation, just change the file type to html and it will be processed as html. (in particular, he will solve the "pre" problem)

Will this answer your questions?

0
source

Source: https://habr.com/ru/post/1308944/


All Articles