Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- window.addEventListener("beforeunload", function() {
- let id = getSessionStorageItem("sessionStorageTabId");
- if (getLocalStorageItem('leadTab') === id) {
- electNewLead();
- } else {
- removeTab(id);
- }
- // Chrome requires returnValue to be set
- e.returnValue = '';
- });
- function initializeTab() {
- if (!getSessionStorageItem('sessionStorageTabId')) {
- setSessionStorageItem('sessionStorageTabId', Math.random().toString())
- }
- return getSessionStorageItem("sessionStorageTabId");
- }
- function registerTab(currentTabId) {
- console.log("Registering tab with ID:", currentTabId);
- const leadTabID = getLocalStorageItem('leadTab');
- if (leadTabID) {
- if (leadTabID !== currentTabId) {
- console.log("Assigning tab ID: ", currentTabId, "as excess tab.");
- assignAsExcessTab(currentTabId);
- return;
- } else {
- console.log("This tab is already a leader.");
- return;
- }
- }
- console.log("Assigning this (current) tab with ID: ", currentTabId, "as a leader");
- assignAsLeader(currentTabId);
- return;
- }
- function electNewLead() {
- let existingTabs = JSON.parse(getLocalStorageItem('excessTabs'));
- if (existingTabs && existingTabs[0]) {
- assignAsLeader(existingTabs[0]);
- removeTab(existingTabs[0]);
- }
- }
- function removeTab(tabId) {
- let existingTabs = JSON.parse(getLocalStorageItem('excessTabs'));
- if (existingTabs) {
- existingTabs = existingTabs.filter(excessTabId => excessTabId !== tabId);
- setLocalStorageItem('excessTabs', JSON.stringify(existingTabs))
- }
- }
- function assignAsLeader(tabId) {
- setLocalStorageItem('leadTab', tabId);
- }
- function assignAsExcessTab(tabId) {
- const excessTabs = getLocalStorageItem('excessTabs');
- if(excessTabs) {
- let existingTabs = JSON.parse(excessTabs);
- existingTabs.push(tabId);
- setLocalStorageItem('excessTabs', JSON.stringify(existingTabs));
- console.log("Tab with ID: ", tabId, "was successfully added to the excess tabs list.");
- return;
- } else {
- setLocalStorageItem('excessTabs', JSON.stringify([tabId]));
- console.log("This tab is the first excess tab.");
- return;
- }
- }
- function getSessionStorageItem(key) {
- return window.sessionStorage.getItem(key);
- }
- function setSessionStorageItem(key, value) {
- return window.sessionStorage.setItem(key, value);
- }
- function getLocalStorageItem(key) {
- return window.localStorage.getItem(key);
- }
- function setLocalStorageItem(key, value) {
- return window.localStorage.setItem(key, value);
- }
- function removeLocalStorageItem(key) {
- return window.localStorage.removeItem(key);
- }
- registerTab(initializeTab());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement