我有一个由C#ASP.Net MVC 5.0驱动的新闻网站,当管理员添加/编辑或删除新闻时,我想将通知推送到客户端浏览器。
所以我在模板中添加了一个Signalr脚本,该脚本可用于所有页面。
_Layout.cshtml
var notificationsHub = $.connection.notificationHub;
$.connection.hub.start();
jQuery(function($) {
notificationsHub.client.Toast = function (title, body) {
var options = {
body: body,
};
var notification = new Notification(title, options);
};
});
并将此代码添加到新闻添加/编辑/删除完成后重定向的页面
<script>
$.connection.hub.start().done(function() {
notificationsHub.server.toast('@NotificationHub.Type.ToString()', '@Html.Raw(NotificationHub.Title)', '@Html.Raw(NotificationHub.Body)');
});
</script>
当我添加/编辑/删除新闻时,它可以正常工作,但问题是它会将通知推送到站点中所有打开的选项卡。有什么办法可以避免这种情况的发生,并且每个站点仅显示一个浏览器通知?
好吧,我在这个问题中找到了答案。
诀窍是tag
在选项中使用:
var notificationsHub = $.connection.notificationHub;
$.connection.hub.start();
jQuery(function($) {
notificationsHub.client.Toast = function (title, body) {
var options = {
body: body,
tag: 'my-unique-id',
};
var notification = new Notification(title, options);
};
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句