Not allowing multiple sessions to open in an web application

This was an enigma for me to be honest.

The problem was to limit the user to use only one session of the application in one browser.

The solution to this problem is the one that works for you.

There are various people who has given suggestions that may work for you.

Solution 1: https://stackoverflow.com/questions/11008177/stop-people-having-my-website-loaded-on-multiple-tabs — This was a good resource.

The answer https://stackoverflow.com/a/45717724/10120165 — helped me shape up the solution for me. I modified the code and made it work for fixing my issue.

I am adding my solution here for this. It worked but I did not go with it because it seemed little complicated to the people I did review with.

Code —

Since the application loads with index.html, I called the function checkForMultipleTab there.

Also, the other change was added in window.unload method where the following code was added:

if(localStorage.getItem(‘local-storage-tab-guid’) === sessionStorage.getItem(‘session-storage-tab-guid’)) {
    localStorage.clear();
}

Or you could also add:

localStorage.removeItem(localStorageTabKey);

Solution 2: Using the cookie approach, the logic was essentially the same thing that we did with localStorage and sessionStorage but I felt it was more clean and understandable.

The reference of which was taken from: https://stackoverflow.com/a/42514062/10120165 https://stackoverflow.com/a/37209703/10120165 https://stackoverflow.com/a/33769481/10120165 https://stackoverflow.com/questions/10593013/delete-cookie-by-name

Cookie: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

I did not use the library though.

My solution for using cookie was:

In window.onunload:

if(document.cookie.includes(‘tabNumber=1’)){
    document.cookie = ‘tabNumber=0’;
}

The line window.open(window.location, ‘_self’) is definitely a hack, but it achieves what I want to implement and does not hurt as far as I understand.

Note: I could not go with the solution for the back-end because our application is not designed that way where I could in any way check if the user is logged in or not and I still believe that that would be the ideal solution to go ahead with.

There were also ideas of using libraries shared in the answers like: https://stackoverflow.com/a/62231610/10120165 https://blog.arnellebalane.com/sending-data-across-different-browser-tabs-6225daac93ec https://github.com/js-cookie/js-cookie https://github.com/tejacques/crosstab