Search code examples
javascriptgoogle-chromemime-types

What is the best method to detect xml in JavaScript


What is the best method to detect xml in JavaScript

e.g. is it possible to detect the mime type of a document - particularly if it is text/xml in JavaScript.

this needs to work in Chrome.

thanks,

Josh


Solution

  • If you are using XMLHttpRequest to get this data, then you can simply check for the Content-Type header using the getResponseHeader method (granted that the server sends the appropriate headers).

    var getFile = function(address, responseHandler) {
      var req = new XMLHttpRequest();  
    
      req.open('get', address, true);  
      req.onreadystatechange = responseHandler;
      req.send(null);  
    }
    
    var responseHandler = function(resp) {
      if ( this.readyState < 4 ) { return; }
      console.log(this.getResponseHeader("Content-Type"));
    };
    
    getFile("http://zebrakick.com/some/file", responseHandler);
    

    (I seem to be using this code sample a lot...)