Токен веб-push-уведомления 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 и поместил его в ту же папку. . Я получаю предупреждение о разрешении, но токен имеет значение null.

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

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

На самом деле здесь я использую локальный хост 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.


person iOS    schedule 16.03.2019    source источник


Ответы (1)


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

person Webdev    schedule 19.03.2019
comment
Я не понял вопроса. Могли бы вы объяснить - person Webdev; 19.03.2019
comment
на самом деле я использую локальный хост xampp для запуска своего веб-приложения. Достаточно ли нашего веб-приложения в режиме реального времени или локального хоста. - person iOS; 19.03.2019
comment
локального хоста достаточно. Я выполнил тот же код на локальном хосте xampp - person Webdev; 19.03.2019
comment
Хорошо, но я не получаю токен, не могли бы вы прислать свой тестовый код. Является ли это возможным. - person iOS; 19.03.2019
comment
Можно ли пообщаться в чате? - person Webdev; 19.03.2019
comment
Хорошо, пожалуйста, подождите - person iOS; 19.03.2019
comment
Давайте продолжим обсуждение в чате. - person iOS; 19.03.2019