首页 > 解决方案 > 当打开一页的两个选项卡时,通知不起作用

问题描述

我在我的 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);
    };
});

标签: asp.net-mvcnotificationssignalr

解决方案


问题可能出在您的信号器初始化代码中。我假设这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'
});

请注意,如果两个浏览器选项卡中的标记属性值相同,则即使打开了许多浏览器选项卡,通知也只会显示一次。在这种情况下,您可以在标签名称中添加一个随机数,以确保它们在标签之间是不同的。


推荐阅读