Javascript- <iframe> isn't working with local file

0

I'm trying to display a local file in my computer using <iframe>. If I add the file as an existing item to my project it works great but if I add the path of my local file (to <iframe> src) it doesn't work. I tried creating the file as txt file and as html file and both don't work. I also tried different methods to write the path (single or double slash and backslash). the first <iframe> in the code is the one that works with the existing file(added to the project) and the second one is the one with the path to the file location in my computer(which doesn't work).

After debugging the javascript part I saw that the second file's body (pa.contentWindow.document.body) doesn't include childnodes[0] in his properties like the first file does, and it made me understand that maybe the program thinks that the file is empty or undefined which is also the error I get:

0x800a138f - JavaScript runtime error: Unable to get property 'innerHTML' of undefined or null reference).

What can I do? Any help would be appreciated.

html:

 <iframe id="50" src="file.txt" style="width:100px;height:100px; border:0; border:none;">Browser doesnt support iframe</iframe>
 <iframe id="51" src="file:///C:\folder\file.txt" style="width:100px;height:100px; border:0; border:none;">Browser doesnt support iframe</iframe>

javascript:

 oFrame = document.getElementById("50");
        strRawContents = String(oFrame.contentWindow.document.body.childNodes[0].innerHTML);
 pa = document.getElementById("51");
        strRawContentspa = String(pa.contentWindow.document.body.childNodes[0].innerHTML);
javascript
file
iframe
asked on Stack Overflow Feb 20, 2018 by sheli • edited Feb 20, 2018 by Jordi Castilla

2 Answers

0

You need to be sure that the iframe has been loaded before to do something with it:

oFrame.onload = () => {
  // your javascript actions here
}
answered on Stack Overflow Feb 20, 2018 by zelda11
0

If the frames source comes from different origin than your main document - you won't have access to it.
MDN article on origins

Imagine a site which opens you banks site in an iframe and just grabs your account data from the dom.

answered on Stack Overflow Feb 20, 2018 by Alexander Taran

User contributions licensed under CC BY-SA 3.0