When I push a notification on chrome the messaging.onMessage()does't work(when I'm on page) and I don't see any notification(when I'm off the page). The only thing that is displayed is a pop up which says The site has been updated in the background but I don't have that issue in firefox. I've looked around about this issue and found out it is a semi-common one, but I couldn't modify my code in order to get it to work properly.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Notifications</title>
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/4.1.3/firebase.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js
/**
* Created by nikos on 13/7/2017.
*/
console.log('APP.JS');
var config = {
apiKey: "AIz..",
authDomain: "....firebaseapp.com",
databaseURL: "https://....firebaseio.com",
projectId: "locpushweb",
storageBucket: "locpushweb.appspot.com",
messagingSenderId: "..."
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function () {
console.log("Have Permission");
return messaging.getToken();
}).then(function (token) {
console.log(token);
}).catch(function (err) {
console.log("Error: " + err)
});
messaging.onMessage(function (payload) {
console.log(payload);
})
firebase-messaging-sw.js
/**
* Created by nikos on 13/7/2017.
*/
console.log('SW');
importScripts('https://www.gstatic.com/firebasejs/4.1.3/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.1.3/firebase-messaging.js');
var config = {
apiKey: "AIz..",
authDomain: "....firebaseapp.com",
databaseURL: "https://....firebaseio.com",
projectId: "locpushweb",
storageBucket: "locpushweb.appspot.com",
messagingSenderId: "..."
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
// messaging.setBackgroundMessageHandler(function (payload) {
// var data = JSON.parse(payload);
// self.registration.showNotification(data.title, {
// body: data.body,
// icon: data.icon,
// click_action: data.click_action,
// time_to_live: data.time_to_live,
// data: data.data,
// tag: data.tag
// });
// });
Lastly, this is the curl command:
curl -X POST -H "Authorization: key=AAAAZGd...." -H "Content-Type: application/json" -d '{
"notification": {
"title": "Portugal vs. Denmark",
"body": "5 to 1",
"icon": "firebase-logo.png",
"click_action": "http://localhost:8081"
},
"to": "cxfoMyjwsOY:APA91bFnOQlYxw3iPlbcc714wI5BFWLfEXvmT1FRTL0SJNuy1AOTfah4EKTdvoi1SvnX8SpD9CUD1D-I8GdKcIb-M1l65NFc8xhJNF2iBffERN9yWSNnN2_CHqodcpMMSyC_IDKZJ0GH"
}' "https://fcm.googleapis.com/fcm/send"
Related
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)
});
}
I'm using firebase web push notifications API and sending post request with the message I want to display on the client-side with Postman and/or from the firebase notifications composer, the message is being sent successfully but it is not being received, how can I fix this?
This is the response I get
{
"multicast_id": 6360733777037549929,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1592759038463623%cc9b4facf9fd7ecd"
}
]
}
I'm using Firebase hosting, and including the entire Firebase Javascript SDK, although I already tried including only firebase-messaging SDK.
<body>
<h1>Some Firebase app</h1>
<script src="/__/firebase/7.15.3/firebase.js"></script>
<script src="/__/firebase/init.js"></script>
<script type="text/javascript">
const messaging = firebase.messaging();
messaging.requestPermission()
.then(()=>{
console.log('Permission Granted');
return messaging.getToken()
})
.then((token)=>{
console.log(token);
})
.catch((err)=>{
console.log(err);
})
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
});
</script>
</body>
With the token I get, and with my server key I send the following request
Method: POST
URL: https://fcm.googleapis.com/fcm/send
Headers: {
Authorization: "key=myServerKey",
Content-Type: "application/json"
}
Body: {
"to" : "token",
"notification" : {
"body" : "Test message",
"title" : "Test title"
}
}
And this is how I handle the message on firebase-messaging-sw.js file
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-messaging.js');
var firebaseConfig = {
apiKey: "xxxx",
authDomain: "newproject-95acc.firebaseapp.com",
databaseURL: "https://newproject-95acc.firebaseio.com",
projectId: "newproject-95acc",
storageBucket: "newproject-95acc.appspot.com",
messagingSenderId: "xxxx",
appId: "xxxx"
};
firebase.initializeApp(firebaseConfig);
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
});
Which you want to receive message in the Foreground(has focus), or in the Background (service worker)?
in the Background (service worker)
Could you try the following code?
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-messaging.js');
var firebaseConfig = {
apiKey: "xxxx",
authDomain: "newproject-95acc.firebaseapp.com",
databaseURL: "https://newproject-95acc.firebaseio.com",
projectId: "newproject-95acc",
storageBucket: "newproject-95acc.appspot.com",
messagingSenderId: "xxxx",
appId: "xxxx"
};
firebase.initializeApp(firebaseConfig);
if (firebase.messaging.isSupported()) {
firebase.messaging();
}
See https://firebase.google.com/docs/cloud-messaging/js/receive
If you set notification fields in your message payload, your setBackgroundMessageHandler callback is not called, and instead the SDK displays a notification based on your payload.
Or, Could you try samples?
See:
https://github.com/firebase/functions-samples/tree/master/fcm-notifications
https://github.com/firebase/functions-samples/blob/master/fcm-notifications/public/main.js
https://github.com/firebase/functions-samples/blob/master/fcm-notifications/public/firebase-messaging-sw.js
I am sending following Notification
Authorization:key=A.....
Content-Type:application/json
{
"to" : "cBx_ErhkhNw:APA91bEzwHvZ2daEK15Y3A0VAprxPV-4GGq10FjlrFnHzCs8xSJXz2lATjh9AoLRQvnSseT6r4ggApC6TbtD9M_sI_BDDmycZ1TEVn0HaF5pAABeSbHqcOK-kmkPqOve1VThUaUIXQy4",
"notification": {
"title": "Test Nachricht",
"body": "This is a message from FCM to web"
},
"priority": "high",
"webpush": {
"fcm_options": {
"link": "https://dummypage.com"
}
}
}
And have following code:
app.js
// Initialize Firebase
var config = {
apiKey: "<KEY>",
authDomain: "<AUTH_DOMAIN>",
databaseURL: "<DB_URL>",
projectId: "atlas-test-35d33",
storageBucket: "<STORAGE_BUCKET>",
messagingSenderId: "817272374311"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.usePublicVapidKey("<PUBLIC_KEY>");
messaging.requestPermission()
.then(function() {
console.log("Permission granted");
return messaging.getToken()
})
.then(function(token) {
console.log(token)
})
.catch(function(err) {
console.log(err)
})
console.log("listenting")
messaging.onMessage(function(payload) {
console.log('Message received. ', payload);
// ...
});
firebase-messaging-sw.js
// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here, other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/5.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.9.0/firebase-messaging.js');
var config = {
apiKey: "<KEY>",
authDomain: "<AUTH_DOMAIN>",
databaseURL: "https://atlas-test-35d33.firebaseio.com",
projectId: "atlas-test-35d33",
storageBucket: "<STORAGE_BUCKET>",
messagingSenderId: "817272374311"
};
firebase.initializeApp(config);
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
When I try to send a Notification to the fcm Server I get following response:
{
"multicast_id": 5394725759940263108,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1552646324437940%e609af1cf9fd7ecd"
}
]
}
Which seems, like everything is fine for me. But I dont receive anything in my Web application. I just hardcoded the "to" token for testing purposes but I dont think thats the Problem.
Do you have any clue whats the problem, or is there any debug possibility.
Thanks!
Token is not generating on the web...........................................................................................................................
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
heloooo
</body>
</html>
<script src="https://www.gstatic.com/firebasejs/4.12.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
const messaging=firebase.messaging();
messaging.requestPermission()
.then(function() {
console.log('Have permission');
return messaging.getToken();
})
.then(function(token){
console.log(this.token);
})
.catch(function(err){
console.log('Error occured.');
})
</script>
this is my code sorry i can't show my fcm initiation code completely
error on my console
hello.html:29 Have permission
hello.html:33 null
hello.html:34 undefined
You need to supply your API key when initialising
I'm having an issue with Firebase Cloud Messaging (I'm trying to use it in the web) in which I get the Token and when i use it to send a notification , it give me a good response like this:
{"multicast_id":5064947793483036169,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1496136155591444%e609af1cf9fd7ecd"}]}
but i don't receive the notification.
This is the script that should receive the notification:
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase-app.js">
</script>
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase-messaging.js"></script>
<script>
var config = {
apiKey: "AIzaS.........7AP0",
authDomain: "prova-notifications.firebaseapp.com",
databaseURL: "https://prova-notifications.firebaseio.com",
projectId: "prova-notifications",
storageBucket: "prova-notifications.appspot.com",
messagingSenderId: "59.......20"
};
firebase.initializeApp(config);
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(function(payload) {
console.log("Message received. ", payload);
});
what am I doing wrong?
EDIT: Here a sample payload that i'm sending:
Host: fcm.googleapis.com
Authorization: key=AAAAilrlPU.........LBA90EJk
Content-Type: application/json
{
"notification": {
"title": "Portugal vs. Denmark",
"body": "5 to 1"
},
"to": "eHdpi3OX..........5AvG"
}