Home » Php » javascript – Service Worker not receiving push message

javascript – Service Worker not receiving push message

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m trying to implement push messages. I followed a tutorial to register a service worker and a push service subscription :

    //requesting notification permisison
    Notification.requestPermission(status => {
        console.log('Notification permission status:', status);
        if (status == 'granted') {

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

                navigator.serviceWorker.register('/sw.js')
                    .then(function (registration) {
                        console.log('ServiceWorker registration successful with scope: ', registration.scope);

                    })
                    .catch(function (error) {
                        console.error('Service Worker Error', error);
                    });
            } else {
                console.error('Push messaging is not supported');
            }

        } else {
            console.warn("Notifications denied");
        }
    });


    navigator.serviceWorker.ready.then(function (registration) {
        registration.pushManager.subscribe({
                userVisibleOnly: true,
                applicationServerKey: urlBase64ToUint8Array(
                    '<mypublickey>'
                )
            })
            .then(function (subscription) {
                //successfull
                console.log('push service subscription successfull: ' + JSON.stringify(subscription));
            })
            .catch(function (e) {
                console.error(e);
            })
    })


    function urlBase64ToUint8Array(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;
    }

In my browser console, I get the following subscription

push service subscription successfull:{
    "endpoint":"https://fcm.googleapis.com/fcm/send/id",
    "expirationTime":null,
    "keys":{
        "p256dh":"myp256dh",
        "auth":"myauth"
    }
}

Then to send my push, I’m using the web-push php library. Here’s my code to send a push :

    <?php

    use Minishlink\WebPush\MessageSentReport;
    use Minishlink\WebPush\WebPush;
    use Minishlink\WebPush\Subscription;

    class Test
    {

        public function execute()
        {


            $auth = [

                'VAPID' => [
                    'subject' => 'mailto:[email protected]', 
                    'publicKey' => 'mypubkey',
                    'privateKey' => 'myprivatekey'

                ]
            ];



            $notifications = [
                [
                    'subscription' => Subscription::Create([
                        "endpoint" => 'myendpoint',
                        "keys" => [
                            'p256dh' => 'myp256dh',
                            'auth' => 'myauth'
                        ],
                    ]),
                    'payload' => '{"msg":"hello world!"}'
                ]
            ];

            $webPush = new WebPush($auth);

            $webPush->sendNotification(
                $notifications[0]['subscription'],
                $notifications[0]['payload']
            );

            /** @var MessageSentReport $report */

            foreach ($webPush->flush() as $report) {
                $endpoint = $report->getEndpoint();

                if ($report->isSuccess()) {
                    echo "[v] Message sent successfully for subscription {$endpoint}.";
                } else {
                   echo $report->getReason();

                }
            }
        }
    }

And this is what I’m getting from this code

[v] Message sent successfully for subscription myendpoint.

And this does not trigger any notification in the browser. I’m using chrome, and the ‘send test push message’ in the dev tools works and displays a notification. There aren’t any log in the browser console when I execute my php code to send the notification. I have also tried in Firefox and have reached the same results.

Any idea what could be wrong ?

Here’s my service worker

sw.js

    self.addEventListener('push', event => {
      console.log('received a push!');

      event.waitUntil(
        self.registration.showNotification('This is a push');
      );
    });
How to&Answers: