4

プッシュ通知を受信するために GCM と ServiceWorkers を正常に実装しました。

私の問題

SOS アップデートがあるたびに、HTTP リクエストをgcm-httpに送信しています。これにより、Google Chrome に通常の通知が表示されますが、ペイロードやデータは表示されません。

Google Developers Docによると、chrome はペイロード/データを受信できないため、プッシュ イベントがトリガーされたときにバックエンドから手動で通知を取得する必要があります。

したがって、データを取得するために、バックエンド (django) で URL を要求して、通知データを送信します。しかし、問題はここにあります。データベース/モデルから送信する必要がある通知のデータをどのように知ることができますか?

注:- SOSの更新であり、既読/未読は必要ないためdatabase table/model、クライアントが読んだ通知を判断するために別のものを維持していません。

機能しない回避策:-

クライアントのブラウザーに Cookie を設定し、バックエンドで次の通知を受け取ることができます (以下はコードです)。

class GetSOSNotification(View):
    notif_id = 0

    def get(self, request):
        if 'last_notif_id' in request.COOKIES:
            notif_id = request.COOKIES.get('last_notif_id') + 1
            sos = SOSUpdate.objects.get(id=notif_id)
        else:
            sos = SOSUpdate.objects.order_by('-timestamp').filter()[0]
            notif_id = sos.id

        data = dict()
        data['notification'] = dict()
        if sos.get_condition_display() and sos.get_subject_display():
            data['notification']['title'] = sos.polling_station.name + " " + sos.get_subject_display() + " " + sos.get_condition_display()
        elif sos.get_condition_display():
            data['notification']['title'] = sos.polling_station.name + " " + sos.get_condition_display()
        elif sos.get_subject_display():
            data['notification']['title'] = sos.polling_station.name + " " + sos.get_subject_display()
        else:
            data['notification']['title'] = sos.polling_station.name + " SOS Alert!"

        if sos.message:
            data['notification']['message'] = sos.message
        else:
            data['notification']['message'] = "Please click here to check the details."

        data['notification']['notif_id'] = notif_id

        return JsonResponse(data)

しかし、JSON レスポンスを返す必要があり、そのためサーバー側から Cookie を設定することができないため、クライアント側 (つまり Javascript) で Cookie を設定するために使用する予定でしdata['notification']['notif_id']

私のSW.jsのスニペットは次のようになります。

self.addEventListener('push', function(event) {
  console.log('Push message', event);
  event.waitUntil(
    fetch("//localhost/get_sos_notification/").then(function(response){
        if(response.status!=200){
            console.log('Looks like there was a problem. Status Code: ' + response.status);
            throw new Error();
        }
        return response.json().then(function(data){
            if(data.error || !data.notification){
                console.error('The API returned an error.', data.error);
                throw new Error();
            }
            var title = data.notification.title;
            var message = data.notification.message;
            var icon = '//localhost/static/main/images/push-notification.png';
            var notificationTag = data.notification.tag;
            return self.registration.showNotification(title, {
              body: message,
              icon: icon,
              tag: notificationTag
            });
        });
    }).catch(function(err){
       console.log('Unable to retrieve data', err);
       var title = 'SOS - Update';
       var message = 'We were unable to get the information, please click here to know the real message.';
       var icon = '//localhost/static/main/images/push-notification.png';
       var notificationTag = 'notification-error';
       return self.registration.showNotification(title, {
           body: message,
           icon: icon,
           tag: notificationTag
       });
    })
  );
});

document.cookie = last_notif_id=data.notification.notif_idしかし、JSスクリプトがエラーを出しているため、受信した通知データを処理している場所ではできません(正常に受信された場合)Unable to retrieve data ReferenceError: document is not defined at http://localhost/static/main/js/sw.js

追加情報: //localhost/get_sos_notification/は GET 要求であり、JSON を返し、にマップされますclass GetSOSNotification(View)

私はグーグルでSOをたくさん検索しましたが、解決策はありません。

前もって感謝します。

4

0 に答える 0