【问题标题】:How to clear local storage when a particular tab is closed and not when browser is closed in Angular 2?如何在关闭特定选项卡而不是在 Angular 2 中关闭浏览器时清除本地存储?
【发布时间】:2017-09-15 05:47:07
【问题描述】:

我的要求是:

  1. 当浏览器关闭时,我必须清除本地存储。
  2. 我已经尝试使用 onbeforeunload。它在浏览器关闭事件上执行。
  3. 由于打开了多个浏览器选项卡,localStorage 将保留旧值,而不是将其重定向到登录页面。

下面是我的示例代码。

请为此提出任何解决方案。

@HostListener('window:onbeforeunload', ['$event'])
unloadHandler(event) {
    localStorage.clear();
}

Also, attached the code screenshot

【问题讨论】:

  • 试试window.localStorage.removeItem(key);
  • 感谢您的回复。但是如何克服死锁问题呢?我的意思是当我再次重新打开应用程序时,代码 window.localStorage.removeItem(key);继续执行并且永远不会到达@登录屏幕。

标签: angular2-services angular2-directives


【解决方案1】:

您可以改用sessionStorage。与localStorage 不同,它不会跨标签保存数据。 Here is some more information about it.

会话存储的工作方式与本地存储相同,但唯一的区别是它会在当前选项卡关闭时清除数据。如果您为此应用程序打开一个新选项卡,它将重定向到登录。

您应该阅读以下文章,该文章将帮助您清楚地了解浏览器中可用的不同存储选项。 Sharing sessionStorage between tabs...

【讨论】:

    【解决方案2】:

    下面的技巧可以锻炼区分刷新和标签/浏览器关闭。在这里,我将卸载前的请求时间戳与加载后的时间戳进行比较。在下面的例子中,如果 timediff 以秒为单位小于 10sec ,浏览器会认为它是 Refresh ,如果 time diff 超过 10sec ,它将被认为是标签关闭。

    您可以根据客户端的 http 请求时间重新定义差异。如果它更多,只需将其增加到 50 秒。如果超过此值,则在加载时,浏览器将清除本地存储并重新加载站点。

    <script>
        window.onbeforeunload = function(e) {
            let date = Date.now();
            localStorage.setItem("lastactivity", date);
        };
        window.onload = function() {
            let date1 = localStorage.getItem('lastactivity');
            let date2 = Date.now();
            if (date1 !== undefined) {
             let difference = date2 - date1;
             let diff = ((difference) / 1000).toFixed(0);
             if (diff > 10) {
                localStorage.clear();
                //localStorage.removeItem(key);  for removing a single item
                location.reload();
             }
            }
        };
    </script>
    

    **特别是angular 2,在index.html中的&lt;/body&gt;标签前添加这段代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-27
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多