Vue pwa with firebase cloud messaging not working

2019-01-29 08:09发布

问题:

im trying the following code:

    navigator.serviceWorker.register('service-worker.js')
      .then((registration) => {
        const messaging = firebase.messaging().useServiceworker(registration)
        console.log(messaging)
        messaging.requestPermission().then(function () {
          console.log('Notification permission granted.')
          messaging.getToken().then(function (currentToken) {
            if (currentToken) {
              console.log(currentToken)
            }
          })
        })
      })

my manifest:

{
  "name": "Herot-Eyes",
  "short_name": "herot-eyes",
  "gcm_sender_id": "103953800507",
  "icons": [
    {
      "src": "/static/img/icons/herot-eyes-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "/static/img/icons/herot-eyes-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    },
    {
      "src": "/static/img/icons/apple-touch-icon-180x180.png",
      "sizes": "180x180",
      "type": "image/png"
    }
  ],
  "start_url": "/",
  "display": "fullscreen",
  "orientation": "portrait",
  "background_color": "#000000",
  "theme_color": "#2196f3"
}

what is going wrong? my console.log(messaging) is returning a factory error, the following:

bad-push-set : "The FCM push set used for storage / lookup was not not a valid push set string." bad-scope

"The service worker scope must be a string with at least one character." bad-sender-id

"Please ensure that 'messagingSenderId' is set correctly in the options passed into firebase.initializeApp()." bad-subscription

"The subscription must be a valid PushSubscription." bad-token : "The FCM Token used for storage / lookup was not a valid token string." bad-vapid-key

"The public VAPID key is not a Uint8Array with 65 bytes." bg-handler-function-expected

"The input to setBackgroundMessageHandler() must be a function." delete-scope-not-found

"The deletion attempt for service worker scope could not be performed as the scope was not found." delete-token-not-found

"The deletion attempt for token could not be performed as the token was not found." failed-delete-vapid-key

"The VAPID key could not be deleted." failed-serviceworker-registration

"We are unable to register the default service worker. {$browserErrorMessage}" failed-to-delete-token

"Unable to delete the currently saved token." get-subscription-failed

"There was an error when trying to get any existing Push Subscriptions." incorrect-gcm-sender-id

"Please change your web app manifest's 'gcm_sender_id' value to '103953800507' to use Firebase messaging." invalid-delete-token

"You must pass a valid token into deleteToken(), i.e. the token from getToken()." invalid-public-vapid-key

"The public VAPID key must be a string." invalid-saved-token

"Unable to access details of the saved token." no-fcm-token-for-resubscribe

"Could not find an FCM token and as a result, unable to resubscribe. Will have to resubscribe the user on next visit." no-sw-in-reg

"Even though the service worker registration was successful, there was a problem accessing the service worker itself." no-window-client-to-msg

"An attempt was made to message a non-existant window client." notifications-blocked

"Notifications have been blocked." only-available-in-sw

"This method is available in a service worker context." only-available-in-window

"This method is available in a Window context." permission-blocked

"The required permissions were not granted and blocked instead." permission-default

"The required permissions were not granted and dismissed instead." public-vapid-key-decryption-failed

"The public VAPID key did not equal 65 bytes when decrypted." should-be-overriden

"This method should be overriden by extended classes." sw-reg-redundant

"The service worker being used for push was made redundant." sw-registration-expected

"A service worker registration was the expected input." token-subscribe-failed

"A problem occured while subscribing the user to FCM: {$message}" token-subscribe-no-push-set

"FCM returned an invalid response when getting an FCM token." token-subscribe-no-token

"FCM returned no token when subscribing the user to push." token-unsubscribe-failed

"A problem occured while unsubscribing the user from FCM: {$message}" token-update-failed

"A problem occured while updating the user from FCM: {$message}" token-update-no-token

"FCM returned no token when updating the user to push." unable-to-resubscribe

"There was an error while re-subscribing the FCM token for push messaging. Will have to resubscribe the user on next visit. {$message}" unsupported-browser

"This browser doesn't support the API's required to use the firebase SDK." use-sw-before-get-token

"You must call useServiceWorker() before calling getToken() to ensure your service worker is used."

回答1:

Configure to server to receive notifications

Add the following files to the public folder:

manifest.json

{
    "gcm_sender_id": "103953800507"
}

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');

var config = {
  messagingSenderId: <Sender ID>
};
firebase.initializeApp(config);

let messaging = firebase.messaging();

In your main.js file add the following code

var config = {
  apiKey: <API_KEY>,
  authDomain: <DOMAIN>,
  databaseURL: <DATABASE_URL>,
  projectId: <PROJECT_ID>,
  storageBucket: <STORAGE_BUCKET>,
  messagingSenderId: <SENDER_ID>
};
firebase.initializeApp(config);

Vue.prototype.$messaging = firebase.messaging()

navigator.serviceWorker.register('/firebase-messaging-sw.js')
  .then((registration) => {
    Vue.prototype.$messaging.useServiceWorker(registration)
  }).catch(err => {
    console.log(err)
  })

Receive notifications

Then in your App.vue, add this code to the created() function

created() {
    var config = {
        apiKey: <API_KEY>,
        authDomain: <DOMAIN>,
        databaseURL: <DATABASE_URL>,
        projectId: <PROJECT_ID>,
        storageBucket: <STORAGE_BUCKET>,
        messagingSenderId: <SENDER_ID>
    };
    firebase.initializeApp(config);
    const messaging = firebase.messaging();

    messaging
    .requestPermission()
    .then(() => firebase.messaging().getToken())
    .then((token) => {
        console.log(token) // Receiver Token to use in the notification
    })
    .catch(function(err) {
        console.log("Unable to get permission to notify.", err);
    });

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

Send notification

UPDATE

const admin = require("firebase-admin")

var serviceAccount = require("./certificate.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
});
const Messaging = admin.messaging()

var payload = {
    webpush: {
        notification: {
            title: "Notification title",
            body: "Notification info",
            icon: 'http://i.imgur.com/image.png',
            click_action: "http://yoursite.com/redirectPage" 
        },
    },
    topic: "Doente_" + patient.Username
};

return Messaging.send(payload)

Older version

Then, in postman you do the following request

POST /v1/projects/interact-f1032/messages:send HTTP/1.1
Host: fcm.googleapis.com
Authorization: Bearer <SENDER_TOKEN>
Content-Type: application/json

{
  "message":{
    "token" : The token that was in the console log,
    "notification" : {
      "body" : "This is an FCM notification message!",
      "title" : "FCM Message"
      }
   }
}

Sender Token

In your backend, use the following code, where the file "certificate.json" was got in the firebase dashboard (https://firebase.google.com/docs/cloud-messaging/js/client - Generate pair of keys)

const {google} = require('googleapis');

function getAccessToken() {
  return new Promise(function(resolve, reject) {
    var key = require('./certificate.json');
    var jwtClient = new google.auth.JWT(
      key.client_email,
      null,
      key.private_key,
      ["https://www.googleapis.com/auth/firebase", 
      "https://www.googleapis.com/auth/cloud-platform"],
      null
    );
    jwtClient.authorize(function(err, tokens) {
      if (err) {
        reject(err);
        return;
      }
      resolve(tokens.access_token);
    });
  });
}

getAccessToken().then(senderToken => console.log(senderToken))

The senderToken is used on the Authorization header to send a notification