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(: