Create a localStorage name/value pair with name="lastname"
and value="Smith",
Retrieve the value of "lastname"
and insert it into the element with id="result":
<!DOCTYPE html> <html> <body> <div id="result"></div> <script> // Check browser support if (typeof(Storage) !== "undefined") { // Store/*from w w w . j av a 2 s .c o m*/ localStorage.setItem("lastname", "Smith"); // Retrieve document.getElementById("result").innerHTML = localStorage.getItem("lastname"); } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage..."; } </script> </body> </html>
The localStorage and sessionStorage properties allow to save key/value pairs in a web browser.
The localStorage object stores data with no expiration date.
The data will not be deleted when the browser is closed.
The localStorage property is read-only.
The sessionStorage property which stores data for one session. Data is lost when the browser tab is closed.
to save data to localStorage:
localStorage.setItem("key", "value");
to read data from localStorage:
var lastname = localStorage.getItem("key");
ro remove data from localStorage:
localStorage.removeItem("key");