sessionStorage
sessionStorage
var user_id = "A1B2C3D4";
var user_data = {
name: "Tom Hanks",
occupation: "Actor",
favorite_color: "Blue"
// ...
};
sessionStorage.setItem(user_id, JSON.stringify(user_data));
localStorage
localStorage
var user_id = "A1B2C3D4";
var user_prefs = {
keep_me_logged_in: true,
start_page: "daily news"
// ...
};
localStorage.setItem(user_id, JSON.stringify(user_prefs));
localStorage.setItem(key, value)
, we can say localStorage[key]= value: localStorage["size"] = 6;
localStorage.setItem(key, value)
[or]
localStorage[key]= value
var user_id = "A1B2C3D4";
var user_data = { /* defaults */ };
var user_prefs = { /* defaults */ };
if (sessionStorage.getItem(user_id)) {
user_data = JSON.parse(sessionStorage.getItem(user_id));
}
if (localStorage.getItem(user_id)) {
user_prefs = JSON.parse(localStorage.getItem(user_id));
}
localStorage.getItem(key)
, we can simply say localStorage[key]
.var size = localStorage["size"];
Method | Description |
---|---|
removeItem(key) | To remove a specific item from Web Storage, we can use the removeItem method. We pass it the key we want to remove, and it will remove both the key and its value. |
clear() | To remove all data stored by our site on a user's computer, we can use the clear method. This will delete all keys and all values stored for our domain. |