Refreshing browser

window.location.reload() causes intended behavior in firefox but clears local storage on chrome. Any workaround ?

Hello @akshay1

call it with boolean true value as described here https://developer.mozilla.org/en-US/docs/Web/API/Location/reload
window.location.reload(true)

do not worry that parameter would be ignored with other browser

hope that help and have a nice day :slight_smile:

@justsomeone I think this is not what @akshay1 means. This boolean is Firefox specific to bypass the cache. The question is about localStorage on Chrome.

The described behavior in the original post seems very unlikely to me, since using this function does the same as reloading the page with F5. LocalStorage is designed to survive reloads and even closing the browser and reopening it.

To test it I created following HTML on my server. This code won’t work on CodePen or similar online editors as reload() gets ignored when called from an <iframe>

<html>
    <head>
        <title>Is localStorage emptied on reload?</title>
        <script>
            (function(){
              console.log('Content of localStorage at page load: ' + localStorage.getItem('text'));
              localStorage.setItem('text', 'Hello');
              console.log('Content of localStorage after setting it: ' + localStorage.getItem('text'));
              window.setTimeout(reloadFct, 3000);
              console.log('Reload in three seconds');
            })();

            function reloadFct(){
              window.location.reload();
            }
        </script>
    </head>
    <body>
    </body>
</html>

The code runs the function on page load, gets localStorage, sets localStorage, gets it again and then calls window.location.reload(); after three seconds.

The output from Firefox:
First run

Content of localStorage at page load: null
Content of localStorage after setting it: Hello
Reload in three seconds

After reloading

Content of localStorage at page load: Hello
Content of localStorage after setting it: Hello
Reload in three seconds

As expected the localStorage gets set in the first run and persists after reloading the page. When running the same code on Chrome I get the same output.

I think there is something else in your code @akshay1 that clears localStorage under certain circumstances.

I hope I understood your question correctly! :sweat_smile:
Maybe you could share some code that shows your described behavior.

Happy Coding!
Michael

time will tell what he meant :wink:

1 Like

If I’m wrong I had at least some programming practice
:grin: :grin: :grin:

1 Like

oh-yeah-cute :joy: :joy: :joy:

1 Like