Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Window localStorage property

Window localStorage property

JavaScript Storage Objects JavaScript Storage Object

Example

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

//

Storage

localStorage

.

setItem

(

"

lastname

"

,

"

Smith

"

)

;

//

Retrieval

document

.

getElementById

(

"

result

"

)

.

innerHTML

=

localStorage

.

getItem

(

"

lastname

"

)

;

Try it »


Definition and usage

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

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

The localStorage property is read-only.

Tip: If you only want to save data for the current session, you can use the sessionStorage property; this data object temporarily saves data for the same window (or tab), and the data is deleted after the window or tab is closed.


Browser support

The numbers in the table indicate the first browser version that supports this property.

property
localStorage 4.0 8.0 3.5 4.0 11.5

Syntax

window.localStorage

Syntax for saving data:

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

Syntax for reading data:

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

Syntax for deleting data:

localStorage.removeItem("key");


Technical Details

Return value: A storage object

More examples

Example

The following example counts 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 »

JavaScript Storage Objects JavaScript Storage Object