1
votes

I am implementing Push Notification for web browser. Chrome/Firefox browser show permission popup and after allow its return token id in both browsers. When I send push notification its only show in Chrome not a Firefox browser. My code is:

window.addEventListener('load', function() {  
    if ('serviceWorker' in navigator) {  
        navigator.serviceWorker.register('service-worker.js').then(initialiseState);  
    } else {  
        console.warn('Service workers aren\'t supported in this browser.');  
    }  
});

function initialiseState() 
{  
    if (!('showNotification' in ServiceWorkerRegistration.prototype)) {  
        console.warn('Notifications aren\'t supported.');  
        return;  
    }

    if (Notification.permission === 'denied') {  
        console.warn('The user has blocked notifications.');  
        return;  
    }

    if (!('PushManager' in window)) {  
        console.warn('Push messaging isn\'t supported.');  
        return;  
    }

    navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {  
        serviceWorkerRegistration.pushManager.getSubscription({
            userVisibleOnly: 1
        })  
        .then(function(subscription) {  
            if (!subscription) {  
              return;  
            }
        })  
        .catch(function(err) {  
            console.warn('Error during getSubscription()', err);  
        });  
    });  
}

function subscribe() 
{  
    navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {  
        serviceWorkerRegistration.pushManager.subscribe({
            userVisibleOnly: 1
        })  
        .then(function(subscription) {  
            console.log('subscribe', subscription.endpoint);
        })  
        .catch(function(e) {  
            if (Notification.permission === 'denied') {  
              console.warn('Permission for Notifications was denied');  
              pushButton.disabled = true;  
            } else {  
              console.error('Unable to subscribe to push.', e);  
              pushButton.disabled = false;  
              pushButton.textContent = 'Enable Push Messages';  
            }  
        });  
    });  
}

service-worker.js file code is:

self.addEventListener('push', function(event) {  
     event.waitUntil(
        fetch('https://example.com/message')
        .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 = data.notification.icon;  
                var notificationTag = data.notification.tag;

                return self.registration.showNotification(title, {  
                    body: message,  
                    icon: icon,  
                    tag: notificationTag 
                });  
            });  
        })
        .catch(function(err) {  
            console.error('Unable to retrieve data', err);

            var title = 'An error occurred';
            var message = 'We were unable to get the information for this push message';  
            var icon = URL_TO_DEFAULT_ICON;  
            var notificationTag = 'notification-error';  
            return self.registration.showNotification(title, {  
                body: message,  
                icon: icon,  
                tag: notificationTag  
            });  
        })  
    );  
});

self.addEventListener('notificationclick', function(event) {  
    console.log('On notification click: ', event.notification.tag);  
    event.notification.close();
    event.waitUntil(
        clients.matchAll({  
          type: "window"  
        })
        .then(function(clientList) {  
            for (var i = 0; i < clientList.length; i++) {  
                var client = clientList[i];  
                if (client.url == '/' && 'focus' in client)  
                    return client.focus();  
            }  
            if (clients.openWindow) {
                return clients.openWindow('/');  
            }
        })
    );
});

Send message using CURL:

$data = ["registration_ids" => ["token id"]];
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
$headers = [ 
    'Content-Type: application/json',
    'Authorization: key= MY-GOOGLE-KEY'   
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
curl_close ($ch);
$response = json_decode($result);

AND

curl --header "Authorization: key=KEY" --header "Content-Type: application/json" https://android.googleapis.com/gcm/send -d "{\"registration_ids\":[\"KEY\"]}"

Why it is not working for Firefox browser. THANKS :)

1
You send a request to android.googleapis.com/gcm/send, but you need to send a request to PushSubscription.endpoint which is valid URL. Also you can pass data with push message, to avoid additional request from service worker. - Dmitry Manannikov
@DmitryManannikov ok I checked endpoint, but i want to send message to multiple users at the time with CURL how it possible like chrome allow us to send multiple users - Harinder Singh
One user - one endpoint - one request to push provider. - Dmitry Manannikov

1 Answers

0
votes

Try to send on end point URL which browser gives, in case of Firefox endpoint url is different it is not https://fcm.googleapis.com/fcm/send. When you get subscription object, you will get endpoint also which is different in different browsers.

I just checked, Firefox endpoint is: https://updates.push.services.mozilla.com/wpush/v2