使用JavaScript,是否可以將頁面上的所有變量保存到本地存儲,然後在頁面刷新或重新加載時重新加載存儲的變量?我試圖將變量保存到本地存儲並在刷新頁面時加載它們。這是我到目前爲止已經試過:保存頁面上的所有JavaScript變量
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();
檢查了這一點:http://stackoverflow.com/questions/2226007/fetching-all-javascript-global-variables-in-a-page – Stegrex 2013-03-18 18:50:15
'for(prop in window){console.log(prop); }'現在你擁有了所有的變量。儘管跨瀏覽器兼容性不佳。 – Vinay 2013-03-18 18:50:58
@rid我想保存整個頁面的狀態,包括所有的JavaScript對象。 Stack Overflow已經有幾個關於保存網頁狀態的問題,但唯一討論的是保存DOM的狀態,並且他們都沒有討論保存JavaScript變量。 – 2013-03-18 18:51:50