Firebase: رجیستر کردن Service Worker برای FCM

ابتدا در مورد Service Worker ها بخوانید. برای دیدن Worker ها در موزیلا به about:debugging و برای دیدن وضعیت Worker به about:config مراجعه کنید.

// Initialize Firebase
var config = {
  apiKey: "...",
  authDomain: "....firebaseapp.com",
  databaseURL: "https://....firebaseio.com",
  storageBucket: "....appspot.com",
  messagingSenderId: "..."
};

firebase.initializeApp(config);

messaging = firebase.messaging();

// Request permission.
messaging.requestPermission().then(function () {
  console.log('Notification permission granted.');
}).catch(function (err) {
  console.log('Unable to get permission to notify. ');
  console.log(err);
});

// Register firebase messaging service worker.
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sites/all/modules/custom/firebase/js/firebase-messaging-sw.js', {scope: '/sites/all/modules/custom/firebase/js/'}).then(function (registration) {

    // Set messaging service worker.
    messaging.useServiceWorker(registration);

    // Get Instance ID token. Initially this makes a network call, once retrieved
    // subsequent calls to getToken will return from cache.
    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.');
      }
    }).catch(function (err) {
      console.log('An error occurred while retrieving token. ');
      console.log(err);
    });

    // Callback fired if Instance ID token is updated.
    messaging.onTokenRefresh(function () {
      messaging.getToken().then(function (refreshedToken) {
        console.log(refreshedToken);
      }).catch(function (err) {
        console.log('An error occurred while retrieving token. ');
        console.log(err);
      });
    });

    // Retrieve an instance of Firebase Messaging so that it can handle background messages.
    messaging.onMessage(function (payload) {
      console.log("Message received. ", payload);
    });

    // Registration was successful.
//    console.log('ServiceWorker registration successful with scope: ', registration.scope);
//    registration.pushManager.subscribe({
//      userVisibleOnly: true
//    }).then(function (sub) {
//      console.log('endpoint:', sub.endpoint);
//    }).catch(function (e) {
//
//    });
  }).catch(function (err) {
    // registration failed.
//    console.log('ServiceWorker registration failed: ', err);
  });
}
برچسب ها: 

افزودن نظر جدید