I am trying to implement FCM notification inside a Flutter Web application but I am getting errors when registering my service worker. I think it might come from the way my files index.html and firebase-messaging-sw.js are made.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MyApp</title>
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js"></script>
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var devConfig = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
databaseURL: "DB_URL",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "MESSAGING_SENDER_ID",
appId: "APP_ID",
measurementId: "MEASUREMENT_ID"
};
// Initialize Firebase
firebase.initializeApp(devConfig);
</script>
<script>
if ("serviceWorker" in navigator) {
window.addEventListener("load", function () {
navigator.serviceWorker.register("/firebase-messaging-sw.js");
});
}
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.5.0/firebase-messaging.js');
var devConfig = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
databaseURL: "DB_URL",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "MESSAGING_SENDER_ID",
appId: "APP_ID",
measurementId: "MEASUREMENT_ID"
};
// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp(devConfig);
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
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);
});
Errors
Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
at p (https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js:1:10100)
at Object.o [as messaging] (https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js:1:9710)
at http://localhost:56234/firebase-messaging-sw.js:33:28
Uncaught (in promise) TypeError: Failed to register a ServiceWorker for scope ('http://localhost:56234/') with script ('http://localhost:56234/firebase-messaging-sw.js'): ServiceWorker script evaluation failed
I am testing the application using the command flutter run -d web-server.
I am correctly calling await Firebase.initializeApp() before starting my application in my main.dart.
I am using the package firebase_core: ^0.5.0.
I have tested with firebase scripts in version 7.22.1 and 7.5.0.
add follow ing in your index.html
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-messaging.js"></script>
Related
I started looking into authentication and installed firebase using Node.js, then took the CDN links from the documentation. It worked once on saturday then hasnt worked since.
Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app-compat/no-app).
This is the current look of the file that handels logging in.
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.16.0/firebase-app.js';
const firebaseConfig = {
apiKey: 'AIzaSyBfb3L9WKUf7qhVyzxpxKBRWUWbcMohUxY',
authDomain: 'study-track-7df2d.firebaseapp.com',
projectId: 'study-track-7df2d',
storageBucket: 'study-track-7df2d.appspot.com',
messagingSenderId: '1015802748429',
appId: '1:1015802748429:web:e7884ea90aec8d73d63f44',
measurementId: 'G-RPCPGGCFV1',
};
const app = initializeApp(firebaseConfig);
const btnCreate = document.querySelector('.create-account');
function googleLogin() {
const provider = new firebase.auth.GoogleAuthProvider();
firebase
.auth()
.signInWithPopup(provider)
.then(result =\> {
const user = result.user;
console.log(user);
})
.catch(console.log);
}
btnCreate.addEventListener('click', function (e) {
googleLogin();
});
These are the two CDN calls from the HTML
<script type="module" src="https://www.gstatic.com/firebasejs/9.16.0/firebase-app-compat.js"></script>
<script type="module" src="https://www.gstatic.com/firebasejs/9.16.0/firebase-auth-compat.js"></script>
I can't link the function below to my JavaScript file. I am using Firebase CDN code snippet. What am I doing wrong?
Firebase snippet:
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.0.0/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.0.0/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyAPeU7jO2Zz5kdrh-4g4ehfcrL8Aufzubs",
authDomain: "udemy-modern-javascript-cee40.firebaseapp.com",
databaseURL: "https://udemy-modern-javascript-cee40.firebaseio.com",
projectId: "udemy-modern-javascript-cee40",
storageBucket: "udemy-modern-javascript-cee40.appspot.com",
messagingSenderId: "941299603483",
appId: "1:941299603483:web:afcd4f1da6878b51ef80be",
measurementId: "G-BRYW3TQNLL"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.analytics();
js file:
db.collection('recipes').get().then((snapshot)=>{
console.log(snapshot);
}).catch(err =>{
console.log(err)
});
The error msg is:
sandbox.js:1 Uncaught TypeError: db.collection is not a function at sandbox.js:1 (anonymous) # sandbox.js:1
The db variable from the script tag in your HTML file is not automatically available in the .js file.
You'll typically want to put all JavaScript (including what you now have in the script tag into the .js file or have all of it in the script tag in the HTML file.
Putting all code in the .js file is more common, so that'd become:
var firebaseConfig = {
apiKey: "AIzaSyAPeU7jO2Zz5kdrh-4g4ehfcrL8Aufzubs",
authDomain: "udemy-modern-javascript-cee40.firebaseapp.com",
databaseURL: "https://udemy-modern-javascript-cee40.firebaseio.com",
projectId: "udemy-modern-javascript-cee40",
storageBucket: "udemy-modern-javascript-cee40.appspot.com",
messagingSenderId: "941299603483",
appId: "1:941299603483:web:afcd4f1da6878b51ef80be",
measurementId: "G-BRYW3TQNLL"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.analytics();
db.collection('recipes').get().then((snapshot)=>{
console.log(snapshot);
}).catch(err =>{
console.log(err)
});
const db = firebase.analytics();
I'm new in Firebase, and I am trying to figure out how to make my simple web app get token.
Since this is just prototype, I have 3 files.
1: init.js
// Initialize Firebase
const config = {
apiKey: "XXXXX",
authDomain: "XXXXX",
databaseURL: "XXXXXXX",
projectId: "XXXXXXXX",
storageBucket: "",
messagingSenderId: "XXXXXX"
}
var defaultApp = firebase.initializeApp(config);
console.log(defaultApp.name);
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
messaging.requestPermission().then(function() {
console.log('Notification permission granted.');
}).catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken().then(function(currentToken) {
if (currentToken) {
console.log('token 1 : '+currentToken);
var el = document.getElementById("firebaseToken").value = currentToken;
} else {
console.log('token 2 : '+currentToken)
}
}).catch(function(err) {
console.log('An error occurred while retrieving token. ', err);
});
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
});
2: index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<textarea id='firebaseToken'></textarea>
</head>
<body>
<!-- Firebase App is always required and must be first -->
<script src="https://www.gstatic.com/firebasejs/5.5.9/firebase-app.js"></script>
<!-- Add additional services that you want to use -->
<script src="https://www.gstatic.com/firebasejs/5.5.9/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.5.9/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.5.9/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.5.9/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.5.9/firebase-functions.js"></script>
<script src="init.js"></script>
</body>
</html>
3: firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
const config = {
apiKey: "XXXXX",
authDomain: "XXXXX",
databaseURL: "XXXXXXX",
projectId: "XXXXXXXX",
storageBucket: "",
messagingSenderId: "XXXXXX"
}
var defaultApp = firebase.initializeApp(config);
console.log(defaultApp.name);
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: '/itwonders-web-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
The problem is when I publish my code on Windows hosting, my web app
prototype doesn't get the token (I host in somee.com). But it works fine in 000webhost.com (Linux hosting), and also run with no problem in localhost.
The error says:
code: "messaging/unsupported-browser"
message: "Messaging: This browser doesn't support the API's required to use the firebase SDK. (messaging/unsupported-browser)."
stack: "FirebaseError: Messaging: This browser doesn't support the API's required to use the firebase SDK. (messaging/unsupported-browser)
Do I have to configure something on Windows server? Open port or etc?
Here's the screenshots:
I finally got the root cause.
the reason firebase not running on somee.com.
Because in somee.com i dont use ssl. but 000webhost got SSL. thats why firebase running on 000webhost.
because based on this :
https://github.com/firebase/firebase-js-sdk/issues/1220
firebase wont running on https not http.
enter image description here
// Initialize Firebase
var config = {
apiKey: "AIzaSyBz13eirmEOGD1uXOZwf6tKGnEsjfwsUFo",
authDomain: "platformtechproject.firebaseapp.com",
databaseURL: "https://platformtechproject.firebaseio.com",
projectId: "platformtechproject",
storageBucket: "platformtechproject.appspot.com",
messagingSenderId: "1065758005439"
};
firebase.initializeApp(config);
var database = firebase.database();
ref msgs clllection
var msgRef = firebase.database().ref('survey');
I am trying to connect to firebase, but I continue getting these errors on chrome console failing to connect to firebase:
Chrome console error
This is because you did not write:
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase.js"></script>
in the <head>...</head>
You have to write it to be able to use the firebase sdk in your project.
more info here:
https://firebase.google.com/docs/web/setup
I want to create FCM token for web application based on this i want to send push notifications.Is it possible?Can i expect sample code for this?
I try this one
var config = {
apiKey: "AIzaSyC2GoeeoYfPTgP61w77FMPFep-cLBz9Pmc",
authDomain: "sample-3a7a1.firebaseapp.com",
databaseURL: "https://sample-3a7a1.firebaseio.com",
projectId: "sample-3a7a1",
storageBucket: "sample-3a7a1.appspot.com",
messagingSenderId: "990467369229"
};
firebase.initializeApp(config);
const messaging=firebase.messaging();
messaging.requestPermission()
.then(function(){
console.log('Have permission');
return messaging.getToken();
})
.then(function(token){
console.log(token);
})
but it shows following error
Uncaught e {code: "app/no-app", message: "Firebase: No Firebase App '[DEFAULT]' has been cre…- call Firebase App.initializeApp() (app/no-app).", name: "[DEFAULT]", stack: "FirebaseError: Firebase: No Firebase App '[DEFAULT… at http://localhost:8080/FCMPushNotify/:88:30"}