Web Storage usage explained (local storage, session store)

Source: Internet
Author: User
Tags sessionstorage

Web Storage usage explained (local storage, session store)
1,web Storage Introduction
The HTML5 Web Storage feature is for Web pages to hold some information on the user's computer. Web Storage is also divided into two types:
(1) Local storage, corresponding to the Localstorage object. For long-term preservation of the site's data, and any page within the station can access the data.
(2) session storage, corresponding to the Sessionstorage object. Used to temporarily save data for a window (or tab). The data is present before the visitor closes the window or tab, and is deleted by the browser when it is closed.

2, the similarities and differences of local storage session storage
(1) The operating code for local and session storage is identical, and they differ only in the life of the data.
(2) Local storage is primarily used to save data that visitors will see in the future.
(3) session storage is used to save data that needs to be passed from one page to the next.

3,web Storage Capacity Limits
Most browsers limit local storage to less than 5MB. This is associated with the domain where the site resides.

Examples of use of 4,web storage
The following is an example of local storage (Localstorage), where session storage is changed to Sessionstorage objects.

(1) Saving and reading of text data
1
2
3
Localstorage.setitem ("user_name", "hangge.com");

var userName = Localstorage.getitem ("user_name");

(2) Saving and reading of values
1

Localstorage.setitem ("User_age", 100);

var userage = number (Localstorage.getitem ("User_age"));

(3) Date Saving and reading
1


Create Date Object
var today = new Date ();

Converts a date to a text string in the standard format of YYY/MM/DD, and then saves it as text
var todaystring = today.getfullyear () + "/" + today.getmonth () + "/" + today.getdate ();
Localstorage.setitem ("session_started", todaystring);

Gets the date text and creates a new Date object based on the text
var newtoday = new Date (Localstorage.getitem ("session_started"));
Alert (Newtoday.getfullyear ());

(4) Saving and reading of custom objects
The save and read of objects can be implemented by JSON-encoded transformations.
Json.stringify (): Converts any object, along with its data, to a text-shaped shape.
Json.parse (): Converts the text back to the object.
1

Customizing a User Object
function User (n, a, t) {
THIS.name = n;
This.age = A;
This.telephone = t;
}

Creating a User Object
var user = new User ("Hangge", 100, "123456");
Save it as a handy JSON format
Sessionstorage.setitem ("User", json.stringify (user));

Jump page
window.location = "hangge.html";

Turn JSON text back to the original object
var user2 = Json.parse (Sessionstorage.getitem ("user"));
alert (user2.name);

(5) Check whether the value of a key is empty, you can directly test whether it is equal to null
1
3
if (Localstorage.getitem ("user_name") = = null) {
Alert ("User name does not exist!") ");
}

(6) Deleting data items
1
Localstorage.removeitem ("user_name");

(7) Clear all data
1
Localstorage.clear ();

(8) To find all data items
without knowing the key name, you can use the key () method to get all the data items from the local or session store. In the following example, the data in all local storage is listed when the button is clicked.
Original: Html5-web storage usage explained (local storage, session store)
1
<! DOCTYPE html>
<meta charset= "Utf-8";
<title>find all Items </title>

<script>
Function Findallitems () {
//Get <ul> element to hold data item
var itemList = document.getElementById ("ItemList");
//Clear list
itemlist.innerhtml = "";

//Traverse all data Items
for (var i=0; i<localstorage.length; i++) {
//Get key of current position data item
var key = Localstorage.key (i);
Gets the data value saved with the key
var item = Localstorage.getitem (key);

//Create a list item with the above data to add to the page
var newitem = document.createelement ("li");
newitem.innerhtml = key + ":" + item;
Itemlist.appendchild (NewItem);
}
}
</script>

<body>
<button onclick= findallitems () > Export all local storage data </ Button>
<ul id= "itemList";
</ul>
</body>

5, responding to storage changes
Web Storage also provides a mechanism for us to communicate between different browser windows. This means that when local storage or session storage changes, other windows that view the same page or other pages in the same site will trigger the Window.onstorage event.
The change in storage refers to the addition of new data items to the store, modification of existing data items, deletion of data items, or elimination of all data. The Onstorage event is not raised for operations that do not have any effect on storage (either by saving the same value with an existing key name, or by clearing a storage space that is otherwise empty).

The following opens two pages at a time, modifies the data item in page 1, and Page 2 responds to the Onstorage event and reports the result.
Original: Html5-web storage usage explained (local storage, session storage)

Original: Html5-web storage usage explained (local storage, session storage)

---page1.html---
46
<! DOCTYPE html>
<meta charset= "Utf-8" >
<title>Page1</title>
<style>
fieldset {
margin-bottom:15px;
padding:10px;
}

Label {
width:40px;
Display:inline-block;
margin:6px;
}

Input {
margin-top:12px;
width:200px;
}
</style>
<script>
function AddValue () {
Get the value in two text boxes
var key = document.getElementById ("key"). Value;
var item = document.getElementById ("item"). Value;

Saving data items in local storage
(replace the old value with the new value if the key with the same name already exists)
Localstorage.setitem (key, item);
}
</script>

<body>
<fieldset>
<legend>local storage</legend>
<label for= "Key" >Key:</label>
<input id= "Key" ><br>
<label for= "Item" >Value:</label>
<input id= "Item" >
<br>
<button onclick= "AddValue ()" >Add</button>
</fieldset>
</body>
---page2.html---
1
2
<! DOCTYPE html>
<meta charset= "Utf-8" >
<title>Page2</title>
<style>
#updateMessage {
Font-weight:bold;
}
</style>
<script>
Window.onload = function () {
Alert (1);
Add a handler function to the Window.onstorage event
Window.addeventlistener ("Storage", storagechanged, false);
};

function Storagechanged (e) {
Alert (2);
var message = document.getElementById ("Updatemessage");
message.innerhtml = "Local storage updated.";
message.innerhtml + = "<br>key:" + e.key;
message.innerhtml + = "<br>old Value:" + e.oldvalue;
message.innerhtml + = "<br>new Value:" + e.newvalue;
message.innerhtml + = "<br>url:" + e.url;
}
</script>
<body>
<div id= "Updatemessage" >no updates yet.</div>
</body>

Web Storage usage explained (local storage, session store)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.