HTML5 Local Storage item not being saved correclty

2019-06-10 18:13发布

问题:

I'm trying to save a value from a url query string that needs to be inserted into forms an any page the user navigates to, but so far I can't get the code to work past the initial landing page that contains the original query string.

Using this method to grab the query string value for X, and save it in localStorage for key Xcode:

<script>
var field = 'x';
var url = window.location.href;
if(url.indexOf('?' + field + '=') != -1) {

    function getUrlVars()
    {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

var user_code = getUrlVars()["x"];

if (localStorage) { 
   localStorage.setItem("xcode",user_code);
}

</script>

Then use this to insert it into the "value" attribute of any inputs withe class .xcode-field:

<script>
window.onload = function() {
    var thecode = localStorage.getItem("xcode");
     if (thecode != "undefined" && thecode != "null") {
      $(".xcode-field").attr("value",thecode);
} else {
      $(".xcode-field").attr("value","default");
}
}
</script>

If the item is not in LocalStorage, the default value should be inserted (or it should just do nothing, but not sure how to set that.)

My problem now is that this works on the page the user lands ( example.com/?x=1234 ) but when they navigate to any other pages, the value in the form is populated by "undefined". So neither is the query string value being properly stored nor does the else statement above work to insert "default". Any idea what I'm doing wrong here? Thank you!

Fiddle (but does not seem to work on there): http://jsfiddle.net/08suhbuk/

UPDATE: Finally figured it out! The LocalStorage was being reset on consecutive pages because the initial query string parsing and setItem would be repeated on every page and override the original value. I solved it by adding the following code to check for the presence of a query string around the first script:

var field = 'x';
var url = window.location.href;
if(url.indexOf('?' + field + '=') != -1) {

Final working code edited in.