You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现持久化未读消息计数时遇countAdd未定义报错

Fixing "Uncaught ReferenceError: countAdd is not defined" in Your Chat Unread Count Script

Let's break down what's going wrong and how to fix it step by step:

The Root Cause

Your countAdd() function is defined inside the plugins array as a standalone function. This traps it in the local scope of that array element, so the LC_on_message event callback can't access it—hence the reference error.

Step-by-Step Fixes

Here's the revised script with fixes for the scope issue, plus improvements to handle localStorage persistence properly:

// Initialize count from localStorage (or 0 if no value exists)
let count = Number(localStorage.getItem('count')) || 0;
let is_minimized = true;

// Move countAdd to global scope so all callbacks can access it
function countAdd() {
  count++;
  localStorage.setItem('count', count); // Use setItem for proper localStorage handling
}

var chatServiceOptions = {
  license: "*SECRET*",
  group: 4,
  customer: {
    name: "Development Account",
    timezone: "Europe/London"
  },
  plugins: [
    function (chatService) {
      chatService.register('ready', function() {
        // Update minimized state when window is minimized
        chatService.events.on('LC_on_chat_window_minimized', data => {
          is_minimized = true;
        });

        // Reset count and update state when window is opened
        chatService.events.on('LC_on_chat_window_opened', data => {
          count = 0;
          localStorage.setItem('count', 0);
          is_minimized = false;
        });

        chatService.events.on('LC_on_message', function(data) {
          console.log(data);

          // Only increment count if message is from agent AND window is minimized
          if (data.user_type === 'agent' && is_minimized) {
            countAdd();
          } 
          // Reset count if window is maximized
          else if (!is_minimized) {
            count = 0;
            localStorage.setItem('count', 0);
          }

          // Display current unread count
          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);
};

Key Improvements Explained

  • Fixed Scope Issue: Moved countAdd() to the global scope so the message event callback can access it without errors.
  • Proper localStorage Handling:
    • Used localStorage.setItem() and localStorage.getItem() instead of direct property assignment (follows web standards and avoids unexpected behavior).
    • Initialized count by reading from localStorage, converting the stored string value to a number (since localStorage only stores strings).
  • Cleaned Redundant Code: Removed the duplicate LC_API.on_chat_window_minimized definition inside the message event—you already have that logic handled via chatService.events.on.
  • Simplified Conditionals: Made the is_minimized check more concise (is_minimized instead of is_minimized == true).

Additional Notes

  • If your chat window starts maximized by default, set is_minimized = false initially to avoid incorrect counting.
  • Test the full flow: minimize the window, send an agent message, check the console for the incremented count; then open the window and confirm the count resets to 0. Refresh the page to verify the count persists correctly.

内容的提问来源于stack exchange,提问作者jorts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 18:37:30