简体   繁体   中英

Clear local storage without reloading page

I'm trying to make a function that reset the score of some kind of a game and I have a problem.

Here is my function :

function resetScore() {
console.log("q " + q + " score " + score);
localStorage.setItem("q", 1);
localStorage.setItem("score", 0);
console.log("q " + q + " score " + score);
window.localStorage.clear();
console.log("q " + q + " score " + score);
setTimeout(function () {
    window.location.href = "quiz.xhtml";
}, 300);

As you can see I'm trying differents methods : The first one is to set the local storage to defaults values. The second is to simply clear the localStorage.

Here's the output of the console.log :

quiz.js:27 q 2 score 1

quiz.js:30 q 2 score 1

quiz.js:32 q 2 score 1

If I reload the page the console.log is :

quiz.js:27 q 1 score 0

quiz.js:30 q 1 score 0

quiz.js:32 q 1 score 0

The last console.log is not empty after the clear probably because I have a function that set up the local storage to default value if it's == null.

As you can see, after the clear I change the location.href to the page of the quiz (my reset function is in my home page). When I try on Chrome, my localStorage is set to the default when the quiz page load. But I'm doing this for an ePub and when I try this on iBooks, when I arrive on the quiz page, it still has the old values of the local storage. I need to go back to the home page and then to the quiz page to finally get a cleared localStorage.

Any idea to fix this ?

Edit :

Here's the function with the updated variables :

function resetScore() {
console.log("q " + q + " score " + score);
localStorage.setItem("q", 1);
q = parseInt(localStorage.getItem("q"), 10);
localStorage.setItem("score", 0);
score = parseInt(localStorage.getItem("score"), 10);
console.log("q " + q + " score " + score);
setTimeout(function () {
    window.location.href = "quiz.xhtml";
}, 300);

}

After many tests, I really think that the problem comes from iBooks. It seems that the localStorage is not shared between pages.

I also tried to pass the datas through URL parameters but iBooks seems to remove everything after the file extension.

I'll use my reset function inside the quiz page and everything should works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM