How to make Web Storage persistent in Cordova using JS?

Posted by ett on Stack Overflow See other posts from Stack Overflow or by ett
Published on 2014-05-31T20:51:01Z Indexed on 2014/05/31 21:26 UTC
Read the original article Hit count: 258

I have a small quiz app, which is a cross-platform mobile app, that I plan for it to run on Android, iOS, and WP8. I want to store a local highscore, where it will keep track how many points the user had, and if he/she does better than the already stored highscore, update the current highscore. Though, I want the highscore to be persistent, what I mean is, every time the user opens the app I want the last highscore to be present and it to be compared with the new quiz score. Meaning, I don't want the highscore to be deleted after each time the app is closed. I also want for the first time when the app is ran, the highscore to be set to 0, so obviously the first time the user finishes the quiz gets a new highscore.

I have those codes so far:

scoredb.js

// Wait for device API libraries to load
document.addEventListener("deviceready", initScoreDB, false);

// Device APIs are available
function initScoreDB() {
    window.localStorage.setItem("score", 0);
    highscore = window.localStorage.getItem("score");
}

main.js

var correct = 0;
var highscore;

// In between I have some code that keeps incrementing
// correct variable for each correct answer.
if (correct > highscore) {
                window.localStorage.setItem("score", correct);
                highscore = correct;
}

It does seem to work okay once the app is started. I did the quiz three times, in the simulator, and it keeps the score as it should. Though, each time I open the app, highscore is reseted to 0. I guess it is due to the fact that I call initScoreDB when the device is ready, and I initialize the score to 0 there and give that value to highscore. Can someone help me to initialize the score to 0 only when the app is ran for the first time, and all the other times to keep the latest highscore as the current highscore and compare it each time with the score that is achieved when the quiz is finished. If someone can help me, I would be glad.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about cordova