views:

61

answers:

4

I have an <iframe> whose src points to a plain text file (not HTML). The text gets loaded and displayed on screen, but seems to be hidden to JavaScript.

In other browsers, iframe.contentWindow.document.body.innerText is enough to get it for you, but IE returns an empty string in that case.

Is there a way that IE can access the text inside the file without involving a server?

A: 

Just a shot in the dark, but have you tried the innerHTML property?

Alternatively, the more "proper" way to do this is to request the file directly with XMLHttpRequest.

Justin Johnson
Yes, I tried innerText and it's also an empty string. And I'd use XMLHttpRequest, but I'm actually accessing a local file (whose path is pulled out of a <input type='file' />), so security measures prevent that. Other browsers have the FileAPI or whatnot to handle this, but IE does not.
TALlama
+1  A: 

You can read this file using XmlHttpRequest. If the browser can read it, so can XmlHttpRequest.

/* Read a file  using xmlhttprequest 

If the HTML file with your javascript app has been saved to disk, 
this is an easy way to read in a data file.  Writing out is 
more complicated and requires either an ActiveX object (IE) 
or XPCOM (Mozilla).

fname - relative path to the file
callback - function to call with file text
*/
function readFileHttp(fname, callback) {
   xmlhttp = getXmlHttp();
   xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState==4) { 
          callback(xmlhttp.responseText); 
      }
   }
   xmlhttp.open("GET", fname, true);
   xmlhttp.send(null);
}

/*
Return a cross-browser xmlhttp request object
*/
function getXmlHttp() {
   if (window.XMLHttpRequest) {
      xmlhttp=new XMLHttpRequest();
   } else if (window.ActiveXObject) {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
   if (xmlhttp == null) {
      alert("Your browser does not support XMLHTTP.");
   }
   return xmlhttp;
}

Call the readFileHttp(fname, callback) using the iframe.src property for the fname parameter. The callback parameter should be a function that does whatever you want with the result.

Something like this:

var myIFrame = document.getElementById('iframeIdGoesHere');
readFileHttp(myIFrame.src, function(result){
    //process the result
});
Peter
If you would be using jquery it would be a lot easier using the jQuery.get() (http://api.jquery.com/jQuery.get/) method. The principle is the same though.
Peter
A: 
awe
The question is specifically about a JavaScript solution; there is no server in this application. I updated the wording to be a bit more explicit about this.
TALlama
A: 

and

window.frames[0].document.getElementsByTagName("body")[0].innerHTML

?

magnus