Chrome not receiving fcm messages, but firefox does - javascript

I am using FCM to facilitate push messages in a custom service worker. I followed the FCM getting started but am running into issues where the javascript client isn't receiving the sent messages on chrome, but firefox is working as intended.
The messages are being sent from a hosted server, and the messages are sent with no failures and message id's associated with each registered client.
Below is the page script and below that will be relevant service worker code.
page html
<script>
// Initialize Firebase
var config = {
<CONFIG SETTINGS>
};
firebase.initializeApp(config);
var messaging = firebase.messaging();
</script>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/sw.js').then(function (registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
messaging.useServiceWorker(registration);
resetUI();
}).catch(function (err) {
console.log('ServiceWorker registration failed: ', err);
});
});
}
const permissionDivId = 'permission_div';
messaging.onTokenRefresh(function () {
messaging.getToken()
.then(function (refreshedToken) {
console.log('Token refreshed.');
setTokenSentToServer(false);
sendTokenToServer(refreshedToken);
resetUI();
})
.catch(function (err) {
console.log('Unable to retrieve refreshed token ', err);
});
});
messaging.onMessage(function (payload) {
console.log("Message received. ", payload);
appendMessage(payload);
});
function resetUI() {
clearMessages();
messaging.getToken()
.then(function (currentToken) {
if (currentToken) {
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
} else {
console.log('No Instance ID token available. Request permission to generate one.');
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
})
.catch(function (err) {
console.log('An error occurred while retrieving token. ', err);
setTokenSentToServer(false);
});
}
function sendTokenToServer(currentToken) {
if (!isTokenSentToServer()) {
console.log('Sending token to server...');
<TOKEN SENT TO SERVER AND STORED>
setTokenSentToServer(true);
} else {
console.log('Token already sent to server so won\'t send it again ' +
'unless it changes');
}
}
function isTokenSentToServer() {
if (window.localStorage.getItem('sentToServer') == 1) {
return true;
}
return false;
}
function setTokenSentToServer(sent) {
window.localStorage.setItem('sentToServer', sent ? 1 : 0);
}
function showHideDiv(divId, show) {
const div = document.querySelector('#' + divId);
if (show) {
div.style = "display: visible";
} else {
div.style = "display: none";
}
}
function requestPermission() {
console.log('Requesting permission...');
messaging.requestPermission()
.then(function () {
console.log('Notification permission granted.');
resetUI();
})
.catch(function (err) {
console.log('Unable to get permission to notify.', err);
});
}
function deleteToken() {
messaging.getToken()
.then(function (currentToken) {
messaging.deleteToken(currentToken)
.then(function () {
console.log('Token deleted.');
setTokenSentToServer(false);
resetUI();
})
.catch(function (err) {
console.log('Unable to delete token. ', err);
});
})
.catch(function (err) {
console.log('Error retrieving Instance ID token. ', err);
});
}
// Add a message to the messages element.
function appendMessage(payload) {
const messagesElement = document.querySelector('#messages');
const dataHeaderELement = document.createElement('h5');
const dataElement = document.createElement('pre');
dataElement.style = 'overflow-x:hidden;'
dataHeaderELement.textContent = 'Received message:';
dataElement.textContent = JSON.stringify(payload, null, 2);
messagesElement.appendChild(dataHeaderELement);
messagesElement.appendChild(dataElement);
}
// Clear the messages element of all children.
function clearMessages() {
const messagesElement = document.querySelector('#messages');
while (messagesElement.hasChildNodes()) {
messagesElement.removeChild(messagesElement.lastChild);
}
}
function updateUIForPushEnabled(currentToken) {
showHideDiv(permissionDivId, false);
}
function updateUIForPushPermissionRequired() {
showHideDiv(permissionDivId, true);
}
</script>
sw.js
self.addEventListener('push', function (event) {
console.log('Service Worker recived a push message', event.data.text());
var notification = event.data.json().notification;
var title = notification.title;
event.waitUntil(
self.registration.showNotification(title, {
body: notification.body,
icon: notification.icon,
data: { url: notification.click_action }
}));
});
Thank you for any help you can give!

Related

Authentication Error when trying to retrieve Youtube Chanel Information

I am trying authenticate the user and then retrieve youtube channel list.
Below is the function to authenticate:
function authenticate() {
showNewLoader('show');
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/youtube.readonly"})
.then(function(response) {
console.log( response);
youtubeAuthResponse['token_details'] = response.tc;
youtubeAuthResponse['google_email'] = '';
youtubeAuthResponse['google_id'] = '';
showNewLoader('hide');
},
function(err) { console.error("Error signing in", err); showNewLoader('hide');});
}
Loading client:
function loadClient() {
showNewLoader('show');
gapi.client.setApiKey("XXXXXX");
return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
.then(function() { execute();},
function(err) { console.error("Error loading GAPI client for API", err);showNewLoader('hide');});
}
/*Make sure the client is loaded and sign-in is complete before calling this method.*/
function execute() {
return gapi.client.youtube.channels.list({
"part": [
"snippet",
"statistics"
],
"mine": true
})
.then(function(response) {
/*Handle the results here (response.result has the parsed body).*/
youtubeChannelResponse = response.result;
storeYoutubeData();
},
function(err) { console.error("Execute error", err); showNewLoader('hide') }).then(function(){
});
}
User logs in successfully but I am unable to get the channel info:
Any assistance on this issue is greatly appreciated. #DalmTo

Remote video on both sides won't show up

Currently using Chrome 70, Firefox 64 and Safari 12.
The remote video from the other user is not getting displayed on both sides and I am not quite sure what could be the issue.
There is no errors coming from any of the browsers which does not help in debugging the code.
I am using chrome's internal WebRTC debugging tool (chrome://webrtc-internals) and there is zero packets that have been sent or received.
There's a parameter in the tool which is googCandidatePair but this does not show up at all during a call.
ICEgatheringstatechange event triggers and state that it has completed but only when the host is the chrome user.
I have also tried using
pc.oniceconnectionstatechange = () => console.log(pc.iceConnectionState);
to check for the ICE state changes but this does not trigger at all.
One reason I think it might not be working correctly could be due to how RTCPeerconnection was configured as from this picture, the Ice candidate pool size is 0 but it was never stated in the code itself.
Below are 2 pictures where the first one is when the host is chrome and the other being the receiver
The code is as follows :
'use strict';
var configuration = {
iceServers: [
{
urls: 'stun:stun.l.google.com:19302'
}
]
};
var pc = new RTCPeerConnection(configuration);
// Define action buttons.
const callButton = document.getElementById('callButton');
const hangupButton = document.getElementById('hangupButton');
/////////////////////////////////////////////
window.room = prompt('Enter room name:');
var socket = io.connect();
if (room !== '') {
console.log('Message from client: Asking to join room ' + room);
socket.emit('create or join', room);
}
socket.on('created', function(room) {
console.log('Created room ' + room);
startVideo();
});
socket.on('full', function(room) {
console.log('Message from client: Room ' + room + ' is full :^(');
});
socket.on('joined', function(room) {
console.log('joined: ' + room);
startVideo();
callButton.disabled = true;
});
socket.on('log', function(array) {
console.log.apply(console, array);
});
////////////////////////////////////////////////
async function sendMessage(message) {
console.log('Client sending message: ', message);
await socket.emit('message', message);
}
// This client receives a message
socket.on('message', message => {
if (message.sdp) {
pc.setRemoteDescription(new RTCSessionDescription(message.sdp))
.then(function() {
if (pc.setRemoteDescription.type === 'offer') {
pc.setLocalDescription(pc.createAnswer())
.then(function() {
sendMessage({ sdp: pc.localDescription });
})
.catch(function(err) {
console.log(err.name + ': ' + err.message);
});
}
})
.catch(error => console.error(error));
} else if (message.candidate) {
pc.addIceCandidate(new RTCIceCandidate(message.candidate))
.then(() => {
console.log('Candidates received');
})
.catch(error => console.error(error));
}
});
pc.onicecandidate = event => {
if (event.candidate) {
sendMessage({ candidate: event.candidate });
}
};
pc.ontrack = event => {
if (remoteVideo.srcObject !== event.streams[0]) {
remoteVideo.srcObject = event.streams[0];
console.log('Got remote stream');
}
};
////////////////////////////////////////////////////
const localVideo = document.querySelector('#localVideo');
const remoteVideo = document.querySelector('#remoteVideo');
// Set up initial action buttons status: disable call and hangup.
callButton.disabled = true;
hangupButton.disabled = true;
// Add click event handlers for buttons.
callButton.addEventListener('click', callStart);
hangupButton.addEventListener('click', hangupCall);
function startVideo() {
navigator.mediaDevices
.getUserMedia({
audio: true,
video: true
})
.then(function(stream) {
localVideo.srcObject = stream;
stream.getTracks().forEach(track => pc.addTrack(track, stream));
})
.catch(function(err) {
console.log('getUserMedia() error: ' + err.name);
});
callButton.disabled = false;
}
async function callStart() {
callButton.disabled = true;
hangupButton.disabled = false;
console.log('Sending offer to peer');
await pc
.setLocalDescription(await pc.createOffer())
.then(() => {
sendMessage({ sdp: pc.localDescription });
})
.catch(err => {
console.log(err.name + ': ' + err.message);
});
}
/////////////////////////////////////////////////////////
function hangupCall() {
pc.close();
pc = null;
callButton.disabled = false;
hangupButton.disabled = true;
console.log('Call Ended');
}
You're mixing your promise styles, and you have a bug here:
pc.setLocalDescription(pc.createAnswer()) // bug!
.then(function() {
The above sets the local description to a promise object. Either pick async/await throughout:
await pc.setLocalDescription(await pc.createAnswer());
...or .then() chains:
pc.createAnswer()
.then(answer => pc.setLocalDescription(answer))
.then(function() {
If you pick the latter, don't forget to return all the promises.
Here's the message handler done solely with async/await:
// This client receives a message
socket.on('message', async message => {
try {
if (message.sdp) {
await pc.setRemoteDescription(message.sdp);
if (pc.setRemoteDescription.type === 'offer') {
await pc.setLocalDescription(await pc.createAnswer());
sendMessage({sdp: pc.localDescription});
}
} else if (message.candidate) {
await pc.addIceCandidate(message.candidate);
console.log('Candidates received');
}
} catch (err) {
console.log(err.name + ': ' + err.message);
}
}
If anyone might have problems with the remote video not showing up, I found out that it was because the message was not through the second IF statement that was checking if message.type === offer and since it could not create the answer thus it could not send its local description over to the other user. But by splitting the message up at the start to sdp and candidate, it somehow works.
socket.on('message', async ({ sdp, candidate }) => {
if (sdp) {
await pc.setRemoteDescription(new RTCSessionDescription(sdp));
if (sdp.type === 'offer') {
await pc
.setLocalDescription(await pc.createAnswer())
.then(function() {
sendMessage({ sdp: pc.localDescription });
})
.catch(function(err) {
console.log(err.name + ': ' + err.message);
});
}
} else if (candidate) {
await pc
.addIceCandidate(new RTCIceCandidate(candidate))
.then(() => {
console.log('Candidates received');
})
.catch(error => console.error(error));
}
});

Inconsistent results from Firestore Cloud Functions

I have a Cloud Function setup on Firebase that involved checking different parts of the Firestore Database and then sending a message via Cloud Messaging
Below is the JavaScript for the function in question:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().Firebase);
var db = admin.firestore();
exports.newMemberNotification = functions.firestore
.document('Teams/{teamId}/Waitlist/{userId}').onDelete((snap, context) => {
// get the user we want to send the message to
const newValue = snap.data();
const teamidno = context.params.teamId;
const useridno = newValue.userID;
//start retrieving Waitlist user's messaging token to send them a message
var tokenRef = db.collection('Users').doc(useridno);
tokenRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
const data = doc.data();
//get the messaging token
var token = data.messaging_token;
console.log("token: ", token);
//reference for the members collection
var memberRef = db.collection('Teams/'+teamidno+' /Members').doc(useridno);
memberRef.get()
.then(doc => {
if (!doc.exists){
console.log('user was not added to team. Informing them');
const negPayload = {
data: {
data_type:"team_rejection",
title:"Request denied",
message: "Your request to join the team has been denied",
}
};
return admin.messaging().sendToDevice(token, negPayload)
.then(function(response){
console.log("Successfully sent rejection message:", response);
return 0;
})
.catch(function(error){
console.log("Error sending rejection message: ", error);
});
} else {
console.log('user was added to the team. Informing them')
const payload = {
data: {
data_type: "team_accept",
title: "Request approved",
message: "You have been added to the team",
}
};
return admin.messaging().sendToDevice(token, payload)
.then(function(response){
console.log("Successfully sent accept message:", response);
return 0;
})
.catch(function(error){
console.log("Error sending accept message: ", error);
});
}
})
.catch(err => {
console.log('Error getting member', err);
});
}
return 0;
})
.catch(err => {
console.log('Error getting token', err);
});
return 0;
});
The issues I have with this are:
The code runs and only sometimes actually checks for the token or sends a message.
the logs show this error when the function runs: "Function returned undefined, expected Promise or value " but as per another Stack Oveflow posts, I have added return 0; everywhere a .then ends.
I am VERY new to node.js, javascript and Cloud Functions so I am unsure what is going wrong or if this is an issue on Firebase's end. Any help you can give will be greatly appreciated
As Doug said, you have to return a promise at each "step" and chain the steps:
the following code should work:
exports.newMemberNotification = functions.firestore
.document('Teams/{teamId}/Waitlist/{userId}').onDelete((snap, context) => {
// get the user we want to send the message to
const newValue = snap.data();
const teamidno = context.params.teamId;
const useridno = newValue.userID;
//start retrieving Waitlist user's messaging token to send them a message
var tokenRef = db.collection('Users').doc(useridno);
tokenRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
throw 'No such document!';
} else {
const data = doc.data();
//get the messaging token
var token = data.messaging_token;
console.log("token: ", token);
//reference for the members collection
var memberRef = db.collection('Teams/' + teamidno + '/Members').doc(useridno);
return memberRef.get()
}
})
.then(doc => {
let payload;
if (!doc.exists) {
console.log('user was not added to team. Informing them');
payload = {
data: {
data_type: "team_rejection",
title: "Request denied",
message: "Your request to join the team has been denied",
}
};
} else {
console.log('user was added to the team. Informing them')
payload = {
data: {
data_type: "team_accept",
title: "Request approved",
message: "You have been added to the team",
}
};
}
return admin.messaging().sendToDevice(token, payload);
})
.catch(err => {
console.log(err);
});
});

Firebase client doesnt recieve message

I have the following Node.js script:
var registrationToken = "Long Token";
var serviceAccount = require("./config/ServiceAccount.json");
var payload = {
data: {
score: "850",
time: "2:45"
}
};
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: fireBaseConfig.databaseURL
});
admin.messaging().sendToDevice(registrationToken, payload)
.then(function(response) {
// See the MessagingDevicesResponse reference documentation for
// the contents of response.
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
When running this I do get a success response:
Successfully sent message: { results: [ { messageId: '0:1502813815410638%e609af1cf9fd7ecd' } ],
canonicalRegistrationTokenCount: 0,
failureCount: 0,
successCount: 1,
multicastId: 5249778920849394000 }
Then i have my client:
firebase.initializeApp(config);
var messaging = firebase.messaging();
messaging.requestPermission()
.then(function () {
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
// ...
});
console.log('I am in here');
return messaging.getToken()
.then(function (currentToken) {
console.log(currentToken);
})
.catch(function (err) {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
}).catch(function (err) {
console.log('Error');
});
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
// ...
});
Now first I (as my client) go to the website then I get the token in the console I then use that token in my backend (Node.js) and send a message (while the tap where the client is, is still open) However nothing happens.
Can anyone tell me what I've done wrong?

Receiving one notification for each tab in browser in foreground with FCM

