admin管理员组

文章数量:1401298

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction();">Fav Number</button>
<div id="result"></div>
  <!--This code works on chrome-->

<script>
function myFunction() {
// Check browser support
if (typeof(Storage) !== "undefined") {
    // Store
	var a = prompt("fav number");
    localStorage.setItem("lastname", a);
    // Retrieve
    document.getElementById("result").innerHTML = localStorage.getItem("lastname");
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
</script>

</body>
</html>

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction();">Fav Number</button>
<div id="result"></div>
  <!--This code works on chrome-->

<script>
function myFunction() {
// Check browser support
if (typeof(Storage) !== "undefined") {
    // Store
	var a = prompt("fav number");
    localStorage.setItem("lastname", a);
    // Retrieve
    document.getElementById("result").innerHTML = localStorage.getItem("lastname");
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
</script>

</body>
</html>

hello,

is it possible to get local storage items back when you refresh the page? and if so, how?

Thanks

Dylan,

Share Improve this question asked Feb 7, 2017 at 9:51 Dylan StrijkerDylan Strijker 131 gold badge1 silver badge3 bronze badges 2
  • developer.mozilla/en/docs/Web/API/Window/localStorage – Kiksen Commented Feb 7, 2017 at 9:53
  • I always use sessionStorage.. I would remend using this. – Ashish Bahl Commented Feb 7, 2017 at 9:59
Add a ment  | 

1 Answer 1

Reset to default 2

Getting and setting localStoragedata. In following example the data to set is a Object (which is handled by JSON.stringify). If need to persist a string / intthere is no need in using JSON.stringify.

var dataObject = { 'item1': 1, 'item2': 2, 'item3': 3 };

// Set localStorage item
localStorage.setItem('dataObject', JSON.stringify(dataObject));

// Retrieve the object from localStorage
var retrievedObject = localStorage.getItem('dataObject');

// console.log retrieved item
console.log('retrieved data Object: ', JSON.parse(retrievedObject));

By getting localStorage data when needed, there no need to handle the page refresh part. The localStorage data is fetched when needed by application functions and logics.

本文标签: javascriptlocal storage items after refresh pageStack Overflow