asp.net-mvc - 当打开一页的两个选项卡时,通知不起作用
问题描述
我在我的 MVC Web 应用程序上使用通知以及 SignalR。我正在从服务器的某个页面中调用客户端函数。问题是当该页面同时在两个浏览器选项卡中打开时,不会弹出任何通知。我应该提一下,当页面仅在一个选项卡中打开时,它确实可以正常工作。
我注意到,如果我在创建通知对象的行之前放置一个警报,两个选项卡都会收到通知,这就是我所期望的。提前致谢。
$(function () {
var notificationHub = $.connection.notificationHub;
$.connection.hub.start();
notificationHub.client.sendMessage = function (content) {
setTimeout(notifyMe(content), 10);
};
});
function notifyMe(message) {
if (!("Notification" in window)) {
alert("This browser does not support system notifications");
}
else if (Notification.permission === "granted") {
var notification = new Notification(message);
}
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
var notification = new Notification(message);
}
});
}
}
更新: 这是通知创建代码前面有一个警报的场景,它可以按预期工作:
function notifyMe(message, system) {
if (!("Notification" in window)) {
alert("This browser does not support system notifications");
}
else if (Notification.permission === "granted") {
alert('hit');
var notification = new Notification(system, {
body: message,
tag: (Math.floor(Math.random() * 10)).toString(),
icon: 'Content/Images/logo.png',
dir: 'rtl',
background: '#ff0000'
});
}
else if (Notification.permission !== 'denied') {
alert('hit');
Notification.requestPermission(function (permission) {
if (permission === "granted") {
var notification = new Notification(message)
}
});
}
}
$(function () {
var notificationHub = $.connection.notificationHub;
$.connection.hub.start();
notificationHub.client.sendMessage = function (content, system) {
setTimeout(notifyMe(content, system), 10);
};
});
解决方案
问题可能出在您的信号器初始化代码中。我假设这var notificationHub
是一个 globla 对象,并且您已将此 doe 放在母版页中。
然后你需要notificationHub
在初始化之前检查它是否为空。只需像这样更改您的代码:
$(function () {
if(notificationHub === undefined || notificationHub === null){
var notificationHub = $.connection.notificationHub;
$.connection.hub.start();
notificationHub.client.sendMessage = function (content) {
setTimeout(notifyMe(content), 10);
};
}
});
更新:
当您确认信号器正常工作(即警报消息在两个选项卡中工作)后,请尝试以下Notification
对象:
var notification = new Notification('Test', {
body : message,
tag : 'notify-tag-name', //Make this a random number
icon : 'icon.png'
});
请注意,如果两个浏览器选项卡中的标记属性值相同,则即使打开了许多浏览器选项卡,通知也只会显示一次。在这种情况下,您可以在标签名称中添加一个随机数,以确保它们在标签之间是不同的。
推荐阅读
- laravel - 在所有实例上发现不正确的应用程序版本。预期版本
- angular - Angular 11 CORS 问题代理端口正在增加
- javascript - 在 Objection.js 中,如何在查询中包含虚拟列?
- java - 我的应用未请求位置权限,权限被自动拒绝
- docker - Docker 运行没有问题,但我无法从给定的 url 访问该站点
- email - 连接 telnet 时出现“556 5.7.5 Invalid RFC missing body”之类的错误
- mysql - 无法为 MySQL 5.7 启用 jemalloc
- azure - 如果发布成功,为什么没有选项只能在 Slack 中发送 azurepipeline 警报?
- maven - 如何使用 NEXUS 配置 GITLAB CI?
- python - 绘图层请求规范