Adnan Sheikh
Adnan Sheikh

Reputation: 806

Session Storage not being cleared when duplicating tabs

I am working on an Angular Application build using Angular 7. We don't allow users to open our application in multiple tabs of a browser and I am using LocalStoage+SessionStorage to make this happen.

app.component.ts

//This function is being called on component loading
register_tab_GUID() {
// detect local storage available
if (typeof (Storage) !== "undefined") {
  // get (set if not) tab GUID and store in tab session
  if (sessionStorage["tabGUID"] == null){
     sessionStorage["tabGUID"] = this.tab_GUID();
  } 
  var guid = sessionStorage["tabGUID"];

  // add eventlistener to local storage
  window.addEventListener("storage", (e) =>{

  if (e.key == 'tabGUID') {
     if (e.oldValue != e.newValue) {
        this._api.logout();
        localStorage.setItem('multiTabs' , 'true');
        this.router.navigate(['multi-tabs-not-allowed'])
      }
    }
  }, false);

      // set tab GUID in local storage
      localStorage["tabGUID"] = guid;
    }
  }



tab_GUID() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  s4() + '-' + s4() + s4() + s4();
}

Everything works fine when user opens a new tab and tries to open the application. But when user duplicates already opened tab I found that SessionStorage does not clear and it has the same data saved as previous tab that we duplicated.

Duplicating Tab

I tried searching for this behaviour of SessionStorage but couldn't find anything related to this. Is this the accurate behaviour or I am doing something wrong?

Upvotes: 1

Views: 5075

Answers (1)

b4rtaz
b4rtaz

Reputation: 251

To prevent duplication you should use this code at application start.

window.addEventListener('beforeunload', function (event) {
    sessionStorage.removeItem('__lock');
});

if (sessionStorage.getItem('__lock')) {
    sessionStorage.clear();
    console.warn('Found a lock in session storage. The storage was cleared.');
}

sessionStorage.setItem('__lock', '1');

Upvotes: 1

Related Questions