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.
-
I suppose you had a look at this question?ForguesR– ForguesR2014-06-05 01:28:19 +00:00Commented Jun 5, 2014 at 1:28
-
1make a HEAD request. TADA!epascarello– epascarello2014-06-05 01:29:11 +00:00Commented Jun 5, 2014 at 1:29
-
So I gather is impossible for an external urlBelgin Fish– Belgin Fish2014-06-05 01:46:55 +00:00Commented Jun 5, 2014 at 1:46
-
It is not impossible, it depends on the server has CORS enabled.epascarello– epascarello2014-06-05 02:24:38 +00:00Commented Jun 5, 2014 at 2:24
Add a comment
|
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();
2 Comments
Exlord
how about cross origin urls ?
epascarello
@Exlord if they have CORs sure, if they don't, get your serverside to do it.
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
Thales Ludwig
This worked for me. Also, if you want to use an arrow function instead of the nameless function, change "this" for "xmlhttp".