问题
Using JavaScript, is it possible to save all variables on a page to local storage, and then re-load the stored variables when the page is refreshed or reloaded? I'm trying to save the variables to local storage and load them when the page is refreshed. This is what I've tried so far:
http://jsfiddle.net/jZVWk/1/
function saveAllVariables(){
//save all variables on the page to local storage
}
function loadAllVariables(){
//load all variables on the page from local storage, and re-create them using their original names
}
loadAllVariables(); //load all variables that were previously stored
if(typeof theName == "undefined"){
var theName = prompt("Please enter your name:","Your name");
}
if(typeof currentTime == "undefined"){
var currentTime = new Date();
}
document.body.innerHTML += "Time last visited: " + currentTime + "<br />";
document.body.innerHTML += "Your name : " + theName + "<br />";
var currentTime = new Date();
回答1:
Sort of. If the variables you care about are all global, and don't depend on any non global data, you can check out this question: Fetching all (javascript) global variables in a page (Thanks Stegrex)
But that's not the whole story. In JS lots of data is persisted in hidden scopes. This has 2 problems:
- The objects may not be accessible from the global scope.
- Functions may depend on data in the scope in which they were created, but that isn't accessible from the global scope.
For instance:
var globalThing = 'global';
var makeCounter = function() {
var count = 0;
return {
increment: function() { count++; },
getCount: function() { return count; }
}
}
var counter = makeCounter();
counter.increment();
alert(counter.getCount());
The state of this code is now impossible to literally save and reconstitute. count
is in a closure, hidden and inaccessible from the global scope. Without a more intelligent way to inspect and save the internal state of your objects, you can't preserve this structure.
So perhaps this isn't the approach you want to take. I'd bet good money there is a far cleaner way to do what you want. So the question becomes: why do you need this? And what are you trying to do?
I'd strongly suggest that you explicitly save just the data you need, and do not try to brute force save the entire universe.
In your case, that would be simply:
function saveOnlyImportantVaiables() {
localStorage.theName = theName;
localStorage.currentTime = currentTime;
}
来源:https://stackoverflow.com/questions/15484532/save-all-javascript-variables-on-a-page