3

I have added the below script to my header to load service worker on load .When I load my website and check applications tab from inspect on browesr it shows nothing .

<?php $ajaxUrl = $block->getUrl('pwa/index/subscribeTopic'); ?>
<script type="text/javascript">
    require(["jquery"], function ($) {
        // Register Service Worker
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', function () {
                var baseUrl = '<?php echo $block->getBaseUrl() ?>';
                navigator.serviceWorker.register(baseUrl + 'serviceWorker.js').then(function (registration) {
                    // Registration was successful
                    console.log('ServiceWorker registration successful with scope: ', registration.scope);
                }, function (err) {
                    // registration failed :(
                    console.log('ServiceWorker registration failed: ', err);
                });
            });
        }

        function subscriberTopic() {
            messaging.getToken()
                .then(function (currentToken) {
                    if (currentToken) {
                        var subUrl = 'https://iid.googleapis.com/iid/v1/' + currentToken;
                        // subscriber topic
                        $.ajax({
                            url: '<?php echo $ajaxUrl ?>',
                            type: 'POST',
                            dataType: 'json',
                            data: {subUrl: subUrl},
                            success: function (response) {
                                console.log(response);
                            },
                            error: function () {
                                console.log("Cannot get data");
                            }
                        });
                    } else {
                        console.log('No Instance ID token available. Request permission to generate one.');
                    }
                })
                .catch(function (err) {
                    console.log('An error occurred while retrieving token. ', err);
                });
        }

        navigator.serviceWorker && navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {

            window.addEventListener('beforeinstallprompt', function (e) {
                // beforeinstallprompt Event fired

                // e.userChoice will return a Promise.
                // For more details read: https://developers.google.com/web/fundamentals/getting-started/primers/promises
                e.userChoice.then(function (choiceResult) {

                    console.log(choiceResult.outcome);

                    if (choiceResult.outcome === 'dismissed') {
                        console.log('User cancelled home screen install');
                    }
                    else {
                        console.log('User added to home screen');
                    }
                });
            });

            messaging.useServiceWorker(serviceWorkerRegistration);
            messaging.requestPermission()
                .then(function () {
                    console.log('Notification permission granted.');
                    subscriberTopic();
                })
                .catch(function (err) {
                    console.log('Unable to get permission to notify.', err);
                });

            messaging.onMessage(function (payload) {
                console.log("Message received. ");
                if (payload.notification) {
                    var notificationTitle = payload.notification.title;
                    var notificationOptions = {
                        body: payload.notification.body,
                        icon: payload.notification.icon,
                        badge: payload.notification.icon
                    };
                    serviceWorkerRegistration.showNotification(notificationTitle,
                        notificationOptions);
                }
            });

        });

    });
</script>

This is me serviceworker.js

/**  * @copyright Copyright (c) 2017 www.tigren.com  */ importScripts('https://www.gstatic.com/firebasejs/4.5.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/4.5.0/firebase-messaging.js');

firebase.initializeApp({
    'messagingSenderId': '243456161043' });

const messaging = firebase.messaging(); var CACHE_NAME = 'pwa-tigren-cache-v1'; var SWversion = '81';

self.addEventListener('install', function (event) {
    // Perform install steps
    event.waitUntil(
        self.skipWaiting()
    ); });

self.addEventListener('activate', function (event) {
    console.log('[ServiceWorker] Activate');
    event.waitUntil(
        caches.keys().then(function (cacheNames) {
            return Promise.all(
                cacheNames.map(function (cacheName) {
                    return caches.delete(cacheName);

                })
            );
        })
    );
    return self.clients.claim() });

self.addEventListener('fetch', function (event) {
    if (event.request.method !== 'POST' && event.request.url.toString() &&
        event.request.url.toString().indexOf('/admin/') === -1 &&
        event.request.url.toString().indexOf('/checkout/') === -1 &&
        event.request.url.toString().indexOf('/cart/') === -1 &&
        event.request.url.toString().indexOf('/key/') === -1 &&
        event.request.url.toString().indexOf('/adminhtml/') === -1 &&
        event.request.url.toString().indexOf('/serviceWorker/') === -1) {
        event.respondWith(
            caches.match(event.request)
                .then(function (response) {
                    // Cache hit - return response
                    if (response) {
                        return response;
                    }

                    // IMPORTANT: Clone the request. A request is a stream and
                    // can only be consumed once. Since we are consuming this
                    // once by cache and once by the browser for fetch, we need
                    // to clone the response.
                    var fetchRequest = event.request.clone();

                    return fetch(fetchRequest).then(
                        function (response) {
                            // Check if we received a valid response
                            if (!response || response.status !== 200 || response.type !== 'basic') {
                                return response;
                            }

                            // IMPORTANT: Clone the response. A response is a stream
                            // and because we want the browser to consume the response
                            // as well as the cache consuming the response, we need
                            // to clone it so we have two streams.

                            var responseToCache = response.clone();
                            caches.open(CACHE_NAME)
                                .then(function (cache) {
                                    cache.put(event.request, responseToCache);

                                });

                            return response;
                        }
                    );
                })
        );
    } });

messaging.setBackgroundMessageHandler(function (payload) {
    console.log('[serviceWorker.js] Received background message ', payload); });

self.addEventListener('notificationclick', function (event) {
    event.notification.close(); });

My site does not have ssl certificate . Is that could be the issue ? Please Help .

4
+25

PWAs/Service workers do require an SSL certificate/HTTPS.

You need HTTPS

During development you'll be able to use service worker through localhost, but to deploy it on a site you'll need to have HTTPS setup on your server.

Using service worker you can hijack connections, fabricate, and filter responses. Powerful stuff. While you would use these powers for good, a man-in-the-middle might not. To avoid this, you can only register service workers on pages served over HTTPS, so we know the service worker the browser receives hasn't been tampered with during its journey through the network.

GitHub Pages are served over HTTPS, so they're a great place to host demos.

If you want to add HTTPS to your server then you'll need to get a TLS certificate and set it up for your server. This varies depending on your setup, so check your server's documentation and be sure to check out Mozilla's SSL config generator for best practices.

Source - developers.google.com

  • cool that worked . Now I am getting push notifications as well but only to android . Is there any thing I have to do for iOs to recieve push notifications for pwa . – Melvin Sep 26 at 5:12
  • Safari (iOS and OSx) doesn't support push notifications yet, it's taking Apple a loooong time to add this functionality. caniuse.com/#search=push. For Safari desktop you can send push notifications with Apple's own method developer.apple.com/notifications/safari-push-notifications, as for iOS I don't think there is a way for PWAs to send push notifications yet :( – Ben Crook Sep 26 at 9:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.