【问题标题】:localstorage restoring deleted data after page refresh页面刷新后本地存储恢复已删除的数据
【发布时间】:2017-08-02 17:52:52
【问题描述】:

我构建了一个聊天应用程序并使用localStorage 来保持对话,即使在页面刷新后也是如此。如果聊天结束,我想删除 localStorage 并清除聊天窗口,这工作正常。但是如果用户再次发起聊天并刷新页面而不是之前的聊天对话恢复到localStorage

下面是我的代码:

var CHAT_MSG_LOCAL = []; //store messages into it
    CHAT_MSG_LOCAL.push(msgObj); //push message into the variable

    //save in local storage  when page refreshed 
    $(window).on('unload', function () {            
        saveLocalData(CHAT_MSG_LOCAL);  
    });

    //Retrive from local storage when page load
    $(document).ready(function () {
      retriveLocalData();
      var data = retriveLocalData();
      if (data.length > 0)
        for (var i = 0; i < data.length; i++) {
            output(data[i]); // generate html
        }
    });

    //Chat End
    $(".close-conversation").on("click", function (e) {
            e.preventDefault();                
            localStorage.removeItem('local-messages');
            localStorage.setItem('local-messages', []);

        });

    //save function
    function saveLocalData(CHAT_MSG_LOCAL) {
        var messageString = JSON.stringify(CHAT_MSG_LOCAL);
        localStorage.setItem('local-messages', messageString);

    }

    //retrive function
    function retriveLocalData() {
        var localmsgObj = localStorage.getItem('local-messages');
        var retrievedObject = {};
        if (localmsgObj.length > 0) {
            retrievedObject = JSON.parse(localmsgObj);
        }
        return retrievedObject;
    }

请帮我找出错误。提前致谢。

【问题讨论】:

    标签: jquery html local-storage


    【解决方案1】:

    您正面临上述代码未清除 CHAT_MSG_LOCAL 参数的问题。

    请使用以下代码将参数设为空。

     $(".close-conversation").on("click", function (e) {
          e.preventDefault();                
          localStorage.removeItem('local-messages');
          localStorage.setItem('local-messages', []);
          CHAT_MSG_LOCAL = []; //change
      });
    

    【讨论】:

    • 在之前的代码中关闭聊天窗口时,local-messages 参数为空。然后用户重新打开聊天,因此此时本地参数为空,一旦用户刷新浏览器,“卸载事件”将再次将 CHAT_MSG_LOCAL 中可用的数据保存到本地存储,页面刷新数据再次由 retriveLocalData() 填充在 document.ready 中调用。从而清除 CHAT_MSG_LOCAL = [];一定解决了我们的问题。你能附上确切的js文件吗?非常感谢
    • 需要对我的代码进行一些修复。现在它的工作。标记为已采纳答案。谢谢@amit wadhwani
    猜你喜欢
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    相关资源
    最近更新 更多