Remote video on both sides won't show up - javascript

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));
}
});

Related

Simple peer and socket.io keeps sending back and forth requests 100s of times. Unable to establish signal connections

I am trying to establish a connection between the two different users on the server. Every time a users joins the room he gets the info about the socket.ids of other users in the room. What they try and do is the new user creates an initiator peer and sends a signal . Which the other peer accepts for some reason they both keep sending each other back and forth requests and no one access each other requests this is what is happening.
A picture of the backend console
createPeer = (userToSignal, callerId, stream) => {
console.log('create peer called', userToSignal);
const peer = new Peer({
initiator: true,
trickle: false,
stream: stream
})
peer.on('signal', signal => {
console.log('sending a signal to server')
this.socket.emit('sending signal', {
'userToSignal': userToSignal,
'callerId': callerId,
'signal': signal
});
});
return peer;
}
addPeer = (incomingSignal, callerId, stream) => {
console.log('Add peer called', callerId);
const peer = new Peer({
initiator: false,
trickle: false,
stream: stream
});
peer.signal(JSON.stringify(incomingSignal));
peer.on('signal', signal =>{
console.log('returning a signal to : ', callerId)
this.socket.emit('returning signal', {
'signal': signal,
'callerId': callerId
});
});
return peer;
}
joinCall = () => {
navigator.mediaDevices.getUserMedia({ video: false, audio: true }).then(stream => {
console.log(this.socket.id);
this.socket.emit('join call', this.state.id, this.state.userName);
console.log('Join Call Called')
this.socket.on('all users', (usersInThisRoom) => {
console.log('all users ', usersInThisRoom);
const peers = [];
usersInThisRoom.forEach(user => {
console.log('for each called')
const peer = this.createPeer(user['id'], this.socket.id, stream);
peers.push({
'peerId' : user['id'],
'peer': peer
})
});
this.peersRefs = peers;
this.setState({peersRefs : this.peersRefs});
});
this.socket.on('user joined', payload => {
console.log('new user has joined', payload['callerId']);
const peer = this.addPeer(payload['signal'], payload['callerId'], stream);
this.peersRefs.push({
'peerId': payload['callerId'],
'peer': peer
})
this.setState({'peersRefs': this.peersRefs});
});
this.socket.on('receiving returned signal', payload => {
console.log('returned signal recieved ', payload.id)
const peerToSignal = this.peersRefs.find(peer => peer['peerId'] === payload.id)
peerToSignal['peer'].signal(JSON.stringify(payload.signal));
});
});
console.log('joining')
}
This is my front end code ^^
// Changes start
socket.on('join call', (roomId, name) => {
console.log('New User ', name)
SessionModel.findById(roomId, (err, session, callback) => {
if (err) throw err;
let users = session.usersInCall;
if (users.length === 10) {
return;
}
let userObject = { 'id' : socket.id, 'name' : name};
users.push(userObject);
SessionModel.findOneAndUpdate({_id: roomId}, {usersInCall: users}, {
new: true
},
(err) => {
if (err) throw err
});
const usersInThisRoom = users.filter(user => {
return user['id'] !== socket.id;
});
console.log(usersInThisRoom);
socket.emit("all users", usersInThisRoom);
})
})
socket.on('sending signal', payload => {
console.log('Sending Signal',payload['userToSignal'] );
io.to(payload['userToSignal']).emit('user joined', {
'signal': payload['signal'],
'callerId': payload['callerId']
});
})
socket.on('returning signal', payload => {
console.log('forwarding signal ',payload['callerId'])
io.to(payload['callerId']).emit('receiving returned signal', {
'signal' : payload['signal'],
'id': socket.id
});
})
This is my back end code ^^^
Try putting all ur socketio listners inside useEffect
Looks like you have created an infinite loop. Form the backend logs is
"forwarding signal ......" should have only be printed once. As the client socket is emitting the event returning signal twice.
Adding the client console logs would have helped in debugging.

Error "Function returned undefined, expected Promise or value" even after return in all places

