简体   繁体   English

推送事件未触发来自服务器的发送通知

[英]Push event not firing on send notification from server

I want to push notification from my server.for that i am using web push API for java , i am able to send the notification to endpoint url but on receiver side my service worker not executing push event,As I am using VAPID so no need to use gcm Id as per my understanding,here you are my service worker file.我想从我的服务器推送通知。因为我使用的是 Java 的 web 推送 API,我能够将通知发送到端点 url,但在接收方我的服务工作者没有执行推送事件,因为我使用的是 VAPID,所以不需要根据我的理解使用 gcm Id,这是我的服务工作者文件。

'use strict';

const applicationServerPublicKey = 'BEl62iUYgUivxIkv69yViEuiBIa-Ib9-
SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U';

function urlB64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding)
    .replace(/\-/g, '+')
.replace(/_/g, '/');

const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);

for (let i = 0; i < rawData.length; ++i) {
  outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
self.addEventListener('install', function(event){
 event.waitUntil(self.skipWaiting());
 console.log("activate");
});

self.addEventListener('activate', function(event){
event.waitUntil(self.clients.claim());
 console.log("install");
});

self.addEventListener('push', function(event) {
  console.log('Received push');
  let notificationTitle = 'Hello';
  const notificationOptions = {
    body: 'Thanks for sending this push msg.',
    icon: '/JMS/resources/images/icon.png',
    badge: '/JMS/resources/images/badge.png',
    tag: 'simple-push-demo-notification',
    data: {
      url: 'https://developers.google.com/web/fundamentals/getting-
      started/push-notifications/',
    },
  };

  if (event.data) {
    const dataText = event.data.text();
    notificationTitle = 'Received Payload';
    notificationOptions.body = `Push data: '${dataText}'`;
  }

    event.waitUntil(
    Promise.all([
      self.registration.showNotification(
        notificationTitle, notificationOptions),
    ])
  );
});

self.addEventListener('notificationclick', function(event) {
    event.notification.close();
    event.waitUntil(
            clients.openWindow('https://www.auctiontiger.net')
          );
  let clickResponsePromise = Promise.resolve();
  if (event.notification.data && event.notification.data.url) {
    clickResponsePromise = clients.openWindow(event.notification.data.url);
  }

  event.waitUntil(
    Promise.all([
      clickResponsePromise
    ])
  );
});

here you are my main.js file from where i am able to call to my local server.这是我的 main.js 文件,我可以从中调用本地服务器。

'use strict';

const applicationServerPublicKey = 'BEl62iUYgUivxIkv69yViEuiBIa-Ib9-
SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U';
const pushButton = document.querySelector('.js-push-btn');

let isSubscribed = false;
let swRegistration = null;

function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');

const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);

for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}

function updateBtn() {
if (Notification.permission === 'denied') {
pushButton.textContent = 'Push Messaging Blocked.';
pushButton.disabled = true;
updateSubscriptionOnServer(null);
return;
}

    if (isSubscribed) {
     pushButton.textContent = 'Disable Push Messaging';
     } else {
     pushButton.textContent = 'Enable Push Messaging';
     }

     pushButton.disabled = false;
    }

  function updateSubscriptionOnServer(subscription) {
  // TODO: Send subscription to application server

const subscriptionJson = document.querySelector('.js-subscription-json');
const subscriptionDetails =
document.querySelector('.js-subscription-details');

if (subscription) {
subscriptionJson.textContent = JSON.stringify(subscription);
subscriptionDetails.classList.remove('is-invisible');
 } else {
 subscriptionDetails.classList.add('is-invisible');
 }
 }

function subscribeUser() {
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey:applicationServerKey 

  })
 .then(function(subscription) {
  updateSubscriptionOnServer(subscription);
  isSubscribed = true;
  updateBtn();
  initialiseUI();
  return sendSubscriptionToServer(subscription);
  })
   .catch(function(err) {
   console.log('Failed to subscribe the user: ', err);

   });
   }
function sendSubscriptionToServer(subscription) {
var key = subscription.getKey ? subscription.getKey('p256dh') : '';
var auth = subscription.getKey ? subscription.getKey('auth') : '';

return fetch('/JMS/profile/subscription', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        endpoint: subscription.endpoint,
        // Take byte[] and turn it into a base64 encoded string suitable for
        // POSTing to a server over HTTP
        key:key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key))) 
        : '',
        auth:auth ? btoa(String.fromCharCode.apply(null, new 
        Uint8Array(auth))) : ''
    })
    });

     }

   function unsubscribeUser() {
   swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
   if (subscription) {
    return subscription.unsubscribe();
   }
   })
  .catch(function(error) {
  console.log('Error unsubscribing', error);
   })
  .then(function() {
  updateSubscriptionOnServer(null);

  console.log('User is unsubscribed.');
  isSubscribed = false;

  updateBtn();
  });
  }

   function initialiseUI() {
   pushButton.addEventListener('click', function() {
   pushButton.disabled = true;
   if (isSubscribed) {
    unsubscribeUser();
   } else {
  subscribeUser();
    }
    });

   // Set the initial subscription value
    swRegistration.pushManager.getSubscription()
    .then(function(subscription) {
    isSubscribed = !(subscription === null);

    updateSubscriptionOnServer(subscription);

      if (isSubscribed) {

        console.log('User IS subscribed.');
      } else {
     console.log('User is NOT subscribed.');
      }

       updateBtn();
      });
      }

    if ('serviceWorker' in navigator && 'PushManager' in window) {
    console.log('Service Worker and Push is supported');

    navigator.serviceWorker.register('sw.js')
    .then(function(swReg) {
    console.log('Service Worker is registered', swReg.scope);
    swReg.update();
    swRegistration = swReg;
    initialiseUI();
    })
    .catch(function(error) {
    console.error('Service Worker Error', error);
    });
    } else {
    console.warn('Push messaging is not supported');
    pushButton.textContent = 'Push Not Supported';
    }

