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.
'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.
'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,
@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.