在瀏覽器內(nèi)直接存儲數(shù)據(jù)有很多好處,最主要的是快以及獨(dú)立于網(wǎng)絡(luò)去訪問“數(shù)據(jù)庫”,目前有四種方法(加上一個棄用),將數(shù)據(jù)存儲在客戶端:
- Cookies
- Local Storage
- Session Storage
- IndexedDB
- WebSQL (棄用)
Cookies
Cookies 是經(jīng)典的存儲數(shù)據(jù)方式,把簡單的字符串?dāng)?shù)據(jù)儲存在一個文檔里。通常情況下,Cookies從服務(wù)器被發(fā)送到客戶機(jī),然后儲存,并在后續(xù)請求中發(fā)送回服務(wù)器。這可以用于管理賬戶和跟蹤用戶信息。
另外,Cookies可以完全在客戶端存儲數(shù)據(jù),正因?yàn)槿绱?它們也被用于存儲通用數(shù)據(jù)如用戶偏好。
Cookies實(shí)現(xiàn)基本的CRUD
我們可以創(chuàng)建、讀取、更新和刪除cookie使用以下語法:
// Create
document.cookie = "user_name=Ire Aderinokun";
document.cookie = "user_age=25;max-age=31536000;secure";
// Read (All)
console.log( document.cookie );
// Update
document.cookie = "user_age=24;max-age=31536000;secure";
// Delete
document.cookie = "user_name=Ire Aderinokun;expires=Thu, 01 Jan 1970 00:00:01 GMT";
Cookies的優(yōu)點(diǎn)
- 可以用于與服務(wù)器通信
- 可以設(shè)置自動到期,而不必手動刪除
Cookies的缺點(diǎn)
- Cookie數(shù)量和長度有限制
- 只能儲存字符串
- 潛在的安全問題
- 自從網(wǎng)絡(luò)存儲API問世以來,它不再是客戶端存儲所推薦的方法
Support
在所有主要瀏覽器基本都支持
Local Storage
Local Storage是Web Storage API中的一種,是一種將鍵值數(shù)據(jù)存儲在瀏覽器中的API。它通過提供一個更加直觀和安全API來存儲簡單的數(shù)據(jù)在瀏覽器內(nèi),解決了Cookies中的問題。
盡管技術(shù)上我們只能將字符串存儲在本地存儲,但這可以存儲字符串化的JSON。跟Cookies比,這使我們能將更復(fù)雜的數(shù)據(jù)存儲在本地。
Local Storage實(shí)現(xiàn)基本的CRUD
我們可以創(chuàng)建、讀取、更新和刪除cookie使用以下語法:
// Create
const user = { name: 'Ire Aderinokun', age: 25 }
localStorage.setItem('user', JSON.stringify(user));
// Read (Single)
console.log( JSON.parse(localStorage.getItem('user')) )
// Update
const updatedUser = { name: 'Ire Aderinokun', age: 24 }
localStorage.setItem('user', JSON.stringify(updatedUser));
// Delete
localStorage.removeItem('user');
Local Storage 的優(yōu)點(diǎn)
- 提供了一個更簡單直觀的界面來存儲數(shù)據(jù)(跟cookie比)
- 本地存儲更安全(跟cookie比)
- 允許存儲更多的數(shù)據(jù)(跟cookie比)
Local Storage 的缺點(diǎn)
- 只允許存儲字符串
Support
Session Storage
Session Storage是第二種類型的網(wǎng)絡(luò)存儲API。和Local Storage很相似,不同之處在于 Local Storage 里面存儲的數(shù)據(jù)沒有過期時間設(shè)置,而存儲在 Session Storage 里面的數(shù)據(jù)在頁面會話結(jié)束時會被清除。
Session Storage實(shí)現(xiàn)基本的CRUD
我們可以創(chuàng)建、讀取、更新和刪除cookie使用以下語法:
// Create
const user = { name: 'Ire Aderinokun', age: 25 }
sessionStorage.setItem('user', JSON.stringify(user));
// Read (Single)
console.log( JSON.parse(sessionStorage.getItem('user')) )
// Update
const updatedUser = { name: 'Ire Aderinokun', age: 24 }
sessionStorage.setItem('user', JSON.stringify(updatedUser));
// Delete
sessionStorage.removeItem('user');
Session Storage優(yōu)缺點(diǎn)以及Support
跟Local Storage一樣
IndexedDB
IndexedDB是一個對瀏覽器存儲數(shù)據(jù)來說更加復(fù)雜但更加全面的解決方案。IndexedDB 是“一個為了能夠在客戶端存儲可觀數(shù)量的結(jié)構(gòu)化數(shù)據(jù),并且在這些數(shù)據(jù)上使用索引進(jìn)行高性能檢索的 API”(Mozilla)。這是一個基于javascript、面向?qū)ο蟆?shù)據(jù)庫使我們方便地存儲和檢索數(shù)據(jù)
Ire Aderinokun的文章中,詳細(xì)的說了如何使用IndexedDB創(chuàng)建一個離線應(yīng)用程序。
IndexedDB實(shí)現(xiàn)基本的CRUD
跟其他瀏覽器存儲方法比起來,使用IndexedDB更為復(fù)雜的。在我們可以創(chuàng)建/讀取/更新/刪除任何數(shù)據(jù)之前,我們需要首先打開數(shù)據(jù)庫,創(chuàng)建一個放數(shù)據(jù)的倉庫。
function OpenIDB() {
return idb.open('SampleDB', 1, function(upgradeDb) {
const users = upgradeDb.createObjectStore('users', {
keyPath: 'name'
});
});
}
創(chuàng)建(或更新)數(shù)據(jù),我們需要經(jīng)過以下步驟:
// 1. Open up the database
OpenIDB().then((db) => {
const dbStore = 'users';
// 2. Open a new read/write transaction with the store within the database
const transaction = db.transaction(dbStore, 'readwrite');
const store = transaction.objectStore(dbStore);
// 3. Add the data to the store
store.put({
name: 'Ire Aderinokun',
age: 25
});
// 4. Complete the transaction
return transaction.complete;
});
讀取數(shù)據(jù),我們需要經(jīng)過以下步驟:
// 1. Open up the database
OpenIDB().then((db) => {
const dbStore = 'users';
// 2. Open a new read-only transaction with the store within the database
const transaction = db.transaction(dbStore);
const store = transaction.objectStore(dbStore);
// 3. Return the data
return store.get('Ire Aderinokun');
}).then((item) => {
console.log(item);
})
刪除數(shù)據(jù),我們需要經(jīng)過以下步驟:
// 1. Open up the database
OpenIDB().then((db) => {
const dbStore = 'users';
// 2. Open a new read/write transaction with the store within the database
const transaction = db.transaction(dbStore, 'readwrite');
const store = transaction.objectStore(dbStore);
// 3. Delete the data corresponding to the passed key
store.delete('Ire Aderinokun');
// 4. Complete the transaction
return transaction.complete;
})
IndexedDB的優(yōu)點(diǎn)
- 可以處理更復(fù)雜的、結(jié)構(gòu)化的數(shù)據(jù)
- 在每個“數(shù)據(jù)庫”中,可以有多個“數(shù)據(jù)庫”和“表”
- 更多的存儲空間
- 控制我們?nèi)绾闻c之交互
IndexedDB的缺點(diǎn)
跟其他Web Storage API比起來太過復(fù)雜
Support
WebSQL
自2010年以來,W3C Web應(yīng)用程序規(guī)范工作組已經(jīng)停止對其維護(hù)。它不再是一個HTML規(guī)范的一部分,不應(yīng)使用。
比較
| Feature | Cookies | Local Storage | Session Storage | IndexedDB |
|---|---|---|---|---|
| 存儲空間 | ~4KB | ~5MB | ~5MB | Up to half of hard drive |
| 持久數(shù)據(jù)? | Yes | Yes | No | Yes |
| 數(shù)據(jù)類型 | String | String | String | Any structured data |
| 可檢索? | No | No | No | Yes |