以下幾點為 cookie, sessionStorage 和 localStorage 主要的差異:
cookie:cookie 會隨著 http 請求打到伺服器,會在第一次 client 發送請求後,sever 會在 response 的 header 加入Set-Cookie
還有 response 加入 cookie,當 client 收到後會存在瀏覽器本地。
sessionStorage:使用 key-value 的形式儲存在瀏覽器本地。
localStorage:使用 key-value 的形式儲存在瀏覽器本地。
135. localStorage with expiration
localStorage is a simple and handy client-side storage, but you should avoid using it because it is synchronous.
Also Safari's ITP actually deletes client-side script-writable storage after 7 days of Safari use without interacting on your website, and localStorage is included.
Unlike Cookie, localStorage doesn't expire.
In this problem, please create a localStorage wrapper with expiration support
myLocalStorage.setItem("bfe", "dev", 1000);
myLocalStorage.getItem("bfe");
// 'dev'
after 1 second:
myLocalStorage.getItem("bfe");
// null
window.myLocalStorage = {
getItem(key) {
const data = window.localStorage.getItem(key);
if (!data) return null; // key 不存在
const parsedData = JSON.parse(data);
// 檢查 expiry ,沒有設置 expiry 或尚未過期,則返回 value
if (!parsedData.expiry || parsedData.expiry > Date.now()) {
return parsedData.value;
} else {
// 如果過期了,移除該項目並返回 null
window.localStorage.removeItem(key);
return null;
}
},
setItem(key, value, maxAge) {
window.localStorage.setItem(key, value);
if (maxAge === 0) {
//因為這題必須要在 LocalStorage 實現失效時間的功能,因此如果 maxAge 失效時間是0的話就代表就是失效了,直接移除該項目
window.localStorage.removeItem(key);
}
//計算出過期的時間
const expiry = maxAge > 0 ? Date.now() + maxAge : null;
//將過期的時間跟資料儲存
const data = {
value: value,
expiry: expiry,
};
// 儲存 JSON 字串到 localStorage
window.localStorage.setItem(key, JSON.stringify(data));
},
removeItem(key) {
window.localStorage.removeItem(key);
},
clear() {
window.localStorage.clear();
},
};