Client Side Storage
*복습 자료라서 뻔한 내용은 생략
Summary.
0. Web Storage API, IndexedDB API, Cache API, Cookie, 등이 있음
+ Cookie: still used commonly to store data related to user personalization and state, e.g. session IDs and access tokens.
+ Web Storage: when you just need to store some simple data, like the user's name, whether they are logged in, what color to use for the background of the screen, etc
+ IndexedDB: a complete database system for storing complex data. This can be used for things from complete sets of customer records to even complex data types like audio or video files
+ Cache: for storing HTTP responses to specific requests, and is very useful for doing things like storing website assets offline so the site can subsequently be used without a network connection
0.5. Client Side Storage 용도 (Server side storage가 아닌)
- Personalizing site preferences (e.g. showing a user's choice of custom widgets, color scheme, or font size).
- Persisting previous site activity (e.g. storing the contents of a shopping cart from a previous session, remembering if a user was previously logged in).
- Saving data and assets locally so a site will be quicker (and potentially less expensive) to download, or be usable without a network connection.
- Saving web application generated documents locally for use offline
1. The Web Storage API provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies.
+ Cookie는 클라이언트에서 document.cookie 로 값을 설정하거나 서버에서 Set-Cookie Header로 설정 가능
2. Session Storage와 localStorage 두 종류
+ Session Storage
+ Origin 마다 할당 (browser crash/restart에도 5MB 정도 보장. 쿠키보다 큰 저장공간)
+ Page Session 동안 보장 (as long as the browser is open, including page reloads and restores)
+ 즉, the data is stored until the browser (or tab) is closed.
+ Server로 데이터 전송 불가 (?)
+ Local Storage
+ 브라우저 닫혀도 persist
+ no expiration date, and gets cleared only through JavaScript, or clearing the Browser cache / Locally Stored Data
3. A different Storage object is used for the sessionStorage and localStorage for each origin — they function and are controlled separately
4. The Web Storage API extends the Window object with two new properties — Window.sessionStorage and Window.localStorage — which provide access to the current domain's session and local Storage objects respectively, and a storage event handler that fires when a storage area changes (e.g. a new item is stored.)
5. Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings). You can access these values like an object, or with the Storage.getItem() and Storage.setItem() methods.
localStorage.colorSetting = '#a4509b';
localStorage['colorSetting'] = '#a4509b';
localStorage.setItem('colorSetting', '#a4509b');
6. The StorageEvent is fired whenever a change is made to the Storage object (note that this event is not fired for sessionStorage changes). This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects.
window.addEventListener('storage', function(e) {
document.querySelector('.my-key').textContent = e.key;
document.querySelector('.my-old').textContent = e.oldValue;
document.querySelector('.my-new').textContent = e.newValue;
document.querySelector('.my-url').textContent = e.url;
document.querySelector('.my-storage').textContent = JSON.stringify(e.storageArea);
});
Additional.
1. Access to Web Storage from third-party IFrames is denied if the user has disabled third-party cookies
2. If the localStorage object does exist, there is still no guarantee that the localStorage API is actually available, as various browsers offer settings that disable localStorage. So a browser may support localStorage, but not make it available to the scripts on the page.
+ Storage 및 Storage API 지원하는지 확인하는 코드
function storageAvailable(type) {
var storage;
try {
storage = window[type];
var x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch(e) {
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
(storage && storage.length !== 0);
}
}
3. Service Worker는 주로 Cache API와 함께 쓰임
+ A service worker is a JavaScript file that is registered against a particular origin (web site, or part of a web site at a certain domain) when it is accessed by a browser. When registered, it can control pages available at that origin. It does this by sitting between a loaded page and the network and intercepting network requests aimed at that origin.
4. (다음에) Service Worker, IndexedDB, Cache API 자세히 공부 (Client Side Storage 사용할 필요가 있을 때)
Reference.
- https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria
- https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
- https://developer.mozilla.org/en-US/docs/Glossary/Cookie
- https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API
- https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage