@@ -22,6 +22,7 @@ class HTMLChatApp {
2222 this . lastMessageTime = 0 ;
2323 this . lastFetchTime = 0 ;
2424 this . currentReplyTo = null ;
25+ this . initialLoad = true ;
2526
2627 // Initialize managers to null (will be created in init)
2728 this . soundManager = null ;
@@ -556,23 +557,33 @@ class HTMLChatApp {
556557 }
557558
558559 // Check for new messages for notifications and update stored message IDs
559- const lastMessageCount =
560- this . loadFromStorage (
561- `htmlchat_ ${ this . elements . roomSelect . value } _count`
562- ) || 0 ;
563- if (
564- messages . length > lastMessageCount &&
565- ! this . isVisible &&
566- lastMessageCount > 0
567- ) {
568- const newMessages = messages . slice ( lastMessageCount ) ;
569- newMessages . forEach ( ( msg ) => {
570- if ( msg . user !== this . user ) {
571- this . notificationManager . showNotification ( msg . user , msg . text ) ;
572- this . soundManager . playSound ( "message" ) ;
573- }
574- } ) ;
560+ // Load last message time (default 0 for first load)
561+ const lastMessageTime = this . loadFromStorage ( `htmlchat_ ${ this . elements . roomSelect . value } _last_time` ) || 0 ;
562+
563+ // Check for new messages after initial load
564+ if ( ! this . initialLoad && messages . length > 0 ) {
565+ const latestTime = Math . max ( ... messages . map ( m => m . time || 0 ) ) ;
566+ if ( latestTime > lastMessageTime ) {
567+ // Find and notify for messages newer than lastMessageTime
568+ const newMessages = messages . filter ( m => ( m . time || 0 ) > lastMessageTime ) ;
569+ newMessages . forEach ( ( msg ) => {
570+ if ( msg . user !== this . user ) {
571+ this . notificationManager . showNotification ( msg . user , msg . text ) ;
572+ this . soundManager . playSound ( "message" ) ;
573+ }
574+ } ) ;
575+ }
575576 }
577+
578+ // Update last message time to the latest
579+ if ( messages . length > 0 ) {
580+ const latestTime = Math . max ( ...messages . map ( m => m . time || 0 ) ) ;
581+ this . saveToStorage ( `htmlchat_${ this . elements . roomSelect . value } _last_time` , latestTime ) ;
582+ }
583+
584+ // Mark as loaded
585+ this . initialLoad = false ;
586+
576587 this . saveToStorage (
577588 `htmlchat_${ this . elements . roomSelect . value } _count` ,
578589 messages . length
0 commit comments