Skip to content
Advertisement

How to prevent a JS object, initialised in the home page and updated in other pages, to be initialized again when the user goes back to home

I guess I’m posing a silly question, if so thank you for your patience.

In my home.html I have

<script>
  document.addEventListener('DOMContentLoaded', function() {
    [...]
    var taskObj = {};
    localStorage.setItem('task_object', JSON.stringify(taskObj));
    [...]
  }
</script>

In another_page.html

<script>
  document.addEventListener('DOMContentLoaded', function() {
    [...]
    var taskObj_a = JSON.parse(localStorage.getItem('task_object') || '{}');
    taskObj_a.name = "a new task";
    localStorage.setItem('task_object', JSON.stringify(taskObj_a));     
    [...]
  }
</script>

When the user is redirected to home.html, the taskObj gets initialised again and I lose the “name” property set in another_page.html.

How can I avoid this and do not reset the taskObj?

Thank you for any help you can provide.

Advertisement

Answer

You can check if the item already exists in local storage and only set it if it doesnt.

if(!localStorage.getItem('task_object')) localStorage.setItem('{}')
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement