0

我正在开发一个使用 GCM 进行推送通知的 Web 应用程序。我正在关注此文档。我在文档中遇到了 initializeState 函数的问题。

这就是我添加服务工作者脚本的方式:我刚刚创建了一个 service-worker.js 空文件并在代码中指向该文件以注册服务。完全空的文件。

这是我的 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 是空的,所以它不起作用?如果没有,我怎样才能修复我的代码工作?

4

0 回答 0