Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check url content type with javascript

In order to conserve server resources I'm looking for a way to retrieve the content type of a given url using javascript. It should not download the complete content from the url only the headers. Is this possible with the restrictions javascript has.

like image 466
Belgin Fish Avatar asked Jun 05 '14 01:06

Belgin Fish


2 Answers

Make an Ajax call with a head request.

var url = window.location.href;
var xhttp = new XMLHttpRequest();
xhttp.open('HEAD', url);
xhttp.onreadystatechange = function () {
    if (this.readyState == this.DONE) {
        console.log(this.status);
        console.log(this.getResponseHeader("Content-Type"));
    }
};
xhttp.send();
like image 184
epascarello Avatar answered Nov 11 '22 01:11

epascarello


FYI if your server doesn't allow HEAD requests but does allow GET requests, you can do this by limiting the range of the GET request.

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Range", "bytes=0");
xmlhttp.onreadystatechange = function () {
  if (this.readyState == this.DONE) {
    console.log(this.getResponseHeader("Content-Type"));
  }
};
xmlhttp.send();
like image 1
Brettins Avatar answered Nov 11 '22 00:11

Brettins