Cannot initialize state with service worker in GCM for web application in Chrome

271 views Asked by At

I am developing an Web Application that uses GCM for push notifications. I am following this documentation. I am having problem with initializeState function in docs.

This is how I added service worker script: I just created a service-worker.js empty file and pointed to this file in code to register service. Totally empty file.

This is my JavaScript code

<script type="text/javascript">

        if ('serviceWorker' in navigator) {  
            navigator.serviceWorker.register("{{ url('js/service-worker.js') }}").then(initialiseState).catch(function(error){
                alert('Unable to register service worker for notification')
            });  

        } else {  
            alert('Your browser does not support service worker that is used to receive push notification');
        }  

        function subscribe()
        {
            alert('Subscribed')
        }

        function unsubscribe()
        {
            alert('Unsubscribed')
        }

        // the problem is inside this function. This function is called after service worker registration
        function initialiseState() {  
            if (!('showNotification' in ServiceWorkerRegistration.prototype)) {  
                alert("Notification is not supported in this browser")
                return;  
            }

            if (Notification.permission === 'denied') {  
                alert('Notifications are blocked')
                return;  
            }

            if (!('PushManager' in window)) {  
                alert('Push messaging is not supported in thiss browser'); 
                return;  
            }
            // Every code working until here. I already checked using else if to statement.

            // We need the service worker registration to check for a subscription  
            navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {        
                //The problem is here. It is not alerting anything
                alert('Ready to check')
            });  
        }

        </script>

I commented in the code to highlight where the problem is. What I know is it should alert anything if it is working. So it is not alerting anything. So I cannot do other steps. I checked the console and it is not showing any error. Is it not working because my service-worker.js is empty? If not, how can I fix my code to work?

0

There are 0 answers