I am trying to fetch my device token in javascript. I have included these imports in my HTML page:
<script src="https://www.gstatic.com/firebasejs/9.10.0/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.10.0/firebase-database-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.10.0/firebase-messaging-compat.js"></script>
My javascript:
const firebaseConfig = {
messagingSenderId: "MY SENDER ID FROM CONSOLE",
apiKey: "MY API KEY FROM CONSOLE",
authDomain: "domain_name.firebaseapp.com",
projectId: "domain_name",
storageBucket: "domain_name.appspot.com",
messagingSenderId: "01234643924812",
databaseURL: "https://domain_name-default-rtdb.firebaseio.com",
appId: "1:1230535236326:web:f0fc4f32t23t235122e112c800"
};
const app = firebase.initializeApp(firebaseConfig);
(async()=>{
try {
await firebase.messaging().requestPermission();
const token = await messaging.getToken();
console.log('Your token is:', token);
return token;
} catch (error) {
console.error(error);
}
})();
When I execute the code, I get this error:
TypeError: firebase.messaging(...).requestPermission is not a function
What am I doing wrong?
Related
Hi I using firebase cloud messaging in next js project and when I try to run or build my project I get this error :
info - Checking validity of types
info - Creating an optimized production build
info - Compiled successfully
info - Collecting page data ...node:internal/process/promises:246
triggerUncaughtException(err, true /* fromPromise */);
^
Error: Service messaging is not available
at Provider.getImmediate (file:///I:/Work/Web/Php/Project/wamp/www/test/node_modules/#firebase/component/dist/esm/index.esm2017.js:147:23)
at getMessagingInWindow (I:\Work\Web\Php\Project\wamp\www\test\node_modules#firebase\messaging\dist\index.cjs.js:1460:74)
at I:\Work\Web\Php\Project\wamp\www\test.next\server\pages_app.js:117:83 {
type: 'Error'
}
my code :
it seems this problem happens because using getMessaging
firbase.js
import { initializeApp } from 'firebase/app';
import { getMessaging, getToken, onMessage } from "firebase/messaging";
var firebaseConfig = {
apiKey: "----",
authDomain: "---",
projectId: "---",
storageBucket: "---",
messagingSenderId: "---",
appId: "---",
measurementId: "---"
};
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
export const fetchToken = (setTokenFound) => {
return getToken(messaging, {vapidKey: '---'}).then((currentToken) => {
if (currentToken) {
console.log('current token for client: ', currentToken);
setTokenFound(true);
// Track the token -> client mapping, by sending to backend server
// show on the UI that permission is secured
} else {
console.log('No registration token available. Request permission to generate one.');
setTokenFound(false);
// shows on the UI that permission is required
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// catch error while creating client token
});
}
export const onMessageListener = () =>
new Promise((resolve) => {
onMessage(messaging, (payload) => {
resolve(payload);
});
});
firebase-messaging-sw.js
// Scripts for firebase and firebase messaging
importScripts('https://www.gstatic.com/firebasejs/9.6.11/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.6.11/firebase-messaging-compat.js');
// Initialize the Firebase app in the service worker by passing the generated config
const firebaseConfig = {
apiKey: "----",
authDomain: "---",
projectId: "---",
storageBucket: "---",
messagingSenderId: "---",
appId: "---",
measurementId: "---"
};
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function(payload) {
console.log('Received background message ', payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
_app.tsx
import {fetchToken,onMessageListener} from '../tools/firebase'
const [notification, setNotification] = useState({title: '', body: ''});
const [isTokenFound, setTokenFound] = useState(false);
useEffect(() => {
fetchToken(setTokenFound)
onMessageListener().then(payload => {
setNotification({title: payload.notification.title, body: payload.notification.body})
console.log(payload);
}).catch(err => console.log('failed: ', err));
}, []);
i had same issue turns out it was firebase v9 issue
using firebase v8 worked for me
npm i firebase#8.2.3
after installing v8 don't forget to change syntax its firebase.initializeApp(firebaseConfig);
trying to send push notification to app but i need permission from user for that but getting this error that messaging.requestPermission is not a function ,
here is my code for push notification.js file
import * as firebase from 'firebase/app';
import { getMessaging } from "firebase/messaging";
export const initializeFirebase = () => {
firebase.initializeApp({
apiKey: "",
authDomain: "",
projectId: "pushnotification-9b180",
storageBucket: "pushnotification-9b180.appspot.com",
messagingSenderId: "878043563283",
appId: "1:878043563283:web:c2a44f3c8b02ad8a17c6e6",
measurementId: "G-GMWQKL94ZD"
});
}
export const askForPermissionToReceiveNotifications = async () => {
try {
const messaging = getMessaging();
await messaging.requestPermission();
const token = await messaging.getToken();
console.log('Your token is:', token);
return token;
} catch (error) {
console.error(error);
}
}
Here is the screenshot of errorserros
What are you using react-native or react?
but in react-native way you need add this line
import messaging from '#react-native-firebase/messaging';
you donĀ“t need
const messaging = getMessaging();
import * as firebase from 'firebase/app';
import { getMessaging } from "firebase/messaging";
export const initializeFirebase = () => {
firebase.initializeApp({
apiKey: "",
authDomain: "",
projectId: "pushnotification-9b180",
storageBucket: "pushnotification-9b180.appspot.com",
messagingSenderId: "878043563283",
appId: "1:878043563283:web:c2a44f3c8b02ad8a17c6e6",
measurementId: "G-GMWQKL94ZD"
});
}
export const askForPermissionToReceiveNotifications = async () => {
try {
const messaging = getMessaging();
await messaging.requestPermission();
const token = await messaging.getToken();
console.log('Your token is:', token);
return token;
} catch (error) {
console.error(error);
}
}
I am trying to integrate firebase cloud messaging 'FCM' on my payment page. it shows numberTokensSuccess 1 but no payload. I am writing the output to console.I am not getting any error.It is not working. Please help
I'm using https://github.com/brozot/Laravel-FCM .
I have added to top of the page
<script src="https://www.gstatic.com/firebasejs/7.21.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.21.1/firebase-messaging.js"></script>
<link rel="manifest" href="{{ asset('core/manifest.json') }}" />
my firebase.js <script src="{{ asset('assets/js/firebase.js') }}"></script>
const firebaseConfig = {
apiKey: "XXX",
authDomain: "XXX",
databaseURL: "XXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX",
appId: "XXX",
measurementId: "XXX"
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function() {
console.log("Notification permission granted");
return messaging.getToken();
}).then(function(token) {
$('#device_token').val(token);
console.log(token);
}).catch(function (err){
console.log("Unable to get the permission to notify",err);
});
messaging.onMessage((payload) => {
console.log(payload);
});
firebase-messaging-sw.js
importScripts("https://www.gstatic.com/firebasejs/7.21.1/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/7.21.1/firebase-messaging.js");
const firebaseConfig = {
apiKey: "XXX",
authDomain: "XXX",
databaseURL: "XXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX",
appId: "XXX",
measurementId: "XXX"
};
firebase.initializeApp(firebaseConfig);
const msg = firebase.messaging()
msg.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message',payload);
var notificationTitle = 'Background Message Title';
var notificationOptions =
{
body: 'Background Message Body',
icon: '/firebase-logo.png'
}
return self.registration.showNotification(notificationTitle, notificationOptions);
});
I have setup Firebase admin structure and generate all required id, key and token. With Firebase email and password auth it works fine. But when implementing Google signin it fails. Please help.
index.html code
`<i class="icon fab fa-google-plus-g"></i>`
<script src="js/firebase.js"></script>
<script src="js/firebase-auth.js"></script>
<script>
// Initialize Firebase
var configfirebase = {
apiKey: "***********************",
authDomain: "*****************.firebaseapp.com",
databaseURL: "https://f*************.firebaseio.com",
projectId: "************",
storageBucket: "************",
messagingSenderId: "**********",
};
firebase.initializeApp(configfirebase);
</script>
registration.js code
var provider = new firebase.auth.GoogleAuthProvider();
function firebaselogin() {
firebase.auth().signInWithRedirect(provider).then(function() {
return firebase.auth().getRedirectResult();
}).then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
app.dialog.alert('Login success!! Welcome:' + result.user );
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
app.dialog.alert('Login error!! error:' + errorMessage );
});
}
When I run the app I get this error.
I have fixed that issue by just placing the firebase-app js to top.
I am trying to send data form my server to FCM, so that it can be shown on a specific section of my web page. It's like a stock application for example, where the data is constantly updated. In the same way am trying to achieve. So far I have configured it to receive data from FCM and it is being received. But the problem is that it shows the notification to like. My colleague are working on the same there is a option to send only data to the android app and hide notifications to be shown. Likewise I want to do it hear on web, but am unable to do it.
(function () {
// Initialize Firebase
var config = {
apiKey: "xxxxxxxxxxxxxx",
authDomain: "test-xxxxxxxx.xxxxxxxx.com",
databaseURL: "https://xxxxxx-xxxxxxxx.firebaseio.com",
projectId: "xxx-469e9",
storageBucket: "",
messagingSenderId: "xxxxxx"
};
firebase.initializeApp(config);
// Retrieve Firebase Messaging object.
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);
// ...
});
}());
on firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js');
// Initialize Firebase
var config = {
apiKey: "xxxxxx",
authDomain: "xxxx-xxxxxxxxxx.com",
databaseURL: "https://xxx-xxx.firebaseio.com",
projectId: "xxxx-xxxxxxxxxx",
storageBucket: "",
messagingSenderId: "xxxxxxxxxxxx"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
A hack would be to close the notification just after...
messaging.setBackgroundMessageHandler(function (payload) {
var realPush = true;
if(realPush)
{
const notificationOptions = {
body: "It is a REAL push",
data:"true"
};
//We display the notification
return self.registration.showNotification(title, notificationOptions);
}else
{
const notificationOptions = {
body: "It is a SILENT push",
data:"false"
};
//We display a fake notification
return self.registration.showNotification('To delete',notificationOptions).then(function () {
self.registration.getNotifications().then(notifications => {
console.log(notifications);
for (var i =0;i<notifications.length;i++)
{
if(notifications[i].data != "true")
{
//then we destroy the fake notification immedialtely !
notifications[i].close();
}
}
})
});
}
});
The realPush parameter is of course managed by yourself