I've recently created a small galiga like game recently using JavaScript and HTML5. I've run into a bit of trouble saving cookies, the cookie saves, but then resets itself when the page is refreshed, my code:

function saveScore() {
 var date = new Date();
  var expires = "; expires=" + date.toGMTString();
  document.cookie = "score=" + lvl + expires + "; path=/";

function loadScore() {

  var cookiearray = document.cookie.split(';');
  for (var i = 0; i < cookiearray.length; i++) {
    var name = cookiearray[i].split('=')[0];
    var value = cookiearray[i].split('=')[1];
    if (name == "score") {
      alert("Prior score found. Loading score...");
      lvl = value;

EDIT: It appears as though I made an error outside of the given code, and reset the level to zero, I fixed this, and everything works well, I apologize for any confusion caused.

  • \$\begingroup\$ Are you sure you're actually calling the loadScore function? \$\endgroup\$
    – Tetrad
    Jan 23, 2013 at 18:51
  • \$\begingroup\$ Could your JavaScript loadScore() function be throwing an exception? I would think that you can't get the score because of an 'index out of bounds' exception when you use "split('=')[0]" try checking the make sure that the '=' char is there, also please let us know if the alert is being executed. \$\endgroup\$ Jan 23, 2013 at 18:53
  • \$\begingroup\$ The alert is never being executed even though I run loadScore right after the variable lvl is defined. \$\endgroup\$
    – Dylan Katz
    Jan 23, 2013 at 18:54
  • \$\begingroup\$ definitely check for an exception. alert yourself with the unsplit cookiearray element in the for loop so you can check exactly what values you are receiving and possibly where things are blowing up. If it is like I thought with the 'out of bounds' exception, then you can easily fix the method by checking if the string contains a '=' char. \$\endgroup\$ Jan 23, 2013 at 19:05
  • \$\begingroup\$ Ok, Sorry, it appears as though the alert is working, and I also added alerts for the value of score, and it comes out correctly, it seems as though the level is somehow resetting itself, I've also attempted to set the player health to the level, but it seems to stay the same, so it does not appear to be a problem with the lvl variable. \$\endgroup\$
    – Dylan Katz
    Jan 23, 2013 at 19:43

1 Answer 1

ddocument.cookie = "score=" + lvl + expires + "; path=/";

One d too much in document. Is that typo also in your real code?

When I might suggest an alternative solution: Why don't you use HTML5 localStorage? As long as you don't have any server-sided programming which needs persistent data, it's a much superior solution.

When you already require that the users browser supports canvas you don't have to worry about browser support for localStorage. Almost every browser which supports canvas also supports localstorage.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .