I'm making a HTML5 idle game to practice JavaScript. I'm trying to save information in localStorage, and based on examples and tutorials I've found I'm doing everything right. However, it is not working. What am I doing wrong?
My code:
let gameData = {
money: 0
}
document.body.onkeyup = function(e) {
if (e.key == " " ||
e.code == "Space" ||
e.keyCode == 32
) {
money++;
refresh();
}
}
window.onload = (function() {
load();
refresh();
});
function refresh() {
gameData = {
money: money
}
upd(info);
}
window.onbeforeunload = save;
function save() {
localStorage.setItem("lastGameState", JSON.stringify(gameData))
}
function load() {
if (localStorage.length > 0) {
let lastLoad = JSON.parse(localStorage.getItem("lastGameState"));
gameData = {
money: lastLoad.money
}
}
}
I want to be able to add as many variables as I want (without exceeding localStorage limit) to the variable gameData, when the page closes it will save, and when the page loads it will load, or, if no load found, set to 0. The upd() function just loads the variables onto the screen.
EDIT: I got it to work, it turns out the problem I had was unrelated to localStorage, there was an error in the refresh function. Thank you