What is the best way to save a user's changes to a HTML app?

Viewed 71

I am currently working on this website https://idle-chicken.glitch.me/chicken.html and I am trying to save the user's progress(the items they purchased, their eggs, cost, etc.) Right now the number of eggs as a cookie, but I was wondering if there is a way for me to save all of the changes both to the JavaScript and the HTML. I am fine using jQuery Javascript or AJAX (I think that is how you do it)?

This is what I am doing right now

function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function checkCookie() {
  var cookie = getCookie("eggs");
  if (cookie != "") {
     eggs = cookie;
  } else {
      setCookie("eggs", eggs, 365);
  }
}

$(window).bind("beforeunload", function() {
  setCookie("eggs", eggs, 365);
  if (notThis) {
    return "Do you want to exit this page?";
  }
});

and then I do this for the HTML

<body onload="checkCookie()">
1 Answers

I'm actually working on a similar task now, myself. Cookies are rather limited. I'd suggest storing all of that information in either the window.localStorage or window.sessionStorage objects, depending on how permanent you want the data to be stored on the user's device. This is a great way to save all sorts of data whether it be strings, numbers, JSON, or escaped HTML code.

Digital Ocean has a great article on it here: https://www.digitalocean.com/community/tutorials/js-introduction-localstorage-sessionstorage

Related