Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    Master Coder
    Join Date
    Feb 2003
    Location
    UmeŚ, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts

    Post Importing file contents as JS string

    OK, this little code takes a string (URL) input and returns an array ([fileContents,httpHeaders]).

    Code:
    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
          break;
        default:
          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/>
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #2
    Regular Coder
    Join Date
    Jun 2002
    Posts
    185
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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.

    Code:
    // 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.
    var FORMPOST_MSXML_HTTP_PROGIDS = new Array(
      "MSXML2.XMLHTTP.4.0",
      "MSXML2.XMLHTTP.3.0",
      "MSXML2.XMLHTTP",
      "Microsoft.XMLHTTP"
    );
    
    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++)
        {
          try
          {
            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()
    {
      try
      {
        // 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");
        this.xmlHttp.send(this.data);
        // 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.
        else
          return this.xmlHttp.responseText;
      }
      catch (e)
      {
        // An exception occured, pass it on.
        throw e;
      }
    }
    An example usage:

    Code:
      try
      {
        var formPost = new FormPost("formpost.asp");
        formPost.addField("Name", "Jane Doe");
        formPost.addField("Email Address", "jdoe@example.net");
        var s = formPost.submit();
        alert(s);
      }
      catch(e)
      {
        // For IE:
        if (e.description != null) alert(e.name + ": " + e.description);
        // All others:
        else alert(e);
      }
    Last edited by BrainJar; 02-11-2003 at 04:25 PM.

  • #3
    Master Coder
    Join Date
    Feb 2003
    Location
    UmeŚ, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    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.
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #4
    Regular Coder
    Join Date
    Jun 2002
    Posts
    185
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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.

  • #5
    Master Coder
    Join Date
    Feb 2003
    Location
    UmeŚ, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts

    Smile Something about security

    First of all, Mozilla fixed that, as displayed by this error message:
    Security Error: Content at http://sec.greymagic.com/adv/gm001-n...ame=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/>
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •