Reference: http://www.htmldog.com/guides/javascript/advanced/localstorage/
When building more complex JavaScript applications, it’s very useful to be able to store information in the browser, so that the information can be shared across different pages.
Unlike cookies, local storage can only be read client-side - that is, by the browser and your JavaScript. If you want to share some data with a server, cookies may be a better option.
Set Item: localStorage.setItem('name', 'tom');
Example:
<html>
<head>
<title>Javascript Local Storage</title>
</head>
<body>
Give some input to store on local: <input type="text" id="input_msg" />   <input type="button" value="Submit" id="submit" onclick="saveOnLocal();" />
<br /><br />
Data from local: <span id="local_data"></span>
</body>
</html>
<script type="text/javascript">
function saveOnLocal()
{
var data=document.getElementById('input_msg').value;
localStorage.setItem('input_msg',data); //Set local storage
document.getElementById('local_data').innerHTML=localStorage.getItem('input_msg'); //Get local storage
localStorage.removeItem('input_msg'); //Clear specific local storage item
//localStorage.clear(); //Clear all local storage item
}
</script>
When building more complex JavaScript applications, it’s very useful to be able to store information in the browser, so that the information can be shared across different pages.
Unlike cookies, local storage can only be read client-side - that is, by the browser and your JavaScript. If you want to share some data with a server, cookies may be a better option.
Set Item: localStorage.setItem('name', 'tom');
Get Item: var name = localStorage.getItem('name');Example:
<html>
<head>
<title>Javascript Local Storage</title>
</head>
<body>
Give some input to store on local: <input type="text" id="input_msg" />   <input type="button" value="Submit" id="submit" onclick="saveOnLocal();" />
<br /><br />
Data from local: <span id="local_data"></span>
</body>
</html>
<script type="text/javascript">
function saveOnLocal()
{
var data=document.getElementById('input_msg').value;
localStorage.setItem('input_msg',data); //Set local storage
document.getElementById('local_data').innerHTML=localStorage.getItem('input_msg'); //Get local storage
localStorage.removeItem('input_msg'); //Clear specific local storage item
//localStorage.clear(); //Clear all local storage item
</script>
You can only save string using javascript local storage, use JSON for save array.
Example:
<script type="text/javascript">
</script>
<script type="text/javascript">
localStorage.setItem('name', JSON.stringify(your_array));
var user = JSON.parse(localStorage.getItem('name'));
</script>
Browser support for local storage is not 100% but it’s pretty good - you
can expect it to work in all modern browsers, IE 8 and above, and in
most mobile browsers too. And the storage size depends on the browser.
No comments:
Post a Comment