FCM browser notification not working in Vue 3 - javascript

Here's my code. So far I've managed to get the background notification working. (Onmessage not working)
"firebase": "^9.6.7",
firebase-messaging-sw.js
null
App.vue
import { initializeApp } from 'firebase/app';
import { getMessaging, getToken, onMessage } from "firebase/messaging";
const firebaseConfig = {
apiKey: "AIzaSyDXnUaeAK",
authDomain: "test-test.firebaseapp.com",
projectId: "test-test",
storageBucket: "test-test.appspot.com",
messagingSenderId: "123456789",
appId: "1:38296:web:j88054626",
measurementId: "X-TEST"
};
initializeApp(firebaseConfig);
const messaging = getMessaging();
getToken(messaging, { vapidKey: 'key' })
.then((currentToken) => {
console.log("currentToken", currentToken);
})
onMessage(messaging, (payload) => {
console.log('Message received. ', payload);
// ...
});

Related

Not receving notification by onMessage and OnonBackgroundMessage in firebase cloud messaging

I am trying to integrate firebase cloud messaging for notifications, I have added a firebase configure file in App.js and add a service worker (firebase-messaging-sw.js) file in the root (public folder).
while heating an API "https://fcm.googleapis.com/fcm/send", I am getting a message, but it only receives in the background and in the notification, it is not sowing any data, that I have sent by API, It sends just a message "The site has been updated in the background"
file app.js
const firebaseConfig = {
apiKey: "AIz.........................",
authDomain: "firebase project",
projectId: "projectId......",
storageBucket: "storageBucket........",
messagingSenderId: "5487851245788....",
appId: "546497946497995....",
measurementId: "D-54646464646446",
};
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
console.log("messaging: ", messaging)
const VapidKey = "BK08o6mE9WMPK5Wovhkn-..............."
const subscribe = () => {
Notification.requestPermission().then((permission) => {
console.log("permission: ", permission);
if (permission === "granted") {
firebaseToken(messaging, { vapidKey: VapidKey }).then((currentToken) => {
console.log("CurrentToken firebase: ", currentToken);
storeFirebaseToken(currentToken)
}).catch((err) => {
console.log("err: ", err)
})
}
})
}
useEffect(() => {
subscribe();
}, [])
file firebase-messaging-sw.js
import { initializeApp } from "firebase/app";
import { getMessaging, onMessage} from "firebase/messaging/sw";
import { onBackgroundMessage } from "firebase/messaging/sw";
const firebaseConfig = {
apiKey: "AIz.........................",
authDomain: "firebase project",
projectId: "projectId......",
storageBucket: "storageBucket........",
messagingSenderId: "5487851245788....",
appId: "546497946497995....",
measurementId: "D-54646464646446",
};
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
onBackgroundMessage(messaging, (payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
// self.registration.showNotification(notificationTitle,
// notificationOptions);
});
onMessage(messaging, (payload) => {
console.log('Message received. ', payload);
// ...
});
I have added Onmessage and background methods in firebase-messaging-sw.js file, but I am not getting in that method,
I am expecting to receive a notification with title and icon and want to implement a click function on that

Why am I unable to sign in anonymously as an authenticated user in firebase?

