如何在页面刷新后保留 SignalR 消息

huangapple go评论90阅读模式
英文:

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).

我能够向所有客户端发送SignalR消息,但每次客户端页面刷新时,消息(li)会消失在通知面板(ul)中。

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

我希望将消息保留到指定日期。以下是到目前为止的我的代码。

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());
});```

<details>
<summary>英文:</summary>

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(&quot;ReceiveNotification&quot;, Message);

    }
}


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

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

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

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


 

</details>


# 答案1
**得分**: 1

你可以在前端使用localStorage或在后端使用数据库保存消息。

**前端和后端保存的区别。**

*1. 如果我们不需要长时间保存数据,那么可以将其保存在localStorage中。以下是示例和测试结果。*

```javascript
"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)
});

测试结果

如何在页面刷新后保留 SignalR 消息

2. 如果我们想长时间保存数据,那么可以将其保存在数据库中。您可以参考示例代码来加载历史消息。

英文:

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.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

&quot;use strict&quot;;
...

window.onload = function () {
    if (connection == undefined || connection == &quot;undefined&quot;) {
        console.log(&quot;not connect to signalr server&quot;);
        
    } else {
        if (connection._connectionState == &quot;Connected&quot;) {
            //document.getElementById(&quot;sendButton&quot;).disabled = false;
            // load chat history messages
            for (var i = 0, len = localStorage.length; i &lt; 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 &lt;= 15) {
                    var value = localStorage[key];
                    var li = document.createElement(&quot;li&quot;);
                    document.getElementById(&quot;messagesList&quot;).appendChild(li);
                    // We can assign user-supplied strings to an element&#39;s textContent because it
                    // is not interpreted as markup. If you&#39;re assigning in any other way, you
                    // should be aware of possible script injection concerns.
                    var msg = value;
                    li.textContent = msg;
                }

            }
        }
    }
}


connection.on(&quot;Chat_ReceiveMessage&quot;, function (user, message) {
    var li = document.createElement(&quot;li&quot;);
    document.getElementById(&quot;messagesList&quot;).appendChild(li);
    // We can assign user-supplied strings to an element&#39;s textContent because it
    // is not interpreted as markup. If you&#39;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)
});

<!-- end snippet -->

Test Result

如何在页面刷新后保留 SignalR 消息

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

huangapple
  • 本文由 发表于 2023年8月5日 00:05:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76837566.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定