我有一个由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>当我添加/编辑/删除新闻时,它可以正常工作,但问题是它将通知推送到我站点中打开的所有选项卡。是否有办法避免这种情况发生,并且每个站点只向显示一个浏览器通知?
发布于 2016-05-25 08:39:57
好的,我在这个SO question中找到了答案。
诀窍是在选项中使用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);
};
});发布于 2016-05-25 04:27:41
然后,您必须知道打开选项卡的数量和使用的URL。请参阅"How to get the number of tabs opened of my web in a browser using jquery?“这样的问题来进行讨论,因为出于隐私原因,这是不可取的。
https://stackoverflow.com/questions/37427520
复制相似问题