10

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.

4
  • I suppose you had a look at this question? Commented Jun 5, 2014 at 1:28
  • 1
    make a HEAD request. TADA! Commented Jun 5, 2014 at 1:29
  • So I gather is impossible for an external url Commented Jun 5, 2014 at 1:46
  • It is not impossible, it depends on the server has CORS enabled. Commented Jun 5, 2014 at 2:24

2 Answers 2

14

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();
Sign up to request clarification or add additional context in comments.

2 Comments

how about cross origin urls ?
@Exlord if they have CORs sure, if they don't, get your serverside to do it.
1

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();

1 Comment

This worked for me. Also, if you want to use an arrow function instead of the nameless function, change "this" for "xmlhttp".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.