如果浏览器关闭/网络推送,FCM 推送通知排队

FCM push notifications queuing up if browser is closed / Web-push

当浏览器关闭时,在此期间发送的每个推送通知都在排队,导致我第二天第一次打开浏览器时收到数百条通知。有没有办法停止推送通知排队?

一个选项是利用 time_to_live:

This parameter specifies how long (in seconds) the message should be kept in FCM storage if the device is offline. The maximum time to live supported is 4 weeks, and the default value is 4 weeks. For more information, see Setting the lifespan of a message.

并将其设置为您想要的时间。基本上它确定 FCM 何时将消息保留在队列中。

对于那些使用 web push c# 库的代码参考如下:

    public void SendPushNotification(PushSubscription sub)
    {           

        var pushEndpoint = sub.EndPoint;
        var p256Dh = sub.P256dh;
        var auth = sub.Auth;
        const string subject = @"mailto:xyz@xyz.com";
        var publicKey = PushConfiguration.PublicKey; //configuration attribute coming from the web.config file
        var privateKey = PushConfiguration.PrivateKey; //configuration attribute coming from the web.config file
        var subscription = new PushSubscription(pushEndpoint, p256Dh, auth);
        var vapidDetails = new VapidDetails(subject, publicKey, privateKey);
        var options = new Dictionary<string, object> {{"TTL", 3}, {"vapidDetails", vapidDetails}};
        var myPayload = new NotificationData(){// my data};

        var webPushClient = new WebPushClient();
        try
        {
            webPushClient.SendNotification(subscription, myPayload , options);
        }
        catch (WebPushException exception)
        {
            Console.WriteLine("Http STATUS code" + exception.StatusCode);
        }
    }

有两种选择:

  • 当您向推送服务发出请求时,您可以在通知中包含一个 TTL header(以秒为单位),这样如果未在该时间内发送,它就会过期
  • 您可以对通知使用 tag when you display them 来隐藏属于同一组(标签)的旧通知