Skip to content

Instantly share code, notes, and snippets.

@rajkundalia
Last active August 17, 2021 10:20
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/3b5c41a1da911133e6822759730317b5 to your computer and use it in GitHub Desktop.
Save rajkundalia/3b5c41a1da911133e6822759730317b5 to your computer and use it in GitHub Desktop.
The approach for limiting user to single window using document cookie
/**
* This function checks if multiple tabs for the application are not using the document.cookie.
* The approach here is as follows:
* 1. Fetch the cookies and split it and then fetch the value for the cookie name i.e. tabNumber.
* 2. We check if the cookie is value for tabNumber is > 0, for the first time it won't be and we go to the else part
* where we set the value to be tabNumber=1. The tab would load successfully.
* 3. Now when we open the second tab in the same browser session, the cookie will have tabNumber=1, we extract the value
* and we check if cookieValue > 0 and we show an alert saying second tab was opened.
* 4. The line window.open(window.location, '_self') was added so that we get redirected using the same URL and we don't
* let the user open the tab anyhow (my main requirement).
* 5. The refresh of the same tab works (only 1 tab open), because in windows.onunload, we check if the cookie contains
* tabNumber=1, if yes, we set it to 0 and as per the logic in checkForMultipleTabs, we set it to tabNumber=1 again.
*/
function checkForMultipleTab() {
const cookies = document.cookie.split('; ');
const row = altFind(cookies, isTab);
let cookieValue = '0';
if(row) {
cookieValue = row.split('=')[1];
}
if(+cookieValue > 0) {
window.alert('Only one application tab is allowed per browser session. \n' +
'Please close this tab or the previous one.');
window.open(window.location, '_self');
return false;
} else {
document.cookie = 'tabNumber=1';
return true;
}
}
function isTab(row) {
return row.indexOf('tabNumber=') === 0;
}
function altFind(arr, callback) {
for (let i = 0; i < arr.length; i++) {
let match = callback(arr[i]);
if (match) {
return arr[i];
}
}
}
// if(document.cookie.includes(‘tabNumber=1’)){
// document.cookie = ‘tabNumber=0’;
// }
// 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