I'm very new to JS and have been following along with a quick tutorial for building a Chrome Extension. The extension generates a very simple welcome message to a user, once they've supplied their name via an input.
My understanding is this input name then gets saved to localStorage and as such the name + message is carried over to any new tab you open, similar to how the 'Momentum' extension works, I think.
At the moment, however, it seems I have to add a new name each time a new tab is opened, which doesn't seem right. I've always checked in the Application panel and can see the 'receivedName' is showing as undefined.
As I say, I'm quite new to learning JS, so I'm not sure if this is the expected behaviour and that you will have to enter your name each time, or I've missed something in the code.
// declares empty variable for username
var userName;
// function toggles the username input from displaying
function openSettings() {
document.getElementById("settings").classList.toggle("settings-open");
}
// stores the users name in local storage
function saveName() {
localStorage.setItem("receivedName", userName);
// retrives username from storage
var userName = localStorage.getItem("receivedName");
// if no name is entered then placeholder of friend is used
if (userName == null) {
userName = "friend";
}
}
// function runs each time a username updates their name
function changeName() {
if ((userName = document.getElementById("name-input").value == "")) {
userName = "friend";
} else {
userName = document.getElementById("name-input").value;
}
saveName();
getGreeting();
}
//function for the h2 greeting. Executes when the page is refreshed or when changeName runs
function getGreeting() {
document.getElementById(
"greeting"
).innerHTML = `Hello ${userName}. Enjoy your day!`;
}
// EVENT LISTENERS
document
.getElementById("settings-button")
.addEventListener("click", openSettings);
//Every time someone submits the changeName fnc runs
document.getElementById("name-form").addEventListener("submit", function (e) {
e.preventDefault();
changeName();
});
Thanks