Search code examples
javascripthtmlcssgoogle-chrome-app

Chrome.storage for "new tab" chrome app; remembering checkboxes


I am quite new to programming but, eager to learn. I am trying to create an app which keeps tracks of goals (I didn't like the ones I found, so I want to make my own). Anyways, there are checkboxes to be checked and when I open a new tab at a later point, I want the checked boxes to be checked. Here is a little snippet from my code:

<label class="container">Drink 2 liters of water
  <input type="checkbox" checked="checked">
  <span class="checkmark"></span>
</label>

How can I use the chrome.storage function to remember that I clicked this box?. Thank you for your help!.


Solution

  • At a high level, you'll want to use chrome.storage to save your changes any time a checkbox is clicked - or when a button is clicked.

    If you're wanting to save every time the checkbox is clicked, you'll bind a listener to the change event of the checkboxes. Then, call chrome.storage to save.

    document.querySelectorAll('input[type="checkbox"]').forEach(elem=>{ //Get all input checkboxes
        elem.addEventListener('change',(event)=>{ //Add a change listener
            const key = event.target.name; //get the name value from the input element
            const value = event.target.checked; // has it been checked?
            chrome.storage.local.set({[key]: value}, ()=>  { //save it
                console.log('Value is set to ' + value);
            });
        })
    })
    

    Saving on button press will be similar. You'll bind a click listener to the button then in the callback, select all of the checkboxes and loop over them to save.

    When the page is loaded, you'll need to fetch all of the saved values, and set the check state.

    chrome.storage.local.get(['goal1','goal2'],(results)=>{ //Fetch goal1, goal2, goalN... from chrome.storage
        //.get returns a keyed object you can loop over.
        Object.keys(results).forEach((goal)=>{ 
            //Set the check state of each goal.
            document.querySelector(`input[name="${goal}"]`).checked = results[goal];
        })
    })