Unable to get localstorage variable on initialize

Hello

Project

I am trying to make a sound play when clicked on a button, this sound is saved using localstorage in a variable, but when I refresh the page the sound stops playing even though the variable is showing true in localstorage.

I used window.localstorage.getItem to get the boolean variable, if true the sound plays if false not but after refreshing the sound does not play even though the variable is true.

How can I make it so on refresh the sound continues playing if the variable is true? For some reason I can save variables and they work at realtime but when refreshing page it stops working even though the variable is saved.

Hi @nasjarta,

Yes indeed your local storage logic works as expected. What you are experiencing though is a browser behavior: to play a sound there is a requirement of a user interaction first.

So you do need a prompt, a button or someway have your user to interact with your game (mouse/touch input) for the sound to start playing.

Hello Leonidas

When I click the button it should turn green if on and red if off but those are also not saved in the localstorage. Perhaps I am using the getItem in a wrong way?

From what I learned if I test the localstorage variable with a if statement like:

if localstorage.getItem(sound) === true
enable sound
enable button

it works… but upon refreshing the page that value is not saved/initialized anymore.

@nasjarta I am not sure what is really going on after your refresh. Here is a debug screen shot from chrome. Each time I throw the switches it changes from true to false. When I refresh the page the true state seems to be in local storage but no reaction from the script. I see you doing the read in the initialization but there is no reaction. You can see in your code that this state is not handled. You handle to click states but you do not set the state of sound outside of the click events. You will have to read the local variable in initialize and then set the start state of the sound and the switch color first. Anything after will be handled by your onclick events.

I managed to solve it, I did not know localstorage makes the variable into a string so boolean true/false or a number does not work when you test it with conditions.

window.localStorage.getItem(‘sound’) === ‘true’ works when you turn the true into a string. Also if you use sound = 0 or sound = 1 for true and false you also need to turn the number into a string like ‘1’ etc.

After that I just called the enable and disable functions whether or not sound is true or false like Tirk suggested and as Leonidas suggested the sound plays once you interact with the scene and everything is working expectedly.

2 Likes