I'm struggling with this problem for more than a week... We have implemented push message in Chrome by using Firebase and a Service Worker. Everything works just fine, the messages are being sent and received correctly with the payload. On the service worker, we handle the push message to display a notification and the notificationclick event to send the user to a specific URL when clicking on it, then close the notification.
The problem is with 'old' notifications: if a user receives a message but doesn't clicks on it right away, it keeps there for a while then after some time (not sure how much) he clicks the notification - he gets redirected to https://[domain]/firebase-messaging-sw.js
We have traced the entire process: the notification gets received with all the info properly (the url is also correct, actually if he clicks right when the message is received it works just fine). But if the notification lives there for a while it gets 'emptied'.
The message being sent is pretty simple (just for showing there are no TTLs, nor expiration parameters being used). The curl command looks like that:
curl -X POST
-H "Authorization: key=[SERVER API KEY]"
-H "Content-Type: application/json"
-d '{
"notification":{
"click_action":"[URL to be redirected]",
"icon":"[A custom image]",
"title":"[News title]"},
"to":"/topics/[A topic]"
}'
"https://fcm.googleapis.com/fcm/send"
This is the code for processing the push message on the service worker:
self.addEventListener('push', function(event) {
console.log('Push message received', event);
var data = {};
if (event.data) {
data = event.data.json();
}
event.stopImmediatePropagation();
showNotification(data.notification);
});
function showNotification(notification) {
var click_action = notification.click_action; //<-- This is correct!
var options = {
body: notification.body,
icon: notification.icon,
subtitle: notification.subtitle,
data: {
url: click_action
}
};
if (self.registration.showNotification) {
return self.registration.showNotification(notification.title, options);
}
}
And the code for managing notificationclick event is pretty straightforward:
self.addEventListener('notificationclick', function(event) {
var url = '';
try {
url = event.notification.data.url; // <-- event.notification is null randomly!!
} catch (err) {}
event.waitUntil(self.clients.openWindow(url));
});
Is there any reason for loosing the payload after a certain time on the service worker context? Is this time specified on any documentation somewhere?
Thanks in advance for your help!
//payload of push message
{
"notification": {
"title": data.title,
"body": data.text,
"click_action": url,
"tag": "",
"icon": ""
},
"to": token
}
//in service woker
self.addEventListener("notificationclick", (event) => {
event.waitUntil(async function () {
const allClients = await clients.matchAll({
includeUncontrolled: true
});
let chatClient;
for (const client of allClients) {
if (client['url'].indexOf(event.notification.data.FCM_MSG.notification.click_action) >= 0) {
client.focus();
chatClient = client;
break;
}
}
if (!chatClient) {
chatClient = await clients.openWindow(event.notification.data.FCM_MSG.notification.click_action);
}
}());
});
so in this basically, on click of notification you are redirected to application ,and if the application is not open you are opening the application in new tab , as you are concerned that in event you are not able to get the click_action, could you try event.notification.data.FCM_MSG.notification.click_action by using this and see if you are getting the url, and add the event listener in beginning of service worker https://github.com/firebase/quickstart-js/issues/102
Related
I'm new to programming and I'm developing an app in which the user is suppose to get a notification 30 minutes before an event that's scheduled on the app. The schedule is saved in the firebase database and the device checks every 30 minutes to see if it's time to send an alert. If that condition becomes true, I want the device to send the notification so that the user will be alerted about the event. Every tutorial I saw only showed how to send notification through firebase itself. None of them covered how you can send them from the device.
I came across this code:
final postUrl = Uri.parse('https://fcm.googleapis.com/fcm/send');
final data = {
"registration_ids": tokens, //list of tokens
"collapse_key": "type_a",
"notification": {
"title": 'title',
"body": 'body',
},
"data": {
"data1": 'data 1', //data passed
}
};
final Map<String, String> headers = {
'content-type': 'application/json',
'Authorization': serverKey, //..................FCM server key
};
final response = await http.post(postUrl,
body: json.encode(data),
encoding: Encoding.getByName('utf-8'),
headers: headers);
if (response.statusCode == 200) {
print('test ok push CFM');
return true;
} else {
print(' CFM error');
print(response.statusCode);
return false;
}
}
But isn't this bad practice since your server key is exposed? Are there any better and safe methods to do this using flutter??
I think checking the firebase database every 30 minutes from the device is not a good decision.
You can use/write a firebase cloud function. Using a firebase cloud function you can watch any document/field and try to write notification trigger logic like if a event is before 30 minutes then this cloud function will throw a notification via firebase messaging.
See https://firebase.flutter.dev/docs/functions/overview/ for more information.
I'm sending an FCM push notification from a Firebase backend to a Chrome Extension. I get it to show successfully in my Chrome Extension when it's in focus. I want it to show even if the Extension isn't in focus, but I can't get the service worker that's supposed to handle the notification even to fire.
I followed the Google tutorial to set up my JavaScript Chrome Extension client. I already tried this solution to not include a "notification" payload in my message, and this solution to register the worker manually (even though the tutorial doesn't say anything about either), but to no avail.
My service worker firebase-messaging-sw.js looks like this:
importScripts('https://www.gstatic.com/firebasejs/5.8.2/firebase.js');
var config = {
...
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload.data);
var notificationTitle = 'Background Message Title';
var notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
This is the POST request I use to send notifications (obviously with the correct SERVER_KEY and USER_TOKEN values):
POST /fcm/send HTTP/1.1
Host: fcm.googleapis.com
Content-Type: application/json
Authorization: key=<SERVER_KEY>
Cache-Control: no-cache
{
"data": {
"title": "Firebase",
"body": "Firebase is awesome",
"click_action": "http://localhost:5000/",
"icon": "http://localhost:5000/firebase-logo.png"
},
"to": "<USER_TOKEN>"
}
How do I get the service worker to receive the push notification and display it?
Thanks in advance :)
You can use Push API in service worker (firebase-messaging-sw.js):
importScripts('https://www.gstatic.com/firebasejs/7.2.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.2.2/firebase-messaging.js');
var config = {
...
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
this.onpush = event => {
console.dir(event.data.json());
// Here you can use event.data to compose Notification
// #see https://www.w3.org/TR/push-api/#pushmessagedata-interface
};
I have created a server side route (using iron-router). Code is as follows :
Router.route( "/apiCall/:username", function(){
var id = this.params.username;
},{ where: "server" } )
.post( function(req, res) {
// If a POST request is made, create the user's profile.
//check for legit request
console.log('post detected')
var userId = Meteor.users.findOne({username : id})._id;
})
.delete( function() {
// If a DELETE request is made, delete the user's profile.
});
This app is running on port 3000 on my local. Now I have created another dummy app running on port 5000. Frrom the dummy app, I am firing a http.post request and then listening it on the app on 3000 port. I fire the http.post request via dummy app using the below code :
apiTest : function(){
console.log('apiTest called')
HTTP.post("http://192.168.1.5:3000/apiCall/testUser", {
data: [
{
"name" : "test"
}
]
}, function (err, res) {
if(!err)
console.log("succesfully posted"); // 4
else
console.log('err',err)
});
return true;
}
But I get the following error on the callback :
err { [Error: socket hang up] code: 'ECONNRESET' }
Not able to figure out whats the problem here.
The server side route is successfully called, but the .post() method is not being entered.
Using meteor version 1.6
192.168.1.5 is my ip addr
Okay so if I use Router.map function, the issue is resolved.
Router.map(function () {
this.route("apiRoute", {path: "/apiCall/:username",
where: "server",
action: function(){
// console.log('------------------------------');
// console.log('apiRoute');
// console.log((this.params));
// console.log(this.request.body);
var id = this.params.username;
this.response.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
if (this.request.method == 'POST') {
// console.log('POST');
var user = Meteor.users.findOne({username : id});
// console.log(user)
if(!user){
return 'no user found'
}
else{
var userId = user._id;
}
}
});
});
It looks like the content type is not set the application/json. So you should do that...
Setting the "Content-Type" header in HTTP.call on client side in Meteor
Just getting started with Firebase phone auth. Seems pretty slick however I've hit a wall with a bug.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalid",
"message": "SESSION_EXPIRED"
}
],
"code": 400,
"message": "SESSION_EXPIRED"
}
}
Starting with the Captcha: (standard documentation code!)
var applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container', {
'size': 'invisible',
'callback': function(response) {
},
'expired-callback': function() {
}
});
Its rendered and the captcha works well.
Next is the sign-in bit where you are sent the auth code to your phone. Works great:
$scope.signInWithPhoneNumber = function signInWithPhoneNumber() {
var phoneNumber = "*censored*";
var appVerifier = window.recaptchaVerifier;
firebase.auth().signInWithPhoneNumber(phoneNumber, applicationVerifier)
.then(function (confirmationResult) {
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
window.confirmationResult = confirmationResult;
$scope.setConfirmationResult(confirmationResult);
alert('Result: ' + JSON.stringify(confirmationResult));
}).catch(function (error) {
// Error; SMS not sent
alert('Error: ' + error);
// ...
});
};
Finally its the authentication of the code that the user inputs from the text message. Here is when I get the error 400:
$scope.AuthenticateCode = function (code) {
var code = String(document.getElementById("auth_code").value);
var confirmationResult = $scope.getConfirmationResult();
alert(code);
confirmationResult.confirm(code).then(function (result) {
// User signed in successfully.
var user = result.user;
console.log('Signed In! ' + JSON.stringify(user));
// ...
}).catch(function (error) {
// User couldn't sign in (bad verification code?)
// ...
});
}//end of AuthenticateCode
The error is coming from the VerifyPhone method:
https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPhoneNumber?key=censored
Any help or ideas?
Many Thanks,
Kieran
Ok, there are 2 likely reasons:
The code expired. The user took too long to provide the SMS code and finish sign in.
The code was already successfully used. I think this is the likely reason. You need to get a new verificationId in that case. Get a new reCAPTCHA token via the invisible reCAPTCHA you are using.
You are most likely to forget the "Country Code" before the phone no.
That is why firebase throw error 400 which means invalid parameters
If it's an Ionic3 project, change the following lines:
Imports:
import { AngularFireAuth } from 'angularfire2/auth';
import firebase from 'firebase';
Create var:
public recaptchaVerifier: firebase.auth.RecaptchaVerifier;
on "ionViewDidLoad()"
this.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
on "your_method(phoneNumber: number)"
const appVerifier = this.recaptchaVerifier;
const phoneNumberString = "+" + phoneNumber;
this.fireAuth.auth.signInWithPhoneNumber(phoneNumberString, appVerifier)
.then(confirmationResult => {
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
let prompt = this.alertCtrl.create({
title: 'Enter the Confirmation code',
inputs: [{ name: 'confirmationCode', placeholder: 'Confirmation Code' }],
buttons: [
{
text: 'Cancel',
handler: data => { console.log('Cancel clicked'); }
},
{
text: 'Send',
handler: data => {
confirmationResult.confirm(data.confirmationCode)
.then(result => {
// Phone number confirmed
}).catch(error => {
// Invalid
console.log(error);
});
}
}
]
});
prompt.present();
})
.catch(error => {
console.error("SMS not sent", error);
});
Reference:
Firebase Phone Number Authentication
I got into a similar situation when a POST request to google API was returning Bad Request 400. When the message was logged, it said:
All requests from this device are blocked due to Unusual Activity. Please try again later
The issue was when the ReCaptcha was sensing a bot out of my development environment and it worked well when I tried later. During the rest of the development, I turned off this feature for easy work.
I am prototyping browser push notifications with FCM. I just copied the example code from the quickstart (https://github.com/firebase/quickstart-js/tree/master/messaging). Messages are recieved and displayed as they should be. But when I try to modify the message in the Service Worker (messaging.setBackgroundMessageHandler) nothing happens. The service worker is called, and if I implement an event listener in that service worker for the push notifications, it catches the event. But the method setBackgroundMessageHandler is never called.
I am trying this on Chrome 54.
Any ideas what I need to do to customize the message in the service worker?
Thank you very much!
For anyone experiencing the same problem, here is the answer: https://github.com/firebase/quickstart-js/issues/71
short summary: do not include a "notification" element in your json message.
This is a solution that worked for me in a webapp. It displays the notification with title and body text along with an image and handles the user click.
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');
// Initialize Firebase
var config = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
databaseURL: 'YOUR_DB_URL',
projectId: 'YOUR_PROJ_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_SENDER_ID',
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log('Handling background message ', payload);
return self.registration.showNotification(payload.data.title, {
body: payload.data.body,
icon: payload.data.icon,
tag: payload.data.tag,
data: payload.data.link,
});
});
self.addEventListener('notificationclick', function (event) {
event.notification.close();
event.waitUntil(self.clients.openWindow(event.notification.data));
});
JSON Message
{
"message": {
"token": "YOUR_TARGET_APP_TOKEN",
"data": {
"title": "FCM Message",
"body": "This is an FCM Message",
"icon": "https://shortcut-test2.s3.amazonaws.com/uploads/role_image/attachment/10461/thumb_image.jpg",
"link": "https://yourapp.com/somewhere"
}
}
}
As mentioned by others, including notification in the payload stops it working on the web JS SDK, however you need it present for it to work in native apps.
The workaround I found for the web was to use the web browser native EH push to handle the event manually:
https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/onpush
self.addEventListener('notificationclick', function(event) {
console.log('SW: Clicked notification', event)
let data = event.notification.data
event.notification.close()
self.clients.openWindow(event.notification.data.link)
})
self.addEventListener('push', event => {
let data = {}
if (event.data) {
data = event.data.json()
}
console.log('SW: Push received', data)
if (data.notification && data.notification.title) {
self.registration.showNotification(data.notification.title, {
body: data.notification.body,
icon: 'https://example.com/img/icons/icon-144x144.png',
data
})
} else {
console.log('SW: No notification payload, not showing notification')
}
})
When you try to send a push message are you doing it while your app is on focus or not? Because from the documentation, it says that setBackgroundMessageHandler is only called when the Web app is closed or not in browser focus.
Based on the example code from the quickstart (https://github.com/firebase/quickstart-js/tree/master/messaging).
If your app is in focus: the push message is received via messaging.onMessage() on the index.html
If your app does not have focus : the push message is received via setBackgroundMessageHandler() on teh service worker file.