-2

How can I keep the name of the User in the Home Page even when he navigates through other pages and then comes back to the Home Page again?
It's a simple Button through which, once clicked, a prompt asks for the Users name and displays a greeting.

For example:
Button: Who are you?
Prompt: Insert your name
Message Displayed: Hi [Name], welcome to the WebSite!

The problem is that when the User refresh the Home Page, the name disappear and he should click again the button.

Is there any way to keep the User Name in the whole session?

Thanks!

5
  • You can save it as cookie
    – Insax
    Commented Jan 18, 2018 at 10:55
  • You can use localStroage. Look at those localStorage Mozilla ref, localStorage w3schools ref Commented Jan 18, 2018 at 10:55
  • Try using local storage, developer.mozilla.org/en-US/docs/Web/API/Window/localStorage Commented Jan 18, 2018 at 10:55
  • 2
    what have you tried so far? This is not a write my code platform....you are saving the data into the browsers memory which will be released on reloading the page....thus you have to use the localStorage or even cookies
    – messerbill
    Commented Jan 18, 2018 at 10:55
  • Use localStorage if you need to store the name until the user clear the browser localStorage, use sessionStorage if you need to save it only during the user session.
    – LellisMoon
    Commented Jan 18, 2018 at 11:02

3 Answers 3

4

you can use localStorage like this

localStorage.setItem("username", "Smith");

to get the value from the localStorage use this

localStorage.getItem("username");
1
  • 1
    and to get the username value use localStorage.getItem("username")
    – messerbill
    Commented Jan 18, 2018 at 10:56
2

You Can Use sessionStroge like this.

 // Store
sessionStorage.setItem("lastname", "Smith");

// Retrieve
document.getElementById("result").innerHTML = sessionStorage.getItem("lastname"); 

You can Retrieve more information about this function w3schools:SessionStorage

0

@andrea-belluccia you can store it in a session, cookie or localstorage (you should check browser compatibility list for this). Then whenever you need to use the username you can.

Not the answer you're looking for? Browse other questions tagged or ask your own question.