Интеграция Firebase с моим веб-приложением для отправки уведомлений - PullRequest
1 голос
/ 03 октября 2019

Я как бы застрял с firebase, и любая помощь будет оценена. Моя цель заключается в том, чтобы тот, кто открывает мою страницу, получал уведомление о разрешении / блокировке. Кто бы ни разрешал уведомления, я хочу отправлять ему уведомления в будущем через https://console.firebase.google.com - Облачное приложение для обмена сообщениями.

Я чего-то достиг, когда я открываю свою веб-страницу через https, я получаю уведомление, хочу ли яразрешить или нет

enter image description here

После разрешения, когда я пытаюсь отправить сообщение через облако всем участникам проекта, я ничего не получаю.

ПервыйЯ установил конфигурацию firebase

<script>
  // Your web app's Firebase configuration 
  var config = {
    apiKey: "AIzaSyDX5nRZCEI-wxp7L7TzI3lYQXlFlIZq7Rw",
    authDomain: "braintech-6f3cf.firebaseapp.com",
    databaseURL: "https://xxxx.firebaseio.com",
    projectId: "braintech-6f3cf",
    storageBucket: "",
    messagingSenderId: "xxxx",
    appId: "1:747770571255:web:da58976e57ebeb0835a6f2",
    measurementId: "G-73HKECM57P"
  };
  // Initialize Firebase
  firebase.initializeApp(config); 
  // Retrieve Firebase Messaging object.

const messaging = firebase.messaging();
 function setTokenSentToServer(sent) {
window.localStorage.setItem('sentToServer', sent ? '1' : '0');
}

function sendTokenToServer(currentToken) {
    if (!isTokenSentToServer()) {
      console.log('Sending token to server...');
      // TODO(developer): Send the current token to your server. 
      setTokenSentToServer(true);
    } else {
      console.log('Token already sent to server so won\'t send it again ' +
          'unless it changes');
    }
} 

function isTokenSentToServer() {
    return window.localStorage.getItem('sentToServer') === '1';
  }
function getRegisterToken(){
  // Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken().then((currentToken) => {
  if (currentToken) {
    sendTokenToServer(currentToken);

    console.log(currentToken);
    updateUIForPushEnabled(currentToken);
  } else {
    // Show permission request.
    console.log('No Instance ID token available. Request permission to generate one.');
    // Show permission UI.
    updateUIForPushPermissionRequired();
    setTokenSentToServer(false);
  }
}).catch((err) => {
  console.log('An error occurred while retrieving token. ', err);
  showToken('Error retrieving Instance ID token. ', err);
  setTokenSentToServer(false);
});  
}
function showToken(currentToken) {
    // Show token in console and UI.
    const tokenElement = document.querySelector('#token');
    tokenElement.textContent = currentToken;
  }

В журнале консоли я получаю сообщение о том, что токен отправлен на сервер. Но когда я пытаюсь отправить сообщения, ничего не происходит. Также в firebase-messaging-sw.js, который находится в той же папке, что и индексный файл,

// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here, other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
  var config = {
    apiKey: "AIzaSyDX5nRZCEI-wxp7L7TzI3lYQXlFlIZq7Rw",
    authDomain: "xxxx.firebaseapp.com",
    databaseURL: "https://xxx.firebaseio.com",
    projectId: "xxx",
    storageBucket: "",
    messagingSenderId: "xxxx",
    appId: "1:747770571255:web:da58976e57ebeb0835a6f2",
    measurementId: "G-73HKECM57P"
  };
  // Initialize Firebase
  firebase.initializeApp(config); 
  // Retrieve Firebase Messaging object.

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages. 
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);
});

Не знаете, что не так? Любая помощь будет оценена

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...