admin管理员组

文章数量:1180551

So I need to implement web push notifications in our web app, I have successfully setup the firebase cloud messaging in my app with the help of docs, I'm able to ask the user to allow permission for notifications and get the token id as well if he accepts the permission.

The thing is when I try to send a notification to test to the generated token, I'm getting a response that the message is sent, but I'm not able to receive it on the client side.

My index.html

<head>
  <script src=".4.0/firebase.js"></script>
  <link rel="manifest" href="./firebase.json">
</head>
 <script>
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('./firebase-messaging-sw.js').then(function(registration) {
      console.log('Firebase Worker Registered');

    }).catch(function(err) {
      console.log('Service Worker registration failed: ', err);
    });
  }
  </script>

I'm successfully able to register the service worker file

My Appponent.ts

var config = {
            apiKey: "somekey",
            authDomain: "someproject-2.firebaseapp",
            databaseURL: "",
            projectId: "someproject-2",
            storageBucket: "",
            messagingSenderId: "someid"
          };
          firebase.initializeApp(config);



        const messaging = firebase.messaging();

        messaging.requestPermission()
        .then(function() {
          console.log('Notification permission granted.');
          return messaging.getToken()
        })
        .then(function(result) {
            console.log("The token is: ", result);
        })
        .catch(function(err) {
          console.log('Unable to get permission to notify.', err);
        });

        messaging.onMessage(function(payload) {
        console.log("Message received. ", payload);
        });

I'm getting the permission dialog box asking permission and getting a token with this code

The curl code I used to send messages

curl -X POST -H "Authorization: key=somekey" -H "Content-Type: application/json" -d '{
  "notification": {
    "title": "Portugal vs. Denmark",
    "body": "5 to 1",
    "icon": "firebase-logo.png",
    "click_action": "http://localhost:8081"
  },
  "to": "sometoken"
}' ""

I'm able to successfully send notifications with this code

I can't figure out where I'm going wrong, maybe because it's on localhost? maybe the onMessage method is not running properly? Any help is highly appreciated!

So I need to implement web push notifications in our web app, I have successfully setup the firebase cloud messaging in my app with the help of docs, I'm able to ask the user to allow permission for notifications and get the token id as well if he accepts the permission.

The thing is when I try to send a notification to test to the generated token, I'm getting a response that the message is sent, but I'm not able to receive it on the client side.

My index.html

<head>
  <script src="https://www.gstatic.com/firebasejs/4.4.0/firebase.js"></script>
  <link rel="manifest" href="./firebase.json">
</head>
 <script>
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('./firebase-messaging-sw.js').then(function(registration) {
      console.log('Firebase Worker Registered');

    }).catch(function(err) {
      console.log('Service Worker registration failed: ', err);
    });
  }
  </script>

I'm successfully able to register the service worker file

My App.component.ts

var config = {
            apiKey: "somekey",
            authDomain: "someproject-2.firebaseapp.com",
            databaseURL: "https://someproject-2.firebaseio.com",
            projectId: "someproject-2",
            storageBucket: "",
            messagingSenderId: "someid"
          };
          firebase.initializeApp(config);



        const messaging = firebase.messaging();

        messaging.requestPermission()
        .then(function() {
          console.log('Notification permission granted.');
          return messaging.getToken()
        })
        .then(function(result) {
            console.log("The token is: ", result);
        })
        .catch(function(err) {
          console.log('Unable to get permission to notify.', err);
        });

        messaging.onMessage(function(payload) {
        console.log("Message received. ", payload);
        });

I'm getting the permission dialog box asking permission and getting a token with this code

The curl code I used to send messages

curl -X POST -H "Authorization: key=somekey" -H "Content-Type: application/json" -d '{
  "notification": {
    "title": "Portugal vs. Denmark",
    "body": "5 to 1",
    "icon": "firebase-logo.png",
    "click_action": "http://localhost:8081"
  },
  "to": "sometoken"
}' "https://fcm.googleapis.com/fcm/send"

I'm able to successfully send notifications with this code

I can't figure out where I'm going wrong, maybe because it's on localhost? maybe the onMessage method is not running properly? Any help is highly appreciated!

Share Improve this question edited Sep 28, 2017 at 7:33 Manzur Khan asked Sep 28, 2017 at 6:31 Manzur KhanManzur Khan 2,4864 gold badges25 silver badges46 bronze badges 3
  • Service worker does not work on unsecure origins. so your localhost must have to be on https. – Touqeer Shafi Commented Oct 3, 2017 at 13:50
  • Did you find the problem? I have exactly the same problem. – chrisonline Commented Oct 8, 2017 at 21:01
  • No bro, will let you know if I find out – Manzur Khan Commented Oct 9, 2017 at 6:19
Add a comment  | 

3 Answers 3

Reset to default 19

Alright, I didn't get any answers for this on stackoverflow, so I have to do it on my own and got it working!

The problem was in the service worker file, I have apparently not defined messaging variable.

If anybody is facing this issue, just make sure your service worker file looks something like this.

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

firebase.initializeApp({
    'messagingSenderId': '182145913801'
  });

const messaging = firebase.messaging();

I had a similar issue and I went to cloud messaging on firebase and got my Server key and added that to the curl request.

curl --header  "Authorization: key=CloudMessagingServerKey" --header  "Content-Type: application/json" -d '{
     "notification": {
        "title": "FCM Message",
        "body": "This is an FCM Message",
      },
     "to": "token from messaging.getToken()"
     }' "https://fcm.googleapis.com/fcm/send"

and my firebase-messaging-sw.js looked like the code below

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

firebase.initializeApp({
  apiKey: 'yourapikey',
  authDomain: 'xxxx.firebaseapp.com',
  databaseURL: 'https://xxxx.firebaseio.com',
  projectId: 'xxxx',
  storageBucket: 'xxxx.appspot.com',
  messagingSenderId: 'your message sender Id',
});

const messaging = firebase.messaging();

That did the trick for me. My errors were I was using a wrong serverKey and I did not use importScripts in my firebase-messaging-sw.js

As stated on FCM website:

The FCM SDK is supported only in pages served over HTTPS. This is due to its use of service workers, which are available only on HTTPS sites.

See https://firebase.google.com/docs/cloud-messaging/js/client

本文标签: javascriptNot receiving FCM Push Notification for web on localhostStack Overflow