I am new to Node.js and I am struggling with Promises even after reading the tutorials provided by other stackflow users. I have already spent a whole evening on this and I am looking for help. I get the following error " Function returned undefined, expected Promise or value". My code is below. What am I doing wrong? I also have a suspicion that I have to use await/async because it looks like my code is running through without waiting for the first get to complete.
const admin = require('firebase-admin');
const functions = require('firebase-functions');
var db = admin.firestore();
exports.declinedRequest = functions.firestore
.document('requests/{requestId}')
.onUpdate((change, context) => {
const newValue = change.after.data();
const status = newValue.status;
const request = context.params.requestId;
var registrationToken;
var message;
if(status=="created") {
console.log('Checkpoint1 ',context.params.requestId);
newValue.friends.forEach(doc => {
console.log('Checkpoint 2: ', doc);
var usersRef = db.collection('users');
var query = usersRef.where('mobile', '==', doc).get()
.then(snapshotFriend => {
if (snapshotFriend.empty) {
console.log('Checkpoint3.');
return;
}
snapshotFriend.forEach(mobile => {
registrationToken = mobile.data().fcmToken;
console.log('FCM token =>', registrationToken);
if (!registrationToken) {
console.log('No fcmToken available');
return;
}
message = {
notification: {
body: "Request still available from " + newValue.requesterName,
sound: "default",
badge: 1
},
data: {
requestId: `${request}`
}
};
console.log('FCM token message created');
})
})
})
} else {
return;
}
return admin.messaging().sendToDevice(registrationToken, message)
.then(function (response) {
console.log("Successfully sent message:", response)
})
.catch(function (error) {
console.log("Error sending message:", error);
})
})
Try the code below hope this will work.
const admin = require('firebase-admin');
const functions = require('firebase-functions');
const Promise = require('bluebird');
const _ = require('lodash');
let db = admin.firestore();
exports.declinedRequest = functions.firestore
.document('requests/{requestId}')
.onUpdate((change, context) => {
const newValue = change.after.data();
const status = newValue.status;
const request = context.params.requestId;
if (status == "created") {
console.log('Checkpoint1 ', context.params.requestId);
allPromises = [];
newValue.friends.forEach(doc => {
console.log('Checkpoint 2: ', doc);
const usersRef = db.collection('users');
// query for each document return promise.
allPromises.push(queryForEachDocument(doc,request,usersRef));
});
return Promise.all(allPromises);
} else {
return Promise.reject / resolve('Whatever you want.');
}
})
function queryForEachDocument(doc,request,usersRef) {
let promiseInvoices = []
let registrationToken;
let message;
return usersRef.where('mobile', '==', doc).get().then((snapshotFriend) => {
if (_.isEmpty(snapshotFriend)) {
console.log('Checkpoint3.');
return Promise.reject(new Error('Your error'));
}
snapshotFriend.forEach(mobile => {
registrationToken = mobile.data().fcmToken;
console.log('FCM token =>', registrationToken);
if (!registrationToken) {
console.log('No fcmToken available for', newValue.requesterName);
// Do anything you want to change here.
return Promise.reject(new Error('No fcmToken available for',newValue.requesterName));
}
message = {
notification: {
body: "Request still available from " + newValue.requesterName,
sound: "default",
badge: 1
},
data: {
requestId: request
}
};
console.log('FCM token message created');
// send invoice for each registrationToken
promiseInvoices.push(sendInvoice(registrationToken, message))
});
}).then(() => {
return Promise.all(promiseInvoices);
})
}
function sendInvoice(registrationToken, message) {
return admin.messaging().sendToDevice(registrationToken, message)
.then(function (response) {
console.log("Successfully sent message:", response)
})
.catch(function (error) {
console.log("Error sending message:", error);
})
}

Not enough arguments to RTCPeerConnection.setRemoteDescription [duplicate]

