事件发生后localStorage未重置为零



与我之前在这里提出的问题类似,我正在尝试通过这个API计算有多少"未读消息"。当"is_minimized = true"时,count中的数字应增加1。当"is_minimized = false"时,变量count应重置为0。这需要持久性,这就是我使用localStorage的原因。

问题:当is_minimized = false时,count在控制台中显示0。然而,当再次尝试is_minimized = true时,变量会从上次停止的位置开始。例如,如果count以前是4,那么is_minimized = false控制台会记录0,然后再次记录is_minimized = true,数字显示为5,这是错误的,应该是1

这是当前代码:

count = localStorage.getItem('count');
if (count == null) {
count = 0
}
let is_minimized = true;
function countAdd() {
localStorage.setItem('count', ++count);
};
var chatServiceOptions = {
license: "**hidden for privacy**", // ie '1234567'
group: 4, // ie 22,
customer: {
name: "Development Account",
timezone: "Europe/London"
},
plugins: [
function (chatService) {
chatService.register('ready', function() {
// when chat window is closed, ensure is_minimized is true
chatService.events.on('LC_on_chat_window_minimized', data => {
is_minimized = true
});
// when chat window is opened, set is_minimized to false
chatService.events.on('LC_on_chat_window_opened', data => {
// localStorage.setItem('count', 0);    
is_minimized = false
});
chatService.events.on('LC_on_message', function(data) {
// set the window minimized to a variable 
var LC_API = LC_API || {};
LC_API.on_chat_window_minimized = function() {
is_minimized = true;
};
// output the data of the incoming/outgoing message
console.log(data);
// check that it comes from an agent and the chat window is minimized
// if it is, add +1 to unread message count
if (data.user_type === 'agent' && is_minimized == true) {
countAdd(); } 
// if its maximized, set unread count to zero
else if (is_minimized == false) { localStorage.setItem('count', '0'); };
// display number of unread messages
console.log('unread messages: ' + localStorage.getItem('count'));
});
})
}
],
};

var LC_API = LC_API || {};
LC_API.on_message = function(data) {
console.log(data)
alert("Message " + data.text + " sent by " + data.user_type);
};
</script>

首先,count = localStorage.getItem('count');对文件是全局的。其次,count不会在每次设置localStorage时都发生变化。因此,每次调用countAdd时都要获取当前计数,然后在localStorage 中递增并设置计数

function countAdd() {
var persistedCount = localStorage.getItem('count') ;
localStorage.setItem('count', ++persistedCount);
};

我希望这能解决你的问题

在else-if块中将"count"重置为0之前,让我们先清除它。。。

让我们修改这行:

else-if(is_minimized==false({localStorage.setItem('count','0'(;};

收件人:

else if(is_minimized == false)
{
localStorage.removeItem('count');
//now declare count and set it to 0
localStorage.setItem('count', '0');
}

希望这能有所帮助。