LocalStorage does not retrieve values ​​after page refresh.

I am trying to check the html5 localStorage function. For some reason, when I try to get the value from the repository after the page is refreshed, I only get null returns. (If I try to get the values ​​in the same function in which I installed them, then I can restore them correctly).

One thing: the html / javascript that I am loading is being requested from the local disk (for example, I use the line: "file: /// C: /testLocalStore.html" to go to the file, instead of requesting it from the web server.This will cause local storage problems that i see?

(I would like to publish a complete code example, but I'm having formatting issues. I will send it shortly).

<html> <head> <title>test local storage</title> <base href="http://docs.jquery.com" /> <script src="http://code.jquery.com/jquery-1.3.js"></script> <script type="text/javascript"> function savestuff() { var existingData = localStorage.getItem("existingData"); if( existingData === undefined || existingData === null ) { // first time saving a map. existingData = $("#mapName").val(); } else { existingData = existingData + "," + $("#mapName").val(); } localStorage.setItem("existingData", existingData); // test is non-null here, it was properly retrieved. var test = localStorage.getItem("existingData"); } $(document).ready( function init() { // existing data is always null. var existingData = localStorage.getItem("existingData"); if( existingData !== null ) { var existingDataListHtml = existingData.split(","); existingDataListHtml = $.each(existingData, function(data) { return "<li>" + data + "<\/li>"; }); $("#existingData").html("<ul>" + existingDataListHtml + "<\/ul>"); } } ); </script> </head> <body> <form id="loadFromUser" onsubmit="savestuff();"> <input id="mapName" type="text"> <input type="submit" value="save"> </form> <div id="existingData"> </div> </body> </html> 
+4
source share
1 answer

Yes, downloading a file locally means that it has no source. Since localStorage uses a policy of the same origin to determine access to stored data, it is undefined, which happens when you use it with local files, and it is likely that it will not be saved.

You need to host your file on a web server in order to be of proper origin; you can just start Apache or any other local server and access it through localhost .

+9
source

All Articles