View Full Version : Importing file contents as JS string

02-11-2003, 02:22 AM
OK, this little code takes a string (URL) input and returns an array ([fileContents,httpHeaders]).

function getFile(n){
var file; // Define variable
if(n==''||n==self.location)return []; // Don't request self or empty strings (Safety meassure for some IE and pre0.9.9 Moz versions)
switch(typeof ActiveXObject){
case 'function': // Chech if ie
file=new ActiveXObject('Microsoft.XMLHTTP'); // If so use ie XHreq
file=new XMLHttpRequest; // Otherwise use moz XHreq
file.overrideMimeType("text/xml"); // And override content-type to avoid breakage
try{// Error susceptible code (Moz may screw up, especially if you're breaking the security rules)
f.open('GET',n,false);// Open connection
f.send('')// Send empty string
}catch(e){// If error
return []// ...return empty null-length array
return [f.responseText,f.getAllResponseHeaders()]// Otherwise return response and http headers

Note that the file must be within the current domain, or only ie5.5win will actually be able to fetch it.

For seeing script in action, take a look at my bookmarklets at <http://members.evolt.org/liorean/bookmarklets.html>

// liorean <http://members.evolt.org/liorean/>

02-11-2003, 04:16 PM
I recently had to do something similar for an intranet application. Except I needed to submit data to a CGI program on the server and capture the response so it does a POST with data instead of a GET.

It's defined as an object, to make adding the "form" data easier.

// FormPost Object
// Constructor
// FormPost(url) - Creates the object and sets the URL.
// Methods:
// addField(name, value)
// - Adds a name/value pair to the form data.
// clear() - Removes all name/value pairs from the form data.
// submit() - Posts the form data to the object's URL and returns
// the response data received as a text string.

// Constant defining possible Microsoft XML HTTP ProgIDs.

function FormPost(url)
// Create the appropriate XMLHTTP object for the browser.

// For Mozilla:
if (window.XMLHttpRequest != null)
this.xmlHttp = new XMLHttpRequest();
// For IE:
else if (window.ActiveXObject != null)
// Try each ProgID until one works.
var success = false;
for (var i = 0; i < FORMPOST_MSXML_HTTP_PROGIDS.length && !success; i++)
this.xmlHttp = new ActiveXObject(FORMPOST_MSXML_HTTP_PROGIDS[i]);
success = true;
catch (e) {}
// If it couldn't be created, throw an exception.
if (!success)
throw "Cannot create an XMLHTTP object.";

// Set properties.
this.url = url;
this.data = "";

// Set methods.
this.addField = FormPostAddField;
this.clear = FormPostClear;
this.submit = FormPostSubmit;

// Implementation of the FormPost.addField() method.
function FormPostAddField(name, value)
// Add the name/value pair to the request data.
if (this.data.length > 0)
this.data += "&";
this.data += window.escape(name) + "=" + window.escape(value);

// Implementation of the FormPost.clear() method.
function FormPostClear()
// Reset the request data.
this.data = "";

// Implementation of the FormPost.submit() method.
function FormPostSubmit()
// Set up a synchronous POST request, set the data encoding header and send it.
this.xmlHttp.open("POST", this.url, false);
this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// Check the HTTP response status code. If it is not "OK," throw an exception.
if (this.xmlHttp.status != 200)
throw "HTTP request for \"" + this.url + "\" failed with status \"" +
this.xmlHttp.status + " " + this.xmlHttp.statusText + "\"";
// Otherwise, return the response data as a text string.
return this.xmlHttp.responseText;
catch (e)
// An exception occured, pass it on.
throw e;

An example usage:

var formPost = new FormPost("formpost.asp");
formPost.addField("Name", "Jane Doe");
formPost.addField("Email Address", "jdoe@example.net");
var s = formPost.submit();
// For IE:
if (e.description != null) alert(e.name + ": " + e.description);
// All others:
else alert(e);

02-11-2003, 04:29 PM
Hmm, I just had an idea - if you use script the way I did, but link it to a serverside script that simply returns the URL provided to it, you might be able to get it to reach out of the domain. I don't know what it would do with the HTTP headers if you tried to forward them that way, but you would certainly be able to use it for loading cross-domain sources.

Oh, as an aside, this script is like most of my scripts done in a way that tried to keep the size down. I added no features that I didn't need to it.

02-11-2003, 04:43 PM
There's actually posted a security bulletin about that. I guess you could have the server-side script redirect to a local file URL. Both IE and Mozilla have (or had) this vunerability: http://sec.greymagic.com/adv/gm001-ns/

I didn't think to override the mime type. That's probably a good idea knowing how IE likes to interpret things it's own way.

02-11-2003, 06:20 PM
First of all, Mozilla fixed that, as displayed by this error message:

Security Error: Content at http://sec.greymagic.com/adv/gm001-ns/getFile.asp?fName=file%3A/// may not load or link to file:///.

What I was thinking, was that since it currently in neither IE6 nor Moz can reach out of the domain the current page is in (http://www.codingforum.com/ for this forum, for instance), you could use a serverside script for reaching out of the domain, which then returns the source and HTTP headers exactly as they were sent to the script from the outside domain. I don't know whether the HTTP headers would be entirely the ones of the page or if the server would add/change some of them, thus destroying part of the feature.

I also have no idea whether a temporary or permanent redirect would allow reaching cross-domain.

Oh, and about that Content-Type override: it's for Moz's benefit, not IE. Moz sometimes decides to either CPU hog or crash when loading a non-XML page, depending on actual content-type and some of the contained code. Mozilla has had this bug since 0.9.8 or earlier (haven't tested on earlier versions), and it wasn't fixed as of 1.2.1.

(Oh, and there's a setting that you can use to actually get Moz to reach past domains and even protocols, like http-to-file, but the user will be prompted for it when you set it through non-integrated JS.)

It wouldn't surprise me a bit if IE still haven't been fixed, though.

// liorean <http://members.evolt.org/liorean/>

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum