firebasevue.jsfirebase-cloud-messagingservice-workermobile-chrome

The webpage on mobile is blank when Firebase and ServiceWorkert are initialized in a Vue CLI project


(I'm new to VueJS and Firebase)

Hello! I have a very weird problem with my project. I have been trying to add FCM (Firebase Cloud Messaging) to my Vue CLI project.

This is the code of my main.js that works completely fine in my PC chrome browser:

import Vue from "vue";
import "./plugins/axios";
import App from "./App.vue";
import vuetify from "./plugins/vuetify";
import router from "./router";
import firebase from "firebase/app";
import 'firebase/messaging'

firebase.initializeApp({"...Firebase config here..."});

let messaging = firebase.messaging(); 
export { messaging };


export default Vue.use(vuetify, {});
Vue.prototype.$messaging = messaging;
Vue.config.productionTip = false;

navigator.serviceWorker.register('./firebase-messaging-sw.js')
  .then((registration) => {
    Vue.prototype.$messaging.useServiceWorker(registration)
  })
  .catch(err => {
    console.log("Service worker registration error at main.js:", err)
  })

new Vue({
  vuetify,
  router,
  render: h => h(App)
}).$mount("#app");

But, when I try to open the website on my smartphone, via Android's Chrom browser, it shows me only a blank page, when only the favicon if loaded.

(I use the npm run serve command to run the local serve, to which I connect on my PC and my smartphone.)

But, when I comment out, the following parts:

let messaging = firebase.messaging();

and,

navigator.serviceWorker.register('./firebase-messaging-sw.js')
.then((registration) => {
 Vue.prototype.$messaging.useServiceWorker(registration)
 })
 .catch(err => {
  console.log("Service worker registration error at main.js:", err)
})

the webpage on my smartphone loads the UI just fine without any other problems.

What am I doing wrong, and how can I fix this?

P.S: this is my firebase-messaging-sw.js file, (which is located in the public directory of my project) if you need it:

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

firebase.initializeApp({ messagingSenderId: "MY_MSGING_SENDER_ID" });

const messaging = firebase.messaging();

Solution

  • TL;DR: Make sure you run over HTTPS when you are working with Service-Workers.

    Ok, so... apparently I completley forgot, that service-workers work ONLY over HTTPS. Previously I was testing FCM on my PC, and I added an exception to

    chrome://flags/#unsafely-treat-insecure-origin-as-secure

    but I didn't do so on my smartphone, and that's why it didn't work.