无法在GCM中使用服务工作者为Chrome中的Web应用程序初始化状态

时间:2016-06-25 06:31:52

标签: push-notification google-api google-cloud-messaging service-worker chrome-gcm

我正在开发一个使用GCM进行推送通知的Web应用程序。我正在关注此文档 - https://developers.google.com/web/updates/2015/03/push-notifications-on-the-open-web?hl=en。这是我问的这个问题的后果问题 - https://stackoverflow.com/questions/38018061/cannot-register-service-worker-and-initialize-push-notification-in-gcm-for-web-w?noredirect=1#comment63479890_38018061。我在docs中遇到了initializeState函数的问题。请参阅下面的代码。

这就是我添加服务工作者脚本的方式。

I just created a service-worker.js empty file and pointed to this file in code to register service. Totally empty file.

这是我的JavaScript代码

<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>

我在代码中评论说明了问题所在。我所知道的是,如果有效,它应该提醒任何事情。所以它没有提醒任何事情。所以我不能做其他的步骤。我检查了控制台,但没有显示任何错误。是不行,因为我的service-worker.js是空的?如果没有,我如何修复我的代码?

0 个答案:

没有答案