英文:
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("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>
# 答案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)
});
测试结果
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 -->
"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)
});
<!-- end snippet -->
Test Result
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论