简体   繁体   中英

How do I maintain a button state across pages

In my project I'm using normal HTML for front-end and Django for back-end. There I have a login system.


I have two questions on that:

  1. When the user logs-in how do I detect it in HTML and change the Login button to show Log out.

  2. How do I maintain this changes across pages. So, that when I navigate to a different page after login it keeps showing the logout button.


Don't suggest me react. I have come a long way from where I can change my technology stack for this project.

You can use localStorage to save as a variable such as isLoggedIn that will persist across different routes and on refreshes. Example when you want to save

window.localStorage.set("isLoggedIn", "true");

When you want to check if they're logged in

const isLoggedIn = window.localStorage.get("isLoggedIn");

You can use Session Storage for storing the login state of the page for the current session only.

sessionStorage.setItem('isLoggedIn', true);

Fetching the Login Status while displaying the button :

var isLoggedIn = sessionStorage.getItem('isLoggedIn');

if(isLoggedIn) {
   //code for logged-in users
}

Points to know about Session Storage :

  • A page session lasts as long as the browser is open, and survives over page reloads and restores.
  • Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
  • Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window.
  • Closing a tab/window ends the session and clears objects in sessionStorage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM