firebase-messaging.js not found laravel - javascript

Hello everyone I am making an application using firebase for push notifications. This is my first project in firebase. The issue I am having is with the connection as when I run the project and click on the login button it gives me
Notification permission granted
But after this it returns an error which is as follow.
A bad HTTP response code (404) was received when fetching the script.
firebase.js:24 Unable to get permission to notify. FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:8000/firebase-cloud-messaging-push-scope') with script ('http://localhost:8000/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script. (messaging/failed-serviceworker-registration).
at https://www.gstatic.com/firebasejs/7.5.2/firebase-messaging.js:1:44674
I don't know why it is happening as I can see my js file and all the code as well, here is my config files.
In my firebase-messaging-sw.js which is on root directory the code is
importScripts('https://www.gstatic.com/firebasejs/7.5.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.5.2/firebase-messaging.js');
firebase.initializeApp({
'messagingSenderId': 'SenderID'
});
const messaging = firebase.messaging();
console.log(messaging);
messaging.setBackgroundMessageHandler(function(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'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
And in my firebase.js file the code is as follow:
const firebaseConfig = {
apiKey: "API-KEY",
authDomain: "authDomain",
databaseURL: "DBURI",
projectId: "P-ID",
storageBucket: "SB",
messagingSenderId: "SenderID",
appId: "AppID",
measurementId: "MeasurementID"
};
firebase.initializeApp(firebaseConfig);
//------------------------------------------------------------------------------
const messaging = firebase.messaging();
messaging.requestPermission().then(function () {
console.log("Notification permission granted");
return messaging.getToken();
}).then(function (token) {
console.log(token);
}).catch(function (err) {
console.log("Unable to get permission to notify.", err);
});
//------------------------------------------------------------------------------
messaging.onMessage((payload) => {
console.log(payload);
})
Any help would be appreciated. Thank you in advance.

I found the solution and it's working perfectly fine. Posting it for others who faces similar problem. The issue was in my firebase-messaging-sw.js file. I was initializing the firebase with sender id it was written in the documentation. I just initialized the firebase object with all the configuration values changing the initializing object solved my problem.

Related

Heroku: Firebase can't load credentials

Summary of Problem
I'm hosting my Node.js server that uses Firebase on Heroku and when I try to run on Heroku, I get the error below that it can't load my credentials.
It works perfectly when running on my local machine. I'm using the firebase-admin npm package to configure my firebase connection/instance.
Has anyone encountered this before? If so, I'd love your help!
Error from Heroku
Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
Code
Firebase Admin Config File
This is the file I'm using to configure my Firebase admin instance
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: "https://esports-competition-2.firebaseio.com"
}); //this also allows me to use Google OAuth2 refresh token
const db = admin.firestore();
module.exports = db;
Function to save data to firebase
const db = require("../../configs/firebaseConfig");
async function firestorePush(userId, eventType, data) {
try {
//read database
//if userId contains eventType singleEntry then remove from database
const timeStamp = new Date();
userId = userId.toString();
const userDoc = db.collection("pushData").doc(userId);
const pushData = await userDoc.set(
{
event: {
eventType,
data,
timeStamp
}
},
{ merge: true }
);
console.log("Document set in FireStore", pushData);
} catch (err) {
console.log("errpr pushing to firebase", err);
}
}
According to the documentation on admin.credential.applicationDefault():
Google Application Default Credentials are available on any Google infrastructure, such as Google App Engine and Google Compute Engine.
Since Heroku is not Google infrastructure, you will have to initialize the Admin SDK with one of the other options shown in the documentation on initializing the SDK.

firebase-tools getaddrinfo ENOTFOUND metadata.google.internal

I'm getting this error in my terminal:
#firebase/database: FIREBASE WARNING: {"code":"app/invalid-
credential","message":"Credential implementation provided to .
initializeApp() via the \"credential\" property failed to fetch a valid
Google OAuth2 access token with the following error: \"Failed to parse
access token response: Error: Error while making request: getaddrinfo
ENOTFOUND metadata.google.internal metadata.google.internal:80. Error
code: ENOTFOUND\"."}`
when using firebase-tools. This is the simple node script I'm trying to run.
const admin = require("firebase-admin");
const firebase = admin.initializeApp({
apiKey: "MY_API_KEY",
authDomain: "APP_ID.firebaseapp.com",
databaseURL: `https://DATABASE_URL.firebaseio.com`,
projectId: "APP_ID"
});
const snap = firebase
.database()
.ref("REF")
.child("ID")
.once("value");
console.log(snap);
Firebase tools version: 5.0.1
I've tried uninstalling and reinstalling, logging in and out of firebase-tools with firebase login / firebase-logout
the configuration has the wrong structure and lacks fields ...
admin.initializeApp({
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com',
credential: admin.credential.cert({
projectId: '<PROJECT_ID>',
clientEmail: 'foo#<PROJECT_ID>.iam.gserviceaccount.com',
privateKey: '-----BEGIN PRIVATE KEY-----\n<KEY>\n-----END PRIVATE KEY-----\n'
})
});
you cannot just use the "web" configuration to access the Firebase Admin SDK.
because if this would be possible, the private key would be exposed to the public.
see the documentation.
I solved it simply by running :
firebase login
I also have this error when I don't have an internet connection.

Firebase Cloud Functions - onCall not working

I'm testing a very simple implementation as described on FB docs (https://firebase.google.com/docs/functions/callable), and it's not working.
Here's my Firebase Function, deployed to cloud:
exports.getRecSkills = functions.https.onCall((data, context) => {
return {text: data.text};
});
...and my client call (after initializing FB):
var getRecSkills = firebase.functions().httpsCallable('getRecSkills');
getRecSkills({text: '123'}).then(function(result) {
console.log(result);
}).catch(function(error) {
console.log(error.code);
console.log(error.message);
});
I get a CORS header related issue but in the docs, it doesn't mention the need for CORS... am I missing something?
Some notes:
I've been able to execute other Firebase Functions (i.e. HTTPS,
Database) so I don't think it's me setting up Firebase wrong.
Updated to latest Firebase, so don't think that's an issue either.
Gives me an "internal" error, which the API docs aren't helpful, other than "something is seriously wrong".
I can't seem to get the function to work (it keeps giving me
400-errors) when testing locally via the shell, even though I got it
to work with any other database and https functions
Been struggling with this for quite some time... Please help!
To get rid of your CORS error, make sure your firebase.json has the following headers:
"hosting": [
{
"headers": [
{
"source": "**",
"headers": [
{
"key": "Access-Control-Allow-Origin",
"value": "*"
}
]
}
]
}
]
If you're running on Firebase Emulator on local device, make sure you have the following after initializing your Firebase Functions, otherwise your local device will still be calling the remote the Firebase Function and you'll hit the CORS error again:
if (window.location.hostname === "localhost") {
console.log("localhost detected!");
firebase.functions().useFunctionsEmulator('http://localhost:5001');
};
I had the same problem just recently but solved it after including my "projectId" in my config object. Below is a code snippet of the Firebase config object for Javascript. Make sure all fields have been filled in your config object and it should solve your undefined issue.
var config = {
apiKey: "<API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
projectId: "<PROJECT_ID>",
storageBucket: "<BUCKET>.appspot.com",
messagingSenderId: "<SENDER_ID>",
};
If you have CORS issues and you are using express in order to expose the API functions you have to allow cors:
import * as cors from 'cors';
import * as express from 'express';
const corsHandler = cors({origin: true});
const app = express();
app.use(corsHandler);
app.post('/createUser', async (request, response) => {
await createUser(request, response);
});
exports.api = functions.https.onRequest(app);

Firebase Admin With Credential

After coding some of my firebase functions, I deployed and got the following error:
Unexpected error while acquiring application default credentials: Could not load the default credentials.
I researched this error and came to the conclusion that this post would solve my issue: Firebase Cloud Functions: Error: Unexpected error while acquiring application default credentials: read ECONNRESET
I tried this solution. I downloaded a new private key to my desktop and then inserted the following code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
var serviceAccount = require('/Users/nikhilsridhar/Desktop/test-eed0a-firebase-adminsdk-c4tmt-5d905a082b.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://test-eed0a.firebaseio.com"
});
However this does not solve my problem, but rather gives me a new error:
Error: Cannot find module '/Users/nikhilsridhar/Desktop/test-eed0a-firebase-adminsdk-c4tmt-5d905a082b.json'
What am I doing wrong?
So after some time I figured out that the service account file must be within the functions folder. Then make the path relative or in my example: ./test-eed0a-firebase-adminsdk-c4tmt-5d905a082b.json. This should work.
The function admin.credential.cert() receives a string parameter with the path of the firebase json key, this code works well for me with the auth method, you should add databaseURL and call .firestore() instead of auth():
import admin from 'firebase-admin'
export default admin.initializeApp({
credential: admin.credential.cert('../../firebase-key.json')
}).auth()
Watch what TypeScript says about that method:
cert(serviceAccountPathOrObject: string | admin.ServiceAccount, httpAgent?: Agent | undefined): Credential
Optional | HTTP Agentto be used when retrieving access tokens from Google token servers.
The path to a service account key JSON file or an object representing a service account key.
See | Initialize the SDK for more details.
#example
// Providing a path to a service account key JSON file
const serviceAccount = require("path/to/serviceAccountKey.json");
initializeApp({
credential: cert(serviceAccount),
databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});
#example
// Providing a service account object inline
initializeApp({
credential: cert({
projectId: "<PROJECT_ID>",
clientEmail: "foo#<PROJECT_ID>.iam.gserviceaccount.com",
privateKey: "-----BEGIN PRIVATE KEY-----<KEY>-----END PRIVATE KEY-----\n"
}),
databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});
#returns
A credential authenticated via the provided service account that can be used to initialize an app.

The script resource is behind a redirect, which is disallowed

I'm implementing firebase messaging but i'm getting a error on console in chrome.
The script resource is behind a redirect, which is disallowed.
/firebase-messaging-sw.js Failed to load resource: net::ERR_UNSAFE_REDIRECT
The file /firebase-messaging-sw.js is in public folder and i'm using FCM installation like this https://github.com/firebase/quickstart-js/tree/master/messaging
But the link the authorization is a link like https://09029e3f.ngrok.io/admin/pt/settings/notifications.
but the main web site is on main.domain.com
Firebase answer and its working
The service worker script (firebase-messaging-sw.js) is expected to be on the absolute path of the application by default. Using the quickstart project, the location will be http://localhost:5000/firebase-messaging-sw.js.
Since you're using a different server for the static files storage, the service worker script location might not be the same or in place. With this, we need to update the service worker registration code implementation and call the service worker script from a different location.
Find the static location of the service worker script. In my case, it is http://localhost:5000/sw/firebase-messaging.sw.js, since I moved the service worker script location inside the sw folder. To verify that it is accessible, try to input the url in the browser address bar and the service worker script code should be displayed.
Download the firebase.js script locally from https://www.gstatic.com/firebasejs//firebase.js and call it /firebase.js"> on the web pages that need to show a notification.
Update the firebase-messaging.js script. Find the keywords firebase-messaging-sw.js and , then add the path as prefix. In my case, it is http://localhost:5000/sw/firebase-messaging-sw.js and http://localhost:5000/sw/firebase-cloud-messaging-push-scope.
Many thanks firebase
You can fix that by loading firebase-messaging-sw.js manually using service worker.
Suppose you have 2 files: index.html and firebase-message-sw.js. They are on the same location.
1.In the index.html, you load firebase.js and initialize your firebase app:
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase.js"></script>
<script>
var var config = {
apiKey: YOUR_API_KEY,
messagingSenderId: YOUR_SENDER_ID
};
firebase.initializeApp(config);
navigator.serviceWorker.register('/firebase-messaging-sw.js')
.then(function (registration) {
messaging = firebase.messaging();
//request permission for Push Message.
messaging.requestPermission().then(function () {
console.log('grant');
messaging.getToken().then(function (currentToken) {
console.log('current token', currentToken);
});
}).catch(function(error) {
console.log('Push Message is disallowed');
})
})
</script>
2. Implement firebase-messaing-sw.js
importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js');
var config = {
messagingSenderId: YOUR_SENDER_ID
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (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'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
Done!

Categories