Search code examples
asp.net-mvcsignalr.clientasp.net-core-signalr

How to Keep signalr messages even after page refresh


I am able to send signalr messages to all the clients but any time client page refreshes, the messages(li) go off the notification panel(ul).

I would want to keep the messages till a specified date. Below is my code so far.

ctx.Members.Add(addThisMember);
            await ctx.SaveChangesAsync();
            notyf.Success("member successfully created.");
            await hCtx.Clients.All.SendAsync("ReceiveNotification", $"New Member added: {addThisMember.Fullname}");
            return RedirectToAction("Members");



        public class NotificationHub : Hub
    {
        public async Task SendNotification(string Message)
        {
            await Clients.All.SendAsync("ReceiveNotification", Message);

        }
    }


        var connection = new signalr.HubConnectionBuilder().withUrl("/NotificationHub").build();

    connection.on("ReceiveNotification", function (message) {
        // do whatever you want to do with `message`

        var li = document.createElement("li");
        document.getElementById("messagesList").appendChild(li);
        li.textContent = `${user} says ${message}`;
    });

connection.start().catch(function (err) {
    return console.error(err.toString());
});
    

Solution

  • You can save the message in localStorage in frontend or database in backend.

    Difference between saving in frontend and backend.

    1. If we don't need to save the data for longtime, then we can save it in localStorage. Here is the sample and test result.

    "use strict";
    ...
    
    window.onload = function () {
        if (connection == undefined || connection == "undefined") {
            console.log("not connect to signalr server");
            
        } else {
            if (connection._connectionState == "Connected") {
                //document.getElementById("sendButton").disabled = false;
                // load chat history messages
                for (var i = 0, len = localStorage.length; i < len; i++) {
                    var key = localStorage.key(i);
                    let seconds = Math.abs(new Date().getTime() - new Date(key).getTime()) / 1000;
                    //Data over 15s is not loaded
                    if (seconds <= 15) {
                        var value = localStorage[key];
                        var li = document.createElement("li");
                        document.getElementById("messagesList").appendChild(li);
                        // We can assign user-supplied strings to an element's textContent because it
                        // is not interpreted as markup. If you're assigning in any other way, you
                        // should be aware of possible script injection concerns.
                        var msg = value;
                        li.textContent = msg;
                    }
    
                }
            }
        }
    }
    
    
    connection.on("Chat_ReceiveMessage", function (user, message) {
        var li = document.createElement("li");
        document.getElementById("messagesList").appendChild(li);
        // We can assign user-supplied strings to an element's textContent because it
        // is not interpreted as markup. If you're assigning in any other way, you
        // should be aware of possible script injection concerns.
        var msg = `${user} says ${message}`;
        li.textContent = msg;
    
        localStorage.setItem(new Date(), msg)
    });

    Test Result

    enter image description here

    2. If we want to save the data for longtime, then we can save it in database. You can refer the sample code to load the history messages