Токен веб-push-уведомления Firebase не получает

#javascript #php #firebase #firebase-cloud-messaging #web-notifications

#javascript #php #firebase #firebase-облако-обмен сообщениями #веб-уведомления

Вопрос:

Я разработчик iOS, а не php, я внедряю веб-push-уведомления Firebase для отправки и получения в Интернете. Я использую xampp и php. Для этого я следовал этому руководству https://www.itwonders-web.com/blog/push-notification-using-firebase-demo-tutorial. Здесь я создал index1.html страницу и поместил ее в папку myphp, затем создал firebase-messaging-sw.js файл и места в той же папке. Я получаю предупреждение о разрешении, но токен равен нулю.

Смотрите скриншот ниже, это мой вывод.

введите описание изображения здесь

На самом деле здесь я использую локальный хост xampp, обязательно ли запускать веб-сайт в реальном времени для получения токена?

(Мой URL: http://192.168.64.2/myphp /)

Мой код

На самом деле index.html название страницы не получает оповещения, вот почему я заменил название страницы index1.html почему я не знаю, что он не показывает никаких файлов.

index1.html

 <html>
<title>Firebase Messaging Demo</title>
<style>
div {
    margin-bottom: 15px;
}
</style>
<body>
<div id="token"></div>
<div id="msg"></div>
<div id="notis"></div>
<div id="err"></div>
<script src="https://www.gstatic.com/firebasejs/5.9.0/firebase.js"></script>
<script>
    MsgElem = document.getElementById("msg")
    TokenElem = document.getElementById("token")
    NotisElem = document.getElementById("notis")
    ErrElem = document.getElementById("err")
    // Initialize Firebase
    // TODO: Replace with your project's customized code snippet
    var config = {
        apiKey: "AIza********yMSEK3PM",
        authDomain: "myf*********ject.firebaseapp.com",
        databaseURL: "https://myf*********ject.firebaseio.com",
        projectId: "myf******ject",
        storageBucket: "myf********ject.appspot.com",
        messagingSenderId: "67********7"
    };
    firebase.initializeApp(config);

    const messaging = firebase.messaging();
    messaging
        .requestPermission()
        .then(function () {
            MsgElem.innerHTML = "Notification permission granted." 
            console.log("Notification permission granted.");

            // get the token in the form of promise
            return messaging.getToken()
        })
        .then(function(token) {
            TokenElem.innerHTML = "token is : "   token
        })
        .catch(function (err) {
            ErrElem.innerHTML =  ErrElem.innerHTML   "; "   err
            console.log("Unable to get permission to notify.", err);
        });

    messaging.onMessage(function(payload) {
        console.log("Message received. ", payload);
        NotisElem.innerHTML = NotisElem.innerHTML   JSON.stringify(payload) 
    });
</script>

<body>
</body>
  

firebase-messaging-sw.js

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

// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
                   'messagingSenderId': '67******7'
                   });

// 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: '/itwonders-web-logo.png'
                                  };

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

если возможно, отправьте ссылку на подробное руководство по веб-push-уведомлениям Firebase.

Ответ №1:

Я также столкнулся с той же проблемой и смог решить это, переместив файл service worker в папку htdocs, т. е. корневую папку

Комментарии:

1. Я не получил вопрос. Не могли бы вы объяснить

2. на самом деле я использую локальный хост xampp для запуска своего веб-приложения. Достаточно ли нашего веб-приложения в режиме реального времени или локального хостинга.

3. локального хоста достаточно. Я выполнил тот же код на localhost xampp

4. Хорошо, но я не получаю никакого токена, не могли бы вы, пожалуйста, отправить свой тестовый код. Возможно ли это.

5. Можете ли вы общаться в комнате чата?