This question already has an answer here:
RTCPeerConnection.createAnswer callback returns undefined object in mozilla for WebRTC chat
(1 answer)
Closed 4 years ago.
Currently having the follow error in Firefox 64 where its giving this error which I have been searching online for a working fix but could not find one.
TypeError: "Not enough arguments to RTCPeerConnection.setRemoteDescription."
Been using a few of the links to fix but to no avail and also the latter is outdated.
https://developer.mozilla.org/en-US/docs/Web/API/RTCSessionDescription
WebRTC Firefox: Not enough arguments to RTCPeerConnection.setLocalDescription
Chrome triggers another error which is main.js:58 Uncaught TypeError: Cannot read property 'type' of undefined and this is when there's a if statement to check if the remotedescription.type matches offer
Would be grateful if anyone knows a fix.
'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', async message => {
if (message.sdp) {
await pc
.setRemoteDescription(new RTCSessionDescription(message.sdp), () => {
if (pc.remotedescription.type === 'offer') {
pc.setLocalDescription(pc.createAnswer())
.then(function() {
sendMessage({ sdp: pc.localDescription });
})
.catch(function(err) {
console.log(err.name + ': ' + err.message);
});
} else {
pc.addIceCandidate(new RTCIceCandidate(message.candidate)).catch(
error => console.error(error)
);
}
})
.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(function() {
sendMessage(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 are calling pc.setRemoteDescription(desc, callback) but do not provide an error callback, using a .catch instead. Firefox does not like using a callback without providing an error callback as well which leads to the "Not enough arguments" error.
Don't mix the deprecated callbacks with promises but instead use pc.setRemoteDescription(desc).then(() => ...).catch(...)

Failed to execute 'setLocalDescription' on 'RTCPeerConnection

I have been having this error for a while
Have been trying to use async to wait for the local description to be updated but as how my code works right now it would not be able to integrate it and also I heard that socket.on already does async itself.
I have also tried using breakpoints in vs code to debug the code which doesn't work well.
Would greatly appreciate if anyone knows a workaround for this.
The code is attached below
'use strict';
var localStream;
var remoteStream;
var isInitiator;
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);
isInitiator = true;
startVideo();
});
socket.on('joined', function(room) {
console.log('joined: ' + room);
startVideo();
});
socket.on('log', function(array) {
console.log.apply(console, array);
});
////////////////////////////////////////////////
function sendMessage(message) {
socket.emit('message', message);
}
// This client receives a message
socket.on('message', function(message) {
try {
if (message.type === 'offer') {
pc.setRemoteDescription(new RTCSessionDescription(message));
// const stream = navigator.mediaDevices.getUserMedia({
// audio: true,
// video: true
// });
// stream.getTracks().forEach(track => pc.addTrack(track, localStream));
pc.setLocalDescription(
pc.createAnswer(setLocalAndSendMessage, function(err) {
console
.log(err.name + ': ' + err.message)
.then(pc.setLocalDescription);
})
);
} else if (message.type === 'answer') {
console.log('This is to check if answer was returned');
pc.setRemoteDescription(new RTCSessionDescription(message));
} else if (message.type === 'candidate') {
pc.addIceCandidate(candidate);
}
} catch (err) {
console.error(err);
}
});
////////////////////////////////////////////////////
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(mediaStream) {
localStream = mediaStream;
localVideo.srcObject = mediaStream;
})
.catch(function(err) {
console.log('getUserMedia() error: ' + err.name);
});
callButton.disabled = false;
}
function callStart() {
createPeerConnection();
//pc.addTrack(mediaStream);
//stream.getTracks().forEach(track => pc.addTrack(track, localStream));
callButton.disabled = true;
hangupButton.disabled = false;
if (isInitiator) {
console.log('Sending offer to peer');
pc.createOffer(setLocalAndSendMessage, function(err) {
console.log(err.name + ': ' + err.message).then(pc.setLocalDescription);
});
}
}
/////////////////////////////////////////////////////////
function createPeerConnection() {
try {
pc = new RTCPeerConnection(null);
pc.onicecandidate = ({ candidate }) => sendMessage({ candidate });
pc.ontrack = event => {
if (remoteVideo.srcObject) return;
remoteVideo.srcObject = event.streams[0];
};
console.log('Created RTCPeerConnnection');
} catch (e) {
console.log('Failed to create PeerConnection, exception: ' + e.message);
alert('Cannot create RTCPeerConnection object.');
return;
}
}
function setLocalAndSendMessage(sessionDescription) {
console.log('setLocalAndSendMessage sending message', sessionDescription);
pc.setLocalDescription(sessionDescription);
sendMessage(sessionDescription);
}
function hangupCall() {
pc.close();
pc = null;
}
There is no workaround to understanding asynchronous code. You're cut'n'pasting your way here.
If you're not going to use async/await, then you need to contend with that JavaScript is single-threaded, and can't ever block to wait for an asynchronous operation to finish, so you can never just use the return value from an asynchronous method directly, like you're trying to do here:
createAnswer is an asynchronous method, returning a promise, not an answer, so this is wrong:
pc.setLocalDescription( // <-- wrong
pc.createAnswer(setLocalAndSendMessage, function(err) { //
console
.log(err.name + ': ' + err.message)
.then(pc.setLocalDescription);
})
);
You're calling setLocalDescription(promise), which gives you the error you mention, since a promise is not a valid description. Instead, a promise is an object you attach callbacks to:
const promise = pc.createAnswer();
promise.then(setLocalAndSendMessage, function(err) {
console.log(err.name + ': ' + err.message);
});
or simply:
pc.createAnswer()
.then(setLocalAndSendMessage, function(err) {
console.log(err.name + ': ' + err.message);
});
We can even use then successively to form a promise chain:
pc.createAnswer()
.then(function(answer) {
return pc.setLocalDescription(answer);
})
.then(function() {
sendMessage(pc.localDescription);
})
.catch(function(err) {
console.log(err.name + ': ' + err.message);
});
Also, I shouldn't have to tell you console.log() does not return a promise!
Sadly, you're copying really old code here, and RTCPeerConnection has some legacy APIs and does some tricks to sometimes let callers get away with calling these negotiation methods without truly promise-chaining or checking for errors. But it inevitably leads to trouble.

Chrome not receiving fcm messages, but firefox does

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!

Categories

Resources