3

I am trying to create a javascript function which returns the last modified date of a remote url which it recieves. I have tried many different methods, none of which seem to work. The following code seems like it may be close, but unfortunately doesnt work.

function getlastmod(url) {
    var req = new XMLHttpRequest();
    req.open("GET", url, false);
    req.getResponseHeader("Last-Modified");
    req.send("");
    return req.responseText;
}

The function will be used in a chrome extension that I am making. Thanks for any help-Josh

Esailija
  • 138,174
  • 23
  • 272
  • 326
Josh
  • 366
  • 2
  • 8
  • 20
  • 6
    If the server doesn't tell you the `Last-Modified`, it is fundamentally impossible for you to find it. – SLaks Aug 01 '12 at 14:09
  • @sLaks This code should indeed work, make an answer –  Aug 01 '12 at 14:10
  • @Esailija if the server tells the last-modified –  Aug 01 '12 at 14:11
  • 1
    @rsplak it doesn't matter if it tells it because the code ignores it. It is also trying to get the header before the request has even been made. – Esailija Aug 01 '12 at 14:12
  • I withdrew my answer as all you are receiving is the header, which I think would work cross domain; however, as SLaks said, the server has to give you the last-modified time. If the server does not, it defaults to the current time (GMT). – vol7ron Aug 01 '12 at 14:32
  • @vol7ron It won't work cross-domain if the full request doesn't work cross-domain. I have already given you plenty of references on this. Cross-domain xhr can be done just as well as same-domain xhr can be done. ,http://jsfiddle.net/7qA7R/ – Esailija Aug 01 '12 at 14:33

1 Answers1

7

Some issues:

  • You are trying to get the headers before a connection has even been made. You can only read the headers after the server has responded.
  • You are not doing anything with the result

Try this:

function getlastmod(url, cb) {
    var req = new XMLHttpRequest();
    req.open("GET", url);
    req.send(null);
    req.addEventListener("load", function() {
        cb(req.getResponseHeader("Last-Modified"));
    }, false);
}

getlastmod("/", function(v) {
    console.log(v); //"Wed, 01 Aug 2012 14:13:22 GMT"
});

This requires your extension to ask for the right permissions (because you are doing cross-origin xhr) as well as the server to send the header.

Esailija
  • 138,174
  • 23
  • 272
  • 326