So I have a GitHub page with a game on it, and I want to use localStorage to store user’s scores. However, this has caused some problem with the script because the game no longer works and things that should be printed on the screen aren’t printed (using document.write). This is the code which I added:
if (localStorage.getItem("highscore") !=== null) {
document.write("Your highscore is " + localStorage.getItem("highscore"));
}
else {
document.write("Play the game to set a highscore");
}
//game code
if (testhighscore && localStorage.getItem("highscore") > myGameArea.frameNo) {
localStorage.setItem("highscore", myGameArea.frameNo)
document.write("Your highscore is now " + localStorage.getItem("highscore"))
}
How (if possible) can I fix this, and why does it happen?
Have you tried using sessionStorage instead? My app worked locally but it broke once deployed to github pages when I was using localStorage. My problem was that during testing, a value from a previous session was persisted to the app from storage. Using localStorage hid a bug in my code that I was able to fix after switching to sessionStorage and fixing my logic.
Formally, the difference is:
sessionStorage maintains a separate storage area for each given
origin that's available for the duration of the page session (as long
as the browser is open, including page reloads and restores).
localStorage does the same thing, but persists even when the browser is closed and reopened. MDN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With