2017-09-15 4 views
0

저는 자바 스크립트로 서비스 작업자와 firebase 웹을 처음 사용합니다. firebase에서 페이로드를 검색하여 사용자에게 알림을 표시하려고합니다. 이제 다음과 같은 문제로 고민하고 있습니다. 나는 서비스 노동자를 등록하려면 다음 스크립트를 사용하는 경우자바 스크립트에서 프런트 GUI로 초기화 된 firebase 인스턴스를 얻으십시오.

작동 무엇

, 나는 succeeded 응답을 얻을 것이다.

index.html을

<p id="status"></p> 

<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase.js"></script> 
<script> 

    if ('serviceWorker' in navigator) { 
     // Override the default scope of '/' with './', so that the registration applies 
     // to the current directory and everything underneath it. 
     navigator.serviceWorker.register('sw.js', {scope: './'}).then(function (registration) { 
      // At this point, registration has taken place. 
      // The service worker will not handle requests until this page and any 
      // other instances of this page (in other tabs, etc.) have been 
      // closed/reloaded. 
      document.querySelector('#status').textContent = 'succeeded'; 

     }).catch(function (error) { 
      // Something went wrong during registration. The service-worker.js file 
      // might be unavailable or contain a syntax error. 
      document.querySelector('#status').textContent = error; 
     }); 
    } else { 
     // The current browser doesn't support service workers. 
     var aElement = document.createElement('a'); 
     aElement.href = 'http://www.chromium.org/blink/serviceworker/service-worker-faq'; 
     aElement.textContent = 'unavailable'; 
     document.querySelector('#status').appendChild(aElement); 
    } 
</script> 

sw.js 문제가 무엇

importScripts('https://www.gstatic.com/firebasejs/4.3.0/firebase-app.js'); 
importScripts('https://www.gstatic.com/firebasejs/4.3.0/firebase-messaging.js'); 

var config = { 
    apiKey: "MY_API_KEY", 
    authDomain: "project-xxxxx.firebaseapp.com", 
    databaseURL: "https://project-xxxxx.firebaseio.com", 
    projectId: "project-xxxxx", 
    storageBucket: "project-xxxxx.appspot.com", 
    messagingSenderId: "xxxxx" 
}; 
firebase.initializeApp(config); 

const messaging = firebase.messaging(); 


messaging.setBackgroundMessageHandler(function (payload) { 
    console.log('[firebase-messaging-sw.js] Received background message ', payload); 
    // Customize notification here 
    const notificationTitle = 'Background Message Title'; 
    const notificationOptions = { 
     body: 'Background Message body.', 
     icon: '/firebase-logo.png' 
    }; 

    return self.registration.showNotification(notificationTitle, 
     notificationOptions); 
}); 

Uncaught FirebaseError: Messaging: This method is available in a Window context. (messaging/only-available-in-window).

messaging.requestPermission() 
    .then(function() { 
     console.log('Notification permission granted.' + messaging.getToken()); 

     messaging.getToken() 
      .then(function (currentToken) { 
       if (currentToken) { 
        console.log(currentToken); 
       } else { 
        // Show permission request. 
        console.log('No Instance ID token available. Request permission to generate one.'); 
        // Show permission UI. 
       } 
      }) 
      .catch(function (err) { 
       console.log('An error occurred while retrieving token. ', err); 
      }); 
     }) 
     .catch(function (err) { 
      console.log('Unable to get permission to notify.', err); 
     }); 

:이제 내 문제는 내가 콘솔이 나에게 알려주기 때문에 다음 스크립트는 윈도우 환경에서 작동하는 index.html을에서 서비스 노동자의 messaging 상수 처리하는 것을입니다 이제 등록에서 firebase 인스턴스를 가져 오거나 잘못된 이론입니까?

답변

0

서비스 작업자가 창 컨텍스트를 사용할 수 없습니다. 또한 윈도우에서 SW로 또는 그 반대로 공유 할 수 없습니다 (따라서 변수를 선언하고 둘 다에서 액세스 할 수 없습니다). 오류 메시지에서, Firebase 라이브러리는 윈도우 콘텍스트에 의존하기 때문에 SW 스크립트 내부에서 사용할 수 없습니다.

당신이하려는 일을 어떻게 처리해야할지 모르겠습니다.