2

I'm working on an app that uses the Twilio Programmable Chat API using node.js and angular js. I have enabled push configuration inside twilio chat instance. And i have created push credentilals in twilio with the firebase secret key. After this i have fetched the twilio token using chatGrant with the twilio credential sid. I have included the firebase.js file and initialised firebase. After this I got permission from user to show notification. This all works fine. But when I am trying to get device token to register with chatclientinstance, it is getting failed. Here is my code which initialising the firebase and taking permission,

 var config = {
      apiKey: "my_key",
      authDomain: "example.firebaseapp.com",
      databaseURL: "https://example.firebaseio.com",
      projectId: "example",
      storageBucket: "example.appspot.com",
      messagingSenderId: "861813283864"
    };
    if (firebase) {
      firebase.initializeApp(config);
      console.log("firbase initialized.");
    }

    if (firebase && firebase.messaging()) {
      // requesting permission to use push notifications
      firebase.messaging().requestPermission().then(() => {
        // getting FCM token
        console.log("got permission for showing notification.");
        firebase.messaging().getToken().then((fcmToken) => {
          // continue with Step 7 here 
          console.log("got fcm token.",fcmToken);
          // ... 
          // ... 
        }).catch((err) => {
          // can't get token
          console.log("error in getting token for notification.",err);
        });
      }).catch((err) => {
        // can't request permission or permission hasn't been granted to the web app by the user
        console.log("error in getting permission for notification.",err);
      });
    } else {
      // no Firebase library imported or Firebase library wasn't correctly initialized
      console.log("no Firebase library imported or Firebase library wasn't correctly initialized");
    }

}

I got this in console,

firbase initialized.
got permission for showing notification.
The script has an unsupported MIME type ('text/html').
Failed to load resource: net::ERR_INSECURE_RESPONSE                 firebase-messaging-sw.js 
error in getting token for notification. 
e {code: "messaging/failed-serviceworker-registration", message: "Messaging: We are unable to register the default s…). (messaging/failed-serviceworker-registration).", browserErrorMessage: "Failed to register a ServiceWorker: The script has an unsupported MIME type ('text/html').", stack: "FirebaseError: Messaging: We are unable to registe…o/polyfills.bundle.js:3152:35)↵    at <anonymous>"}

I have did everything as twilio docs says at PUSH NOTIFICATIONS ON WEB

But I did not added "firebase-messaging-sw.js" in my server. Is there any need to add this js file or twilio will automatically create and initialise it?

Please find me a solution for this. Thanks in advance.

KENdi
  • 7,576
  • 2
  • 16
  • 31
anoop v m
  • 141
  • 1
  • 8

1 Answers1

3

I found this confusing too, since the docs don't explain what the notification support actually does. The code you included (from their chat SDK docs) only does two basic things:

  • client.setPushRegistrationId('fcm', fcmToken) makes sure the browser is registered with the FCM service and requests Twilio Programmable Chat notifications.
  • messaging.onMessage(function(payload{client.handlePushNotification(payload);}); seems to do very little--it simply lets the Chat client emit an event when FCM receives a message.

What it does not do, though, is create a service that listens for notifications. That's where the missing file comes in. First, create this file, firebase-messaging-sw.js somewhere. I used the following example from the Firebase docs:

// firebase sample code snippets from https://firebase.google.com/docs/cloud-messaging/js/client
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing in the essagingSenderId.
console.log("Initializing service worker...");
firebase.initializeApp({
  messagingSenderId: "<FILL IN FROM YOUR FIREBASE CONFIG>"
});

// Retrieve an instance of Firebase Messaging so that it can handle background messages.
var messaging = firebase.messaging();

// Listen for push messages and create notifications
messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  var notificationTitle = "My Notification Title";
  var notificationOptions = {
    body: "My Notification Text"
  };

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

This is a basic service worker that listens for notifications and then displays them.

Next, from the error message, you might have noticed that FCM is looking for this file to be served from your web root directory. If that's not the case, tweak your Twilio code slightly to look for this service worker at a specified URL (from https://stackoverflow.com/a/41701594/4006592):

var messaging = firebase.messaging();
if (messaging) {
  navigator.serviceWorker.register("<URL FOR firebase-messaging-sw.js>").then(function(registration) {
    messaging.useServiceWorker(registration);

    // requesting permission to use push notifications
    messaging.requestPermission().then(function() {
      ...
    });
  });
}

With the above change, you can explicitly specify where firebase-messaging-sw.js is located, and FCM/Twilio Chat will then work as expected.

SMX
  • 1,372
  • 15
  • 14