Use of localStorage and sessionStorage in HTML5

Source: Internet
Author: User
Tags sessionstorage

1,web Storage Introduction

The HTML5 Web Storage feature is to have the Web page save some information on the user's computer. Web Storage is divided into two categories:

(1) Local storage, corresponding to the Localstorage object. Used to save data for a long time, and any page in the site can access that data.
(2) session storage, corresponding to the Sessionstorage object. Used to temporarily save data for a window (or tab). Before a visitor closes a window or a tab, the data is present and is deleted by the browser after it is closed.

2, the similarities and differences of local storage of session memory

(1) The operation code for local storage and session storage is exactly the same, 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 below 5MB. This is associated with the domain where the site is located.

Examples of the use of 4,web storage
As an example of local storage (Localstorage), the session store is changed to a Sessionstorage object.

(1) Preservation and reading of text data


Localstorage.setitem ("user_name", "hangge.com");

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

(2) Save and read the value


Localstorage.setitem ("User_age", 100);

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

(3) Save and read the date


Create a Date Object
var today = new Date ();

Converts dates to text strings in the standard format of YYY/MM/DD and then saves 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 through JSON encoding conversions.
Json.stringify (): Converts any object with its data to the shape of text.
Json.parse (): Converts text back to an object.


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

Create a User Object
var user = new User ("Hangge", 100, "123456");
Save it in a convenient 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) to detect whether a key value is NULL, you can directly test whether equal to null

if (Localstorage.getitem ("user_name") = = null) {
Alert ("User name does not exist!") ");
}

(6) Delete data items

Localstorage.removeitem ("user_name");

(7) Clear all data

Localstorage.clear ();

(8) Find all data items

Without knowing the key name, you can use the key () method to get all the data items from local or session storage. The following example, clicking the button will list the data in all local storage.

<! DOCTYPE html>
<meta charset= "Utf-8" >
<title>find All items</title>

<script>
function Findallitems () {
Get the <ul> element used to save the data item
var itemList = document.getElementById ("ItemList");
Clear List
itemlist.innerhtml = "";

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

Use the above data to create a list item 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. That is, when a local storage or session store changes, other windows that view the same page or other pages in the same site trigger the Window.onstorage event.
Storage changes here mean adding new data items to the store, modifying existing data items, deleting data items, or clearing all data. An operation that does not have any effect on the store (holding the same value with the existing key name, or clearing the originally empty storage space) does not raise the Onstorage event.

The following opens two pages, modifies the data item in page 1, and Page 2 responds to the Onstorage event and reports the results.


---page1.html---

<! 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 () {
Gets the value in the two text box
var key = document.getElementById ("key"). Value;
var item = document.getElementById ("item"). Value;

To save a data item in the local store
(replace the old value with the new value if the key already exists with the same name)
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---


<! 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>

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.