Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localStorage doesn't retrieve values after page refresh

Tags:

html

I'm trying to test out html5 localStorage feature. For some reason, whenever I try to retrieve a value from storage after refreshing the page, I only get null values returned. (If I try retrieving the values in the same function that I set them in, then I can properly retrieve them).

One thing: the html/javascript that I'm loading is being requested from the local disk (for example, I'm using the string: "file:///C:/testLocalStore.html" to browse to the file, instead of requesting it from a web server. Would this cause the localStore problems that I'm seeing?

(I'd like to post the full code example, but I'm having some problems with the formatting. I'll post 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>
like image 877
brad Avatar asked Jan 21 '23 10:01

brad


1 Answers

Yes, loading the file locally means that it doesn't have an origin. Since localStorage is uses the same-origin policy to determine access to stored data, it is undefined what happens when you use it with local files, and likely that it won't be persisted.

You will need to host your file on a web server in order to have a proper origin; you can just run Apache or any other server locally and access it via localhost.

like image 184
Brian Campbell Avatar answered Feb 01 '23 20:02

Brian Campbell