文件:lastModified 屬性
Document 介面的 lastModified 屬性返回一個字串,其中包含當前文件上次修改的日期和本地時間。
值
字串。
示例
簡單用法
此示例會彈出 lastModified 的值。
js
alert(document.lastModified);
// returns: Tuesday, December 16, 2017 11:09:42
將 lastModified 轉換為 Date 物件
此示例將 lastModified 轉換為 Date 物件。
js
let oLastModif = new Date(document.lastModified);
將 lastModified 轉換為毫秒
此示例將 lastModified 轉換為自 1970 年 1 月 1 日 00:00:00(本地時間)以來的毫秒數。
js
let nLastModif = Date.parse(document.lastModified);
注意
請注意,作為字串,lastModified 不容易用於比較文件的修改日期。以下是一個可能的示例,演示如何在頁面更改時顯示警報訊息(另請參閱:JavaScript cookies API)
js
// Match 'timestamp' in 'last_modif=timestamp'
// e.g. '1687964614822' in 'last_modif=1687964614822'
const pattern = /last_modif\s*=\s*([^;]*)/;
if (
Date.parse(document.lastModified) >
(parseFloat(document.cookie.match(pattern)?.[1]) || 0)
) {
document.cookie = `last_modif=${Date.now()}; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=${
location.pathname
}`;
alert("This page has changed!");
}
…相同的示例,但跳過第一次訪問
js
const pattern = /last_modif\s*=\s*([^;]*)/;
const lastVisit = parseFloat(document.cookie.replace(pattern, "$1"));
const lastModif = Date.parse(document.lastModified);
if (Number.isNaN(lastVisit) || lastModif > lastVisit) {
document.cookie = `last_modif=${Date.now()}; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=${
location.pathname
}`;
if (isFinite(lastVisit)) {
alert("This page has been changed!");
}
}
如果您想知道外部頁面是否已更改,您可以使用 fetch() API 傳送一個 HEAD 請求,並檢查 Last-Modified 響應頭。
規範
| 規範 |
|---|
| HTML # dom-document-lastmodified-dev |
瀏覽器相容性
載入中…