I am trying to login as an authenticated user anonymously. Here is my code:
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js';
import { getAuth, onAuthStateChanged } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-auth.js";
const firebaseConfig = {
apiKey: "key_here",
authDomain: "project.firebaseapp.com",
projectId: "project",
storageBucket: "project.appspot.com",
messagingSenderId: "id_here",
databaseURL: "https://project-default-rtdb.firebaseio.com",
appId: "app_id_here"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth();
document.getElementById("login").addEventListener("click",function(event){
event.preventDefault();
onAuthStateChanged(auth, (user) => {
if(user){
//user can successfully login
}
else{
console.log("Something went wrong");
}
}, (error) => console.error(error)) //Nothing prints here
}
I was able to successfully log in 'til yesterday. But since this morning I keep getting the error Something went wrong in my console.
I didn't change anything in the code, nor in my firebase credentials. Where am I going wrong?
It was so silly of me to not read the documentation page carefully, I had forgotten to execute the signInAnonymously() method before checking for the user's data, the complete code is as follows:
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js';
import { getAuth, onAuthStateChanged, signInAnonymously } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-auth.js";
const firebaseConfig = {
apiKey: "key_here",
authDomain: "project.firebaseapp.com",
projectId: "project",
storageBucket: "project.appspot.com",
messagingSenderId: "id_here",
databaseURL: "https://project-default-rtdb.firebaseio.com",
appId: "app_id_here"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth();
document.getElementById("login").addEventListener("click",function(event){
event.preventDefault();
signInAnonymously(auth)
.then(() => {
onAuthStateChanged(auth, (user) => {
if(user){
//user can successfully login
}
else{
console.log("Something went wrong");
}
});
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
console.log(errorCode+": "+errorMessage);
});
});

#firebase/app-check: AppCheck: Requests throttled due to 400 error. Attempts allowed again after 00m:01s (appCheck/throttled)

I have just set up my app and integrated appcheck
and the code looks like
import { initializeApp, getApps } from "firebase/app";
import { getAuth, } from "firebase/auth";
import { getAnalytics } from "firebase/analytics";
import { getFirestore } from "firebase/firestore";
let app;
if (!getApps().length) {
app = initializeApp({
apiKey: process.env.NEXT_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
databaseURL: process.env.NEXT_PUBLIC_DATABASE_URL,
messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_ID,
appId: process.env.NEXT_PUBLIC_APP_ID,
});
}
async function initialize() {
const { initializeApp } = require("firebase/app");
const { initializeAppCheck, ReCaptchaV3Provider } = require("firebase/app-check");
const app = initializeApp({
apiKey: process.env.NEXT_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
databaseURL: process.env.NEXT_PUBLIC_DATABASE_URL,
messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_ID,
appId: process.env.NEXT_PUBLIC_APP_ID,
});
return initializeAppCheck(app, {
provider: new ReCaptchaV3Provider(process.env.NEXT_PUBLIC_APP_CHECK_KEY),
isTokenAutoRefreshEnabled: true
});
}
if (typeof window !== "undefined") {
initialize().then((res)=>{
// console.log(res)
}).catch((err)=>{
throw(err)
})
}
export const auth = getAuth();
export const db = getFirestore();
export default app;
So when i set isTokenAutoRefreshEnabled to true, the error comes up and when I set it to false everything works.
I am using firebase ^9.9.4 and this gives the above error so I decided to downgrade and use firebase ^9.8.2 since I had set up a different project the same way and there were no errors. In this version, I get the error
FirebaseError: AppCheck: Fetch server returned an HTTP error status. HTTP status: 400. (appCheck/fetch-status-error).
at exchangeToken
What is this error and how can I fix it

TypeError: _app.default.auth is not a function - React Native Web - Firebase

I am currently developing a project on React Native Web and this is my login call in a component. (The call is in the components useEffect, as soon as the component opens, it should log in anonymously)
import firebase from 'firebase/compat/app'
import 'firebase/compat/auth'
const firebaseConfig = {
apiKey: "****",
authDomain: "****",
projectId: "****",
storageBucket: "****",
messagingSenderId: "****",
appId: "****",
measurementId: "****"
};
firebase.initializeApp(firebaseConfig)
const login = async () => {
firebase.auth().signInAnonymously()
.then((userCredential) => {
// Signed in
// ...
})
.catch((error) => {
console.log("LOG: "+error)
});
}
But everytime I get the error: Uncaught (in promise) TypeError: _app.default.auth is not a function
I tried several different imports, but none of them seemed to work.
I see the error when I open the Console on Firefox. How can I fix this issue?
Thanks
Try this approach by checking if firebase is initialized and the user is not logged in:
const [loggedIn, setLoggedIn] = React.useState(false)
React.useEffect(() => {
if (!firebase.apps.length) {
firebase.initializeApp({
apiKey: "****",
authDomain: "****",
projectId: "****",
storageBucket: "****",
messagingSenderId: "****",
appId: "****",
measurementId: "****"
});
}
}, [])
React.useEffect(() => {
if (firebase.apps.length && !loggedIn) {
setLoggedIn(true)
login()
}
}, [firebase])
const login = async () => {
firebase.auth().signInAnonymously()
.then((userCredential) => {
// Signed in
// ...
})
.catch((error) => {
console.log("LOG: " + error)
});
}

How to setup Firebase Cloud Messaging v9 in React?

I'm having trouble setting up my firebase environment in React.
I'm going through the firebase documentation, but I can't seem to get the first step of getting permission correct.
I tried looking everywhere to fix these errors, but all attempts failed. Please help!
Errors:
Service worker registration failed, error: TypeError: Failed to register a ServiceWorker for scope ('http://localhost:8080/') with script ('http://localhost:8080/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script.
An error occurred while retrieving token. FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:8080/firebase-cloud-messaging-push-scope') with script ('http://localhost:8080/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script. (messaging/failed-service-worker-registration).
Code:
src/index.js
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('../firebase-messaging-sw.js')
.then(function(registration) {
console.log('Registration successful, scope is:', registration.scope);
}).catch(function(err) {
console.log('Service worker registration failed, error:', err);
});
}
src/firebase.js
import { initializeApp } from "firebase/app";
import { getMessaging, getToken } from "firebase/messaging";
const firebaseApp = initializeApp({
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
});
const messaging = getMessaging(firebaseApp);
export const fetchToken = async (setToken) => {
await getToken(messaging, { vapidKey: KEY_PAIR }).then((currentToken) => {
if (currentToken) {
setToken(currentToken)
} else {
console.log('No registration token available. Request permission to generate one.');
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});
}
public/firebase-messaging-sw.js
import { initializeApp } from "firebase/app";
import { getMessaging, onBackgroundMessage } from "firebase/messaging/sw";
const firebaseApp = initializeApp({
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
});
const messaging = getMessaging(firebaseApp);
onBackgroundMessage(messaging, (payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: ''
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
so I did this a few months ago and it worked for me, it should for you as well...
First you need to register de service worker to ger this running so in your index.js you can do the following:
// IMPORTS...
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("../firebase-messaging-sw.js")
.then(function (registration) {
console.log("Registration successful, scope is:", registration.scope);
})
.catch(function (err) {
console.log("Service worker registration failed, error:", err);
});
}
const dashboard = (
<Provider store={MyStore}>
<PersistGate loading={null} persistor={persistor}>
<BrowserRouter>
<App />
</BrowserRouter>
</PersistGate>
</Provider>
);
ReactDOM.render(dashboard, document.getElementById("root"));
reportWebVitals();
Then the sw firebase register looks like this:
importScripts("https://www.gstatic.com/firebasejs/9.0.0/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-compat.js");
firebase.initializeApp({
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
});
const isSupported = firebase.messaging.isSupported();
if (isSupported) {
const messaging = firebase.messaging();
messaging.onBackgroundMessage(({ notification: { title, body, image } }) => {
self.registration.showNotification(title, {
body,
icon: image || "/assets/icons/icon-72x72.png",
});
});
}
It is important to have a config file for firebase: firebase.js
import { initializeApp } from "firebase/app";
import { getMessaging, getToken } from "firebase/messaging";
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSENGER_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID,
measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID,
};
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
export { firebaseApp };
export const fetchToken = async (setToken) => {
await getToken(messaging, {
vapidKey: "KEY",
})
.then((currentToken) => {
if (currentToken) {
// setToken(currentToken);
console.log("currentToken: ", currentToken);
} else {
console.log("No registration token available. Request permission to generate one.");
}
})
.catch((err) => {
console.log("An error occurred while retrieving token. ", err);
});
};
After these files configures you can call the fetchToken function from a useEffect inside your main file/navigator/etc and then you can use the onMessage hook/function from firebase/messaging itself

Categories

Resources