I am trying to add Firebase Massaging to my VueJS PWA app, but I am getting the following error:
# ./src/main.js 6:0-28 28:13-16 # multi
(webpack)-dev-server/client?http://192.168.1.7:8080/sockjs-node
(webpack)/hot/dev-server.js ./src/main.js
manifest.json in the Public folder looks like :
"start_url": ".",
"display": "standalone",
"background_color": "#000000",
"theme_color": "#210499",
"gcm_sender_id": "103953800507"
firebase-messaging-sw.js in the public folder looks like :
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: "452219633362"
};
firebase.initializeApp(config);
let messaging = firebase.messaging();
App.vue file Looks like :
created() {
var config = {
apiKey: "My apiKey",
authDomain: "My firebase domain",
databaseURL: "database URL",
projectId: "Project ID",
storageBucket: "storage Bucket",
messagingSenderId: "Sender id "
};
firebase.initializeApp(config);
let 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);
// ...
});
}
main.js looks like :
import Vue from "vue";
import App from "./App.vue";
import firebase from "firebase";
import "../public/firebase-messaging-sw"
Vue.config.productionTip = false;
var config = {
apiKey: "My apiKey",
authDomain: "My firebase 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)
})
new Vue({
render: h => h(App)
}).$mount("#app");
I cannot point out what I did wrong. I did use Vue-Cli version 3. Can someone help me with this error?
Related
I'm new here. Been having issues with working with the firebase cloud messaging. Tried sending notification throught the the notification composer but it not promting any notification at my side. N:B I have no knowledge of backend technologies, so only implemented it in the front-end.
This is my code
// For the App.js folder
import { initializeApp } from "firebase/app";
import { getToken, getMessaging, onMessage } from "firebase/messaging";
const firebaseConfig = {
apiKey: "AIzaSyCy1TQbCwalPdU3sBf2sDKraxHpplamGQ8",
authDomain: "fir-project-test-44a6b.firebaseapp.com",
projectId: "fir-project-test-44a6b",
storageBucket: "fir-project-test-44a6b.appspot.com",
messagingSenderId: "648408030635",
appId: "1:648408030635:web:2a94b932f10e11abb6c6ee",
measurementId: "G-2YHQFP9KWX"
};
// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
Notification.requestPermission().then((permission) => {
if(permission === 'granted'){
console.log('permission granted')
}
})
.catch((err) => {
console.log('permission denied:', err)
})
getToken(messaging, {vapidKey: 'BMRthb-93vz-iQl0XQA8AsKbzMyLq-f2JCB00B2rMb35Z_1iVdWX8CquQ820-z6vyMmdDB0W46FIIS3R5IhTbXY'}).then((token) => {
console.log('my token is', token);
});
onMessage(messaging, (payload) => {
console.log(payload.notification);
new Notification(payload.notification.title, {
body:payload.notification.body
})
})
For the Service worker folder
import { getMessaging, onBackgroundMessage } from "firebase/messaging";
import { initializeApp } from "firebase/app";
importScripts("https://www.gstatic.com/firebasejs/9.16.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/9.16.0/firebase-messaging.js");
const firebaseConfig = {
apiKey: "AIzaSyCy1TQbCwalPdU3sBf2sDKraxHpplamGQ8",
authDomain: "fir-project-test-44a6b.firebaseapp.com",
projectId: "fir-project-test-44a6b",
storageBucket: "fir-project-test-44a6b.appspot.com",
messagingSenderId: "648408030635",
appId: "1:648408030635:web:2a94b932f10e11abb6c6ee",
measurementId: "G-2YHQFP9KWX"
};
// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
onBackgroundMessage(messaging, (payload) => {
console.log('received background messages:', payload)
const notificationTitle= payload.notification.notificationTitle
const notificationBody = {
body: payload.notification.body,
}
self.registration.showNotification(notificationTitle, notificationBody);
})
i would apprecitate if someone can come through for me. thanks[image 1(app.jsimage2 (app.js)](https://i.stack.imgur.com/tMoq2.png)
Tried evrything, but to no avail. I want to be able to send notifications to user via the notificTION COMPOSER
package.json
"firebase": "^9.14.0",
public/firebase-messaging-sw.js
`
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-messaging.js')
try {
const config = {
apiKey: "AIzaSyBzFxb1h0INNwZ2dKMF83PfoMXa2aCdXqM",
authDomain: "jobdoh-dc1db.firebaseapp.com",
projectId: "jobdoh-dc1db",
storageBucket: "jobdoh-dc1db.appspot.com",
messagingSenderId: "922163524694",
appId: "1:922163524694:web:a50be771626fa1356077f7",
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(payload => {
console.log("Payload :> ", payload)
return self.registration.showNotification("hello", { body: "aaa" })
})
} catch (err) {
console.log("err in sw :> ", err)
}
All console.log that in the firebase-messaging-sw.js are not working.
src/plugins/firebase.js
import { initializeApp, getApps } from 'firebase/app';
import { getMessaging } from 'firebase/messaging'
import '#firebase/app';
const config = {
apiKey: "AIzaSyBzFxb1h0INNwZ2dKMF83PfoMXa2aCdXqM",
authDomain: "jobdoh-dc1db.firebaseapp.com",
databaseURL: "https://jobdoh-dc1db-default-rtdb.asia-southeast1.firebasedatabase.app",
projectId: "jobdoh-dc1db",
storageBucket: "jobdoh-dc1db.appspot.com",
messagingSenderId: "922163524694",
appId: "1:922163524694:web:a50be771626fa1356077f7",
measurementId: "G-VJ4952421E"
};
const apps = getApps();
const app = !apps.length ? initializeApp(config) : apps[0];
const messaging = getMessaging(app)
export default messaging;
src/index.js
import {createApp} from "vue";
import firebaseMessaging from './plugins/firebase';
const app = createApp();
app.config.globalProperties.$messaging = firebaseMessaging;
app.mount("#app");
I declare the messaging service as a global properties.
And use it in the customPage(eg. NotiPage.vue)
src/pages/NotiPage.vue
<template>
<v-btn #click="getToken">Get Token</v-btn>
</template>
<script>
import { getMessaging, onMessage, getToken } from "firebase/messaging";
export default {
methods: {
async getToken() {
const token = await getToken(this.$messaging, {
ServiceWorkerRegistration: "/public/firebase-messaging-sw.js",
vapidKey:
"BKOVTA3E_8xNS8MqBNVWxv8bxlaOman4gaY5jXpMG-wpev19uWFANeyKy6rRDxfx8QEarlUSqwJ7UNiuripRA4c",
});
if (token) {
console.log(token); // I got the token
} else {
// Request permission
}
},
},
mounted(){
const message = getMessaging();
onMessage(message, (payload) => console.log("Messages :> "), payload)
}
}
</script>
I got the token and message on the console. But not show the noti popup in my chrome. I turn on my notification permission on my computer setting and allow the notification on my chrome.
This is console.log image.
Pls advice me. Where did I wrong?
I want to appear notification popup on my browser and running the process in background.
i've just tried to integrate firebase custom config at Vue. I'm newbie at this and got error like this
I already add firebase sdk to my project.
This is my main.js
Vue.config.productionTip = false
const config = {
apiKey: "######################",
authDomain: "######################",
databaseURL: "######################",
projectId: "######################",
storageBucket: "######################",
messagingSenderId: "######################",
appId: "######################",
measurementId: "######################"
};
firebase.initializeApp(config);
new Vue({
router,
vuetify,
render: h => h(App)
}).$mount('#app')
and I want to use firebase remote config on my View
<script>
import firebase from "firebase";
remoteConfig = firebase.remoteConfig();
// [START enable_dev_mode]
remoteConfig.settings = {
minimumFetchIntervalMillis: 3600000,
};
// [END enable_dev_mode]
// [START set_default_values]
remoteConfig.defaultConfig = ({
'is_auto_location': 'false',
});
// [END set_default_values]
remoteConfig.ensureInitialized()
.then(() => {
console.log('Firebase Remote Config is initialized');
setLocation();
})
.catch((err) => {
console.error('Firebase Remote Config failed to initialize', err);
});
function setLocation() {
this.isAutoLocation = remoteConfig.getString('is_auto_location');
}
</script>
please help.
Thankyou
import firebase in main.js file import * as firebase from 'firebase'
there have an awesome vuejs package for firebase call vuefire. you can use it
I have a firebase config file like this:
import { firebase } from "#firebase/app";
import "#firebase/firestore";
const firebaseApp = firebase.initializeApp({
apiKey: "myKey",
authDomain: "myDomain",
databaseURL: "myURL",
projectId: "myProject",
storageBucket: "myBucket",
messagingSenderId: "999999999"
});
export const db = firebaseApp.firestore();
export const firebaseApp = firebaseApp;
I am trying to authenticate a user but keep getting firebaseApp.auth() is not a function.
let me = db.collection('staff').where('email', '==', this.current_user.email)
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
this.fbUser = doc.id;
let email = doc.data().email;
let pw = doc.data().key;
firebaseApp.auth().onAuthStateChanged(user => {
if (user) {
//console.log('Already authenticated.');
} else {
firebaseApp.auth().signInWithEmailAndPassword(email, pw)
.then(liu => {
//console.log('Logged in', liu.uid);
let uid = liu.uid;
this.$localStorage.set('fbId',this.fbUser, 0);
this.$localStorage.set('fbAuthId', uid, 0);
me.update({
is_active: true
});
});
} // end if
});
});
Don't I have to configure the app? There's no auth functionality in #firebase.
Any help is appreciated.
You should add the auth Firebase service in your initialization, as follows:
import { firebase } from "#firebase/app";
import "#firebase/firestore";
import "#firebase/auth"; // <- NEW
const firebaseApp = firebase.initializeApp({
apiKey: "myKey",
authDomain: "myDomain",
databaseURL: "myURL",
projectId: "myProject",
storageBucket: "myBucket",
messagingSenderId: "999999999"
});
export const db = firebaseApp.firestore();
export const auth = firebaseApp.auth(); // <- NEW
export const firebaseApp = firebaseApp;
Then, in your component, you do:
auth.onAuthStateChanged(user => {})
and
auth.signInWithEmailAndPassword(email, pw)
I'm writing a web app with Nuxt.js and Firebase. In which file do I need to initialize the Firebase? In other words, where to put this code snippet?
var config = {
apiKey: "xxxxxxxxxx",
authDomain: "xxxxxxxxx.firebaseapp.com",
databaseURL: "https://xxxxxxxx.firebaseio.com",
projectId: "xxxxxxxxx",
storageBucket: "xxxxxxxxxxx.appspot.com",
messagingSenderId: "xxxxxxxxxx"
};
firebase.initializeApp(config);
Create file firebase.js in folder plugins.
import firebase from 'firebase'
import 'firebase/firestore' //if use firestore
if (!firebase.apps.length) {
firebase.initializeApp({
apiKey: "xxx",
authDomain: "xxx",
databaseURL: "xxx",
projectId: "xxx",
storageBucket: "xxx",
messagingSenderId: "xxx"
})
}
firebase.firestore().settings({ timestampsInSnapshots: true })
const db = firebase.firestore()
const storage = firebase.storage() //if use storage
export { storage, db }
In component:
import { db } from '~/plugins/firebase.js'
data() {
return {
users: []
}
},
mounted() {
db.collection("users").get().then((querySnapshot) => {
this.users = querySnapshot.docs.map(doc =>
Object.assign({ id: doc.id }, doc.data())
)
})
}