Search code examples
javascriptdocumentlast-modified

javascript document.lastModified not working properly


I've just tried document.lastModified but it is returning the system date and time NOT the html file last modified date and time as expected.

It is very odd behavior.

How I checked this: I have inserted the command into the js then I looked up into the document property at run time with google chrome dev tools in debug interruption/break point mode: every time I point the mouse onto document.lastmodified property it changes accordingly with the system time and updates every second, without exiting the html document, without saving it elsewhere and without reloading into the browser, without doing anything else to it with any editor.

Then I deactivated the break point and I let the code execute freely and it returns the system time too as the first check...

This double check lets me think that the command is not correctly interpreted from the browser anymore.

Is the command document.lastModified some way "broken"?

EDIT: The file I'm talking about is a local not a server file, so no http requests or headers involved.

..._ _ _...


Solution

  • According to the spec:

    The Document's source file's last modification date and time must be derived from relevant features of the networking protocols used, e.g. from the value of the HTTP Last-Modified header of the document, or from metadata in the file system for local files.

    So it should be there. This is a reported bug in Chrome. Searching the Chromium source code shows that this is indeed the case (note the FIXME comment):

    // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
    String Document::lastModified() const
    {
        DateComponents date;
        bool foundDate = false;
        if (m_frame) {
            if (DocumentLoader* documentLoader = loader()) {
                const AtomicString& httpLastModified = documentLoader->response().httpHeaderField(HTTPNames::Last_Modified);
                if (!httpLastModified.isEmpty()) {
                    date.setMillisecondsSinceEpochForDateTime(convertToLocalTime(parseDate(httpLastModified)));
                    foundDate = true;
                }
            }
        }
        // FIXME: If this document came from the file system, the HTML5
        // specificiation tells us to read the last modification date from the file
        // system.
        if (!foundDate)
            date.setMillisecondsSinceEpochForDateTime(convertToLocalTime(currentTimeMS()));
        return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
    }
    

    Firefox and IE seem to have implemented this, though :)