Window localStorageProperty

JavaScript 存储对象JavaScript Storage Object

Example

Use localStorage to create a localStorage name/value pair, name="lastname" value="Smith", then retrieve the value of "lastname" and insert it into the element with id="result":

//Store localStorage.setItem("lastname", "Smith"); //Retrieve document.getElementById("result").innerHTML = localStorage.getItem("lastname");

Try it Yourself »

Definition and Usage

The localStorage and sessionStorage properties allow storing key/value pairs data in the browser.

localStorage is used to save data for the entire website for a long time; the saved data has no expiration time until manually deleted.

The localStorage property is read-only.

Tip:If you only want to save data in the current session, you can use thesessionStorageproperty. This data object temporarily saves data for the same window (or tab), and the data will be deleted after closing the window or tab.


Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Property
localStorage 4.0 8.0 3.5 4.0 11.5

Syntax

window.localStorage

Save data syntax:

localStorage.setItem("key", "value");

Read data syntax:

var lastname = localStorage.getItem("key");

Delete data syntax:

localStorage.removeItem("key");

Technical Details

Return Value: A Storage object.

More Examples

Example

The following example is used to record the number of times a button is clicked:

if (localStorage.clickcount) { localStorage.clickcount = Number(localStorage.clickcount) + 1; } else { localStorage.clickcount = 1; } document.getElementById("result").innerHTML = "You have clicked the button" + localStorage.clickcount + "times.";

Try it Yourself »

JavaScript 存储对象JavaScript Storage Object

Other Extensions