Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajkundalia/fb7b2dcc80b5a32db20306c85e66b6b1 to your computer and use it in GitHub Desktop.
Save rajkundalia/fb7b2dcc80b5a32db20306c85e66b6b1 to your computer and use it in GitHub Desktop.
The approach for limiting user to single window using local storage and session storage
function createGUID() {
let guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
let r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
return guid;
}
/**
* Compare our tab identifier associated with this session (particular tab)
* with that of one that is in localStorage (the active one for this browser).
* This browser tab is good if any of the following are true:
* 1. There is no localStorage Guid yet (first browser tab).
* 2. The localStorage Guid matches the session Guid. Same tab, refreshed.
*
* Another thing, that should be done is clear the localStorage or remove the item when we unload i.e. in windows#unload method
* if the tab-id comparison between local storage and session storage is same. This solves the problem for refreshing the same tab.
*/
function compareTabIdBetweenSessionAndLocalStorage() {
const localStorageSettingTime = 1 * 1000; // 1000 milliseconds = 1 second.
const localStorageTabKey = 'local-storage-tab-guid';
const sessionStorageGuidKey = 'session-storage-tab-guid';
let sessionGuid = sessionStorage.getItem(sessionStorageGuidKey) || this.createGUID();
let localGuid = localStorage.getItem(localStorageTabKey) || null;
// If no or stale tab object, our session is the winner. If the guid matches, ours is still the winner
console.log('localGuid:' + localGuid);
if (localGuid === null || localGuid === sessionGuid) {
sessionStorage.setItem(sessionStorageGuidKey, sessionGuid);
function setLocalGuid() {
console.log('setTabObj called');
localStorage.setItem(localStorageTabKey, sessionGuid);
}
setTimeout(setLocalGuid, localStorageSettingTime);
return true;
} else {
// An active tab is already open that does not match our session guid.
return false;
}
}
function checkForMultipleTab() {
if (!(compareTabIdBetweenSessionAndLocalStorage())) {
alert("There is already a tab open for the application, please use that window and close this one.");
return false;
} else {
return true;
}
}
// if(localStorage.getItem('local-storage-tab-guid') === sessionStorage.getItem('session-storage-tab-guid')) {
// localStorage.clear();
// } This has to be added in windows.onUnload.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment