0

I hope all is well! Just a quick question, I am newer to programming and have decided to make a chrome extension to exercise the ol' coding muscles (very small at this point) with vanilla JS. A part of this extension is to take a user input from the popup.html/popup.js file and store it in localStorage within the background.js.

I currently have the messaging set up from the popup.js to the background.js (but please let me know if you see anything to change). The background script seems to be the place to set up the .localStorage function - the only issue is that I haven't quite worked out how to store multiple variables in localStorage. However, I have been able to 'somewhat' figure out how to store single inputs until the user then inputs another value, and then the original is overwritten.

My ultimate goal for this part of the program is to be able to store as many user input values as possible (meaning each time that the 'submit' button is clicked, another value is added to local storage on top of what is already there).

Code is as follows:

popup.html:


<body>

  <div class="main_container">
    <form id="main_input">
      <h1>Please enter data</h1>
      <input id="name_textbox" />
      <button id="button1">OK</button>
    </form>

  </div>

  <script src="popup.js"></script>
</body>

popup.js:

    // User Input Field Values
function userInput(e) {
  //e.preventDefault();
  const inputValue = document.getElementById("name_textbox").value;
  //console.log(inputValue);
  chrome.runtime.sendMessage({popupVal: inputValue.trim(), msgType:'userInput'});
};

//Call User Input Value When Button On Popup is Clicked!

document.addEventListener("DOMContentLoaded", function() {

  chrome.storage.local.get(['popupObj'], function(result) {
    console.log('Value currently is ' + JSON.stringify(result));
    if (result && result.popupObj) 

document.getElementById("name_textbox").value=result.popupObj.popupVal || '';
  });

document.getElementById("button1").addEventListener("click", userInput);

});

background.js:

// Messaging From the popup! //


  chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log("background.js got a message")
        sendResponse("recieved");
        if (request.msgType==='userInput') {
            chrome.storage.local.set({key: request}, function() {
                localStorage.setItem("website", JSON.stringify(request));
                //Parse and then store as an array

              // Get the existing data
              var existing = localStorage.getItem('website');

              // Create an array
              // Otherwise, convert the localStorage string to an array
              existing = existing ? existing.split(',') : [];

              // Add new data to localStorage Array
              existing.push(JSON.stringify(request));

              // Save back to localStorage
              localStorage.setItem('website', existing.toString());

})
        }
    }
);

I read that storing the input in an array would be the most ideal option for multiple variables from a user? Any other suggestions?

Also, if there is anything at all that you would recommend changing on top of the original problem displayed, please let me know(:

hendiboi
  • 1
  • 1
  • A trivial way to store multiple strings is to use different keys: `localStorage.setItem('username', ...);` However if you want to store an array, call `JSON.stringify()` on it first.When loading it, you need to `JSON.parse()` the stored value to get back the array. –  Apr 14 '21 at 17:51
  • Duplicate: [Storing Objects in HTML5 localStorage](https://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage) –  Apr 14 '21 at 17:51
  • @ChrisG, Thank you so much for your response (: Would it be possible for the background.js to create its own keys each time the user inputs another value? – hendiboi Apr 14 '21 at 17:54
  • I don't understand; what do you mean by "create its own keys"? There's also a problem with your background.js logic; you're storing `request`, overwriting whatever was saved there, then read the exact same data you just stored back as `existing`. You probably want to 1) read 2) append new data 3) store instead? –  Apr 14 '21 at 17:58
  • Apologies, in terms of the 'creating its own keys' - Would it be possible for there to be a random word generator that would be able to create a new key each time the user input another value? Or am I just overcomplicating it?? ;-; – hendiboi Apr 14 '21 at 18:27
  • Ahhh! Okay, I see what you mean by storing `request` - thank you so much! – hendiboi Apr 14 '21 at 18:28
  • Random words are not useful here, because you'd need those exact words to read back the data. But like I said, you can easily store an object or array if you stringify it first. –  Apr 14 '21 at 18:47

0 Answers0