I'm using FCM API to receive push notifications from browser. The firebase-messaging-sw.js works as expected and messaging.setBackgroundMessageHandler fires only once when the web app is in background. However, when the app is in foreground, I'm receiving one notification for each browser tab (if I have the app opened in 3 tabs, I receive 3 notifications). I wonder how should I handle this, since I can't find any reference to this issue. This is the code for FCM messages in the foreground:
import NotificationActionCreators from '../actions/NotificationActionCreators';
import NotificationService from './NotificationService';
import LocalStorageService from './LocalStorageService';
import { FIREBASE_SCRIPT, FCM_URL, FCM_API_KEY, FCM_AUTH_DOMAIN, FCM_PROJECT_ID, FCM_SENDER_ID, PUSH_PUBLIC_KEY } from '../constants/Constants';
class ServiceWorkerService {
constructor() {
this._messaging = null;
this._subscriptionData = null;
}
// This function is called once
init() {
this.loadScript(FIREBASE_SCRIPT, () => this.onFirebaseLoaded());
}
onFirebaseLoaded() {
// Initialize Firebase
let config = {
apiKey: FCM_API_KEY,
authDomain: FCM_AUTH_DOMAIN,
projectId: FCM_PROJECT_ID,
messagingSenderId: FCM_SENDER_ID
};
firebase.initializeApp(config);
this._messaging = firebase.messaging();
this.requestPermission();
// Callback fired if Instance ID token is updated.
this._messaging.onTokenRefresh(() => {
this._messaging.getToken()
.then((refreshedToken) => {
console.log('Token refreshed.');
NotificationActionCreators.unSubscribe(this._subscriptionData).then(() => {
// Indicate that the new Instance ID token has not yet been sent to the
// app server.
this.setTokenSentToServer(false);
// Send Instance ID token to app server.
this.sendTokenToServer(refreshedToken);
}, () => console.log('Error unsubscribing user'));
})
.catch(function(err) {
console.log('Unable to retrieve refreshed token ', err);
});
});
// Handle incoming messages.
// *** THIS IS FIRED ONCE PER TAB ***
this._messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
const data = payload.data;
NotificationActionCreators.notify(data);
});
}
requestPermission() {
console.log('Requesting permission...');
return this._messaging.requestPermission()
.then(() => {
console.log('Notification permission granted.');
this.getToken();
})
.catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
}
getToken() {
// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
return this._messaging.getToken()
.then((currentToken) => {
if (currentToken) {
this.sendTokenToServer(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
this.setTokenSentToServer(false);
}
})
.catch(function(err) {
console.log('An error occurred while retrieving token. ', err);
this.setTokenSentToServer(false);
});
}
sendTokenToServer(currentToken) {
const subscriptionData = {
endpoint: FCM_URL + currentToken,
platform: 'Web'
};
if (!this.isTokenSentToServer()) {
console.log('Sending token to server...');
this.updateSubscriptionOnServer(subscriptionData);
} else {
console.log('Token already sent to server so won\'t send it again ' +
'unless it changes');
}
this._subscriptionData = subscriptionData;
}
isTokenSentToServer() {
return LocalStorageService.get('sentToServer') == 1;
}
setTokenSentToServer(sent) {
LocalStorageService.set('sentToServer', sent ? 1 : 0);
}
updateSubscriptionOnServer(subscriptionData) {
if (subscriptionData) {
NotificationActionCreators.subscribe(subscriptionData);
this.setTokenSentToServer(true);
this._subscriptionData = subscriptionData;
} else {
console.log('Not subscribed');
}
}
unSubscribe() {
this.removeSetTokenSentToServer();
return this._messaging.getToken()
.then((currentToken) => {
return this._messaging.deleteToken(currentToken)
.then(() => {
console.log('Token deleted.');
return NotificationActionCreators.unSubscribe(this._subscriptionData);
})
.catch(function(err) {
console.log('Unable to delete token. ', err);
return new Promise(function(resolve, reject) {
reject(error)
});
});
})
.catch(function(err) {
console.log('Error retrieving Instance ID token. ', err);
return new Promise(function(resolve, reject) {
reject(error)
});
});
}
}
removeSetTokenSentToServer() {
LocalStorageService.remove('sentToServer');
}
loadScript = function (url, callback) {
let head = document.getElementsByTagName('head')[0];
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onload = callback;
// Fire the loading
head.appendChild(script);
}
}
Is there any way to show the notification just for the first tab found?
The only way I've found to achieve this is to check and set a "notification id" variable in the local storage with a setTimeout with a random time:
this._messaging.onMessage(function(payload) {
const data = payload.data;
// This prevents to show one notification for each tab
setTimeout(() => {
if (localStorage.getItem('lastNotificationId')) != parseInt(data.notId)) {
localStorage.setItem('lastNotificationId', parseInt(data.notId))
NotificationActionCreators.notify(data);
}
}, Math.random() * 1000);
});
The notId is sent within the push notification and is an identifier for the notification.
One way is to create a unique variable per tab, say Math.random() or (new Date()).getMilliseconds() and store that on the server with the token. Now the server can target each tab by attaching the variable to the message, with each tab checking the message variable before acting.
To reduces odds of targeting a closed tab, send the variable up with each request, so the server always targets the latest one.
use document.hidden to detect active tab
if (!document.hidden) {
NotificationActionCreators.notify(data);
}

Categories

Resources