What is the best way to automatically log out a user when a different user logs in on the same browser?

Currently, I am encountering an issue where there are two separate dashboards for different types of users - one for admin and the other for a merchant. The problem arises when an admin logs in on one tab and then a merchant logs in on another tab in the same browser. Upon refreshing the admin page, I notice that the navbar meant for the merchant appears, while the rest of the page remains as the admin's dashboard content. This situation may be related to how I handle storing tokens in the localStorage.

I am seeking advice on how to properly log out the previously logged-in user if a new user logs in on the same browser session. Any suggestions or solutions would be greatly appreciated.

Answer №1

If Internet Explorer is not a concern, I recommend using the Broadcast Channel API in place of localStorage events

To start, initialize your broadcast channel and listen for events

const bc = new BroadcastChannel("your_channel_name")

bc.onmessage = (e) => {
  // Implement your business logic here
  // Access the data sent through the channel using e.data
}

When you are ready to trigger the event

bc.postMessage("your logout message");

Answer №2

If you find yourself needing to sign out from other tabs, consider utilizing local storage events to pass signals between multiple tabs.

Initiate a logout event on the previously active tabs:

localStorage.setItem('logout-event', 'logout' + Math.random());

Any other open tabs can listen for this event using the following code:

window.addEventListener('storage', function(event){
    if (event.key == 'logout-event') { 
        // Implement your code here
    }
});

Whenever a new tab is used to log in as a merchant, follow the above steps to ensure all other users are logged out.

Answer №3

If you're looking for a way to ensure that each tab or session has a unique token that is deleted when the tab is closed, consider using sessionStorage instead of localStorage

Answer №4

Consider using sessionStorage over localStorage for better security measures, check out this informative article:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to access the value of a variable within a loop inside a function and store it in a global variable?

I am struggling to retrieve the value of a variable after it has passed through a loop. I attempted to make it a global variable, but its value remains unchanged. Is there any way to achieve this? Below is my code snippet where I am attempting to access t ...

Numerous pop-up windows displaying a variety of distinct content in each one

While working on a website, I came across a helpful jQuery pop-up function that I found on Stack Overflow. The original post can be found here. I am trying to customize each pop-up box so they contain different content from the .pop1 and .pop2 divs (parag ...

Error: req.next is not a recognized function in node.js

I am completely stumped by this sudden issue that just appeared out of nowhere, with no changes in the code! TypeError: req.next is not a function The error is occurring at line 120. Here is the corresponding SQL query and the problematic line 120: // Set ...

The Angular Date Pipe is displaying an incorrect date after processing the initial date value

Utilizing Angular's date pipe within my Angular 2 application has been beneficial for formatting dates in a user-friendly manner. I have successfully integrated API dates, edited them, and saved the changes back to the API with ease. However, an issue ...

"Design the website with a WYSIWYG editor while preventing users from disrupting the page's

I am considering using an HTML WYSIWYG editor like CKEditor, but I am concerned about the possibility of users submitting HTML code that could alter the layout of the page when rendered. Here is a comparison between two posts: <p><b>This is m ...

Troubleshooting JSON Array Index Problems

I'm having trouble reaching index 3 in the array using the javascript options on my webpage. The final question "are you satisfied with your choice?" is not showing up for me. I'm not sure what I might be missing or doing incorrectly in this sit ...

Using formArray to dynamically populate data in Angular

I am attempting to showcase the values from a formarray that were previously added. component.ts this.companyForm = this.fb.group({ id: [], company_details: this.fb.group({ ---- }), company_ip_addresses: this.fb.array([this.fb.group({ ...

Top method for keeping track of most recent function outcome

Over time, I have become accustomed to utilizing the bind method to store the previous result of a function and keep track of it for future use. This allows me to easily concatenate or join the previous string with a new string without needing external var ...

Leveraging Express for delegating requests to an ADFS server

We are currently facing a challenge with authenticating to our on-premise ADFS 3.0 server. Our Angular application, a single-page app, needs to authenticate with the ADFS server. However, we are encountering CORS issues due to them not being on the same se ...

Clickable link in popup window using fancybox

When I try to use fancybox to open an iframe and scroll to an anchor tag, it works perfectly in IE but not consistently in other browsers. It stops at a different place than the anchor. I suspect the issue may be related to JavaScript based on information ...

What could be causing the issue with this basic THREE.js javascript particle system?

{/*I'm not sure if there are any errors in this code. I'm using the latest version of Chrome for testing purposes. Previously, I created a similar program that displayed a wireframe cube without any issues. It ran smoothly at that time. However, ...

Express fails to handle the POST request

Using ejs, express, nodeJS and mySQL has been great so far. However, I'm facing an error with this code: Cannot POST /search. I believe the index.ejs and app.js files are okay, but I suspect there's a problem with the searchRouter... app.js cons ...

What is the best way to sort through data if I enter more than three characters to filter the results?

Hey there, I'm currently in the process of developing a search bar that functions by displaying only filtered last names from a table when more than 3 characters are typed. The condition for filtering is empty. Here is the HTML code: <mat-form-fi ...

Using Selenium with JavaScript and Python to simulate key presses

Is there a way to simulate key presses as if typing on a keyboard? I am looking to programmatically click on an input element and then emulate the user typing by pressing keys. I prefer not to use XPath selectors combined with sendkeys or similar methods. ...

Creating an AI adversary for a simple Tic Tac Toe game board: a step-by-step guide

Being new to programming, I recently completed a basic Tic Tac Toe gameboard successfully. However, as I progress to the next phase of my assignment which involves implementing an AI opponent, I encountered several challenges. As a novice in programming, ...

What is the best way to automatically adjust the size of this HTML Menu to match the width of its

I am in the process of converting a Drupal 6 theme to Drupal 7 and I'm encountering some difficulties with this particular section. Below is the HTML code snippet: <ul id="nav" class=" scaling-active scaling-ready"> <li><a href="/demos ...

Exploring the power of Next.js dynamic routes connected to a Firestore collection

Currently seeking a solution to create a dynamic route that will display each document in a Firestore collection using Server-side Rendering. For instance, if there is a document named foo, it would be accessible at test.com/foo under the [doc] page compo ...

Utilizing Weather APIs to fetch JSON data

Trying to integrate with the Open Weather API: Check out this snippet of javascript code: $(document).ready(function() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { $(".ok").html("latitude: " + ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...

What is the best way to choose dropdown values by utilizing various button IDs?

I have four different vacation destinations and four buttons. I want to automatically select each destination separately when the corresponding button is clicked. <select class="aa" required="" name="f1990" {input.multiple}="" {input.size}="" id="f19 ...