【问题标题】:Session Storage not being cleared when duplicating tabs复制选项卡时未清除会话存储
【发布时间】:2019-12-04 18:07:33
【问题描述】:

我正在使用 Angular 7 构建 Angular 应用程序。我们不允许用户在浏览器的多个选项卡中打开我们的应用程序,我正在使用 LocalStoage+SessionStorage 来实现这一点。

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();
}

当用户打开一个新标签并尝试打开应用程序时,一切正常。但是当用户复制已经打开的选项卡时,我发现 SessionStorage 并没有清除,并且它保存的数据与我们复制的上一个选项卡相同。

我尝试搜索 SessionStorage 的这种行为,但找不到与此相关的任何内容。这是正确的行为还是我做错了什么?

【问题讨论】:

  • 如何在每次标签加载时清除会话存储,这样您就可以确定标签是新打开还是复制。
  • 我不认为你可以使用duplicate 来避免这种情况,因为它似乎会复制并粘贴旧标签中的所有内容,包括 sessionStorage。
  • this 可能会有所帮助
  • @GopeshSharma 是的,我已经这样做了。但这会引发另一个问题,app.component 由于其他原因在同一个选项卡上被调用,如果我手动清除会话存储,它会将已打开的选项卡作为新选项卡。
  • 添加一个canActivate Guard然后检查sessionStorage是否存在怎么样?如果存在,请不要加载该组件。 @AdnanSheikh

标签: angular browser session-storage


【解决方案1】:

为防止重复,您应该在应用程序启动时使用此代码。

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');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 2022-08-09
    • 2014-07-08
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多