2017-02-19 107 views
0

我寫了下面的腳本,並在控制檯運行它:如何將數據保存在localStorage中,我們將關閉瀏覽器?

var data = "dfsfds"; 
localStorage.getItem("data"); 
localStorage.setItem("data",data); 

然後,我關閉了broswer並重新打開它。當我輸入控制檯時:

localStorage.getItem("data"); 

我得到了「未定義」。

我認爲本地存儲應該在瀏覽器關閉後留在瀏覽器內存中。爲什麼不在這裏發生?

+0

你可以使用cookies爲好。 – Aloso

回答

3

您必須從從域加載的頁面運行此代碼。這意味着代碼必須在通過HTTP訪問的服務器上運行。這就是瀏覽器如何讓一個網站的localStorage數據與另一個網站分開。

下面的代碼顯示瞭如何做到這一點,但由於沙箱,它不會在Stack Overflow片段環境中工作。你可以看到一個工作版本here。填寫你的名字,然後點擊按鈕,複製URL,關閉瀏覽器,然後打開一個新的瀏覽器選項卡並返回頁面。

window.addEventListener("DOMContentLoaded", function(){ 
 

 
    var g1 = document.querySelector(".greeting1"); 
 
    var g2 = document.querySelector(".greeting2"); 
 
    
 
    // Check localStorage to see if the user has already told us their name 
 
    var name = localStorage.getItem("name"); 
 
    if(name){ 
 
    // Put the name into the <span> 
 
    document.getElementById("user").textContent = name; 
 
    
 
    // Hide the initial greeting and show the welcome back greeting 
 
    g1.classList.add("hide"); 
 
    g2.classList.remove("hide"); 
 

 
    } else { 
 
    // Show the initial greeting and hide the welcome back greeting 
 
    g1.classList.remove("hide"); 
 
    g2.classList.add("hide"); 
 
    } 
 

 
    // Set up a click event handler for the button 
 
    var btn = document.querySelector("button"); 
 
    btn.addEventListener("click", function(){ 
 
    // When the button is clicked, save the value from the textbox into localStorage 
 
    localStorage.setItem("name", document.querySelector("input").value); 
 
    }); 
 
    
 
});
.hide { display:none; }
<div class="greetings"> 
 
    <div class="greeting1"> 
 
    <p>Please enter your name: <input type="text"><button>Save my name</button></p> 
 
    </div> 
 
    <div class="greeting2 hide"> 
 
    <p>Welcome back <span id="user"></span></p> 
 
    </div> 
 
</div>

相關問題