here is the URL for webpush API that i have used for my application, [ https://github.com/web-push-libs/webpush-java][1] finally my server side code,这是我用于我的应用程序的 webpush API 的 URL,[ https://github.com/web-push-libs/webpush-java][1]最后是我的服务器端代码,

@RequestMapping(value = "profile/subscription", method = RequestMethod.POST, 
headers = "Content-Type=application/json")
@ResponseBody
public String post(@RequestBody String body,byte[] 
    payload,HttpServletResponse response)
            throws GeneralSecurityException, IOException, JoseException, 
    ExecutionException, InterruptedException, ParseException, JSONException 
    {
    String data="";
    org.json.JSONObject ob = new org.json.JSONObject(body);
    final int TTL = 255;
    payload= "hello".getBytes(); 
    com.demo.controller.PushService pushService = new  
    com.demo.controller.PushService();
    nl.martijndwars.webpush.Notification notification =new 
    nl.martijndwars.webpush.Notification(ob.getString("endpoint")
   ,new Subscription().getUserPublicKey((ob.getString("key"))),
    Base64.decode(ob.getString("auth")), 
    payload,TTL);
    pushService.send(notification);
    org.json.JSONObject ob2 = new org.json.JSONObject(body);
    ob2.put("data", notification.getPayload());
    JSONArray arr= new JSONArray();
    arr.add(ob2);
    data=arr.toJSONString();
    response.setHeader("Service-Worker-Allowed", "/"); 
    return data;
   }

actually I am fetching this from client browser and on server-side sending notification on the endpoint, and i am able to send the notification but my service worker is not able to fire push event so i am not getting notification on my browser.实际上,我是从客户端浏览器中获取此信息,并在端点上的服务器端发送通知,并且我能够发送通知,但我的服务工作者无法触发推送事件,因此我没有在浏览器上收到通知。

  {
  auth:"hcQQq+1FeDuSu7V0zd5DXA==" 
  endpoint:"https://fcm.googleapis.com/fcm/send/
  cXgp0l3svNo:APA91bG8dDfZhrc0iaSyzvuV1BvnxXz9T-
  SmLCKOymKrEdwvrh0_SjzjnU3ORRKvW5QD-
  Zp196T5nAGPayR7EKu_Bkb0pQrSex7Q3DZSu54Lo83AEiUE6p-2Xn-nrquCymKVFt6Z4nY8"
  key:"BJv2qC3WSCsRszMi57vOBpFjnIpdJ/
  uXQQFj4d0XZD9lRuZKuBgJNVFra0SFEvRlQQ88eG8RWWs7sSvO9Pbdkwk="
  }

Please help me to get out of this, any help would be greatly appreciated.Thank you in advance.请帮助我摆脱这种情况,任何帮助将不胜感激。在此先感谢您。

The issue might be due to some firewall blocking you from receiving the push notification.该问题可能是由于某些防火墙阻止您接收推送通知。 This was the case with me.我就是这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从Java服务器向服务器发送推送通知 - Send push notification from server to android device in Java 从我的 Java Web 服务器向 Android 手机发送推送通知 - Send Push Notification to Android mobiles from my Java Web Server 来自服务器的APNS推送通知 - APNS push notification from server Android(PhoneGap)-通过推送通知中的按钮单击事件发送HTTP请求 - Android (PhoneGap) - Send HTTP request from a button's click event in Push Notification 如何通过Java服务器使用FCM向Android设备发送推送通知? - how to send push notification to the android device using FCM by java server? Firebase Java Server 向所有设备发送推送通知 - Firebase Java Server to send push notification to all devices 消息传递服务器如何使目标客户端独立化并发送推送通知 - How can a messaging server indetify target client and send push notification 如何通过java服务器使用GCM向Android设备发送推送通知? - how to send push notification to the android device using GCM by java server? 从Web服务器向客户端发送通知 - Send notification to the client from a web server Java-如何将通知从服务器发送到客户端 - Java - How to send notification from server to client
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM