admin管理员组文章数量:1405170
I am using Laravel 5.4
, I have just started learning firebase messaging
and I want to get the notification
on my web-browser if someone sends it.
What I've implemented is, in a master page
I have imported firebase scripts
as below:
resources/views/layouts/master.blade.php:
<script src=".8.1/firebase-app.js"></script>
<script src=".8.1/firebase-messaging.js"></script>
<script type="text/javascript">
firebase.initializeApp({
'messagingSenderId': '1***************2' //i.e.My firebase key
});
const messaging = firebase.messaging();
</script>
{{ HTML::script('firebase-messaging-sw.js')}} // This script file is there in the public (i.e. root) directory
<script type="text/javascript">
messaging.onMessage(function(payload){
console.log('onMessage', payload);
});
</script>
And
firebase-messaging-sw.js:
if ('serviceWorker' in navigator) {
console.log("serviceWorker exists");
navigator.serviceWorker.register('/../firebase-messaging-sw.js')
.then((registration) => {
messaging.useServiceWorker(registration);
messaging.requestPermission()
.then(function() {
console.log('requestPermission Notification permission granted.');
return messaging.getToken();
})
.then(function(token) {
console.log("requestPermission: ", token); // Display user token
})
.catch(function(err) { // Happen if user deney permission
console.log('requestPermission: Unable to get permission to notify.', err);
});
// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken()
.then(function(currentToken) {
if (currentToken) {
console.log("getToken", currentToken);
} else {
// Show permission request.
console.log('getToken: No Instance ID token available. Request permission to generate one.');
}
})
.catch(function(err) {
console.log('getToken: An error occurred while retrieving token. ', err);
});
// Callback fired if Instance ID token is updated.
messaging.onTokenRefresh(function() {
messaging.getToken()
.then(function(refreshedToken) {
console.log('onTokenRefresh getToken Token refreshed.');
console.log('onTokenRefresh getToken', refreshedToken);
})
.catch(function(err) {
console.log('onTokenRefresh getToken Unable to retrieve refreshed token ', err);
});
});
// [START background_handler]
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle, notificationOptions);
});
// [END background_handler]
});
}
else {
console.log("serviceWorker does not exists");
}
With console log on browser, I am getting messages requestPermission Notification permission granted.
and get token
along with a token generated.
In Mozilla firefox, it seems everything OK but in chrome I am getting this javascript error:
controller-interface.js:137
Uncaught (in promise) e
{
code: "messaging/only-available-in-sw",
message: "Messaging: This method is available in a service worker context. (messaging/only-available-in-sw).",
stack: "FirebaseError: Messaging: This method is available…irebase-messaging-sw.js:67:19)"
}
code:
"messaging/only-available-in-sw"message: "Messaging: This method is available in a service worker context. (messaging/only-available-in-sw).
"stack: "FirebaseError: Messaging: This method is available in a service worker context. (messaging/only-available-in-sw) at t.e.setBackgroundMessageHandler (.8.1/firebase-messaging.js:6:11342) ..."
Now, to send message I am using post-man:
Request type: post
URL:
Headers: Authorization: key=AAA*****fg // i.e. my authorization token
Body:
{
"notification": {
"title": "Some title",
"body": "Some body",
"icon": "firebase-logo.png",
"click_action": ""
},
"to": "f3ea******q" //token generated by firebase using getToken method
}
And I am getting a success response as:
{
"multicast_id": 5************1,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "***********byb"
}
]
}
But, however I am not able to get the notification on my browser. If the notification is received then it must console log the statements I have put in setBackgroundMessageHandler
or messaging.onMessage
methods.
Am I missing or misconfigured something? P.S. All these codes are running on HTTPS on my linux server.
I am using Laravel 5.4
, I have just started learning firebase messaging
and I want to get the notification
on my web-browser if someone sends it.
What I've implemented is, in a master page
I have imported firebase scripts
as below:
resources/views/layouts/master.blade.php:
<script src="https://www.gstatic./firebasejs/4.8.1/firebase-app.js"></script>
<script src="https://www.gstatic./firebasejs/4.8.1/firebase-messaging.js"></script>
<script type="text/javascript">
firebase.initializeApp({
'messagingSenderId': '1***************2' //i.e.My firebase key
});
const messaging = firebase.messaging();
</script>
{{ HTML::script('firebase-messaging-sw.js')}} // This script file is there in the public (i.e. root) directory
<script type="text/javascript">
messaging.onMessage(function(payload){
console.log('onMessage', payload);
});
</script>
And
firebase-messaging-sw.js:
if ('serviceWorker' in navigator) {
console.log("serviceWorker exists");
navigator.serviceWorker.register('/../firebase-messaging-sw.js')
.then((registration) => {
messaging.useServiceWorker(registration);
messaging.requestPermission()
.then(function() {
console.log('requestPermission Notification permission granted.');
return messaging.getToken();
})
.then(function(token) {
console.log("requestPermission: ", token); // Display user token
})
.catch(function(err) { // Happen if user deney permission
console.log('requestPermission: Unable to get permission to notify.', err);
});
// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken()
.then(function(currentToken) {
if (currentToken) {
console.log("getToken", currentToken);
} else {
// Show permission request.
console.log('getToken: No Instance ID token available. Request permission to generate one.');
}
})
.catch(function(err) {
console.log('getToken: An error occurred while retrieving token. ', err);
});
// Callback fired if Instance ID token is updated.
messaging.onTokenRefresh(function() {
messaging.getToken()
.then(function(refreshedToken) {
console.log('onTokenRefresh getToken Token refreshed.');
console.log('onTokenRefresh getToken', refreshedToken);
})
.catch(function(err) {
console.log('onTokenRefresh getToken Unable to retrieve refreshed token ', err);
});
});
// [START background_handler]
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle, notificationOptions);
});
// [END background_handler]
});
}
else {
console.log("serviceWorker does not exists");
}
With console log on browser, I am getting messages requestPermission Notification permission granted.
and get token
along with a token generated.
In Mozilla firefox, it seems everything OK but in chrome I am getting this javascript error:
controller-interface.js:137
Uncaught (in promise) e
{
code: "messaging/only-available-in-sw",
message: "Messaging: This method is available in a service worker context. (messaging/only-available-in-sw).",
stack: "FirebaseError: Messaging: This method is available…irebase-messaging-sw.js:67:19)"
}
code:
"messaging/only-available-in-sw"message: "Messaging: This method is available in a service worker context. (messaging/only-available-in-sw).
"stack: "FirebaseError: Messaging: This method is available in a service worker context. (messaging/only-available-in-sw) at t.e.setBackgroundMessageHandler (https://www.gstatic./firebasejs/4.8.1/firebase-messaging.js:6:11342) ..."
Now, to send message I am using post-man:
Request type: post
URL: https://fcm.googleapis./fcm/send
Headers: Authorization: key=AAA*****fg // i.e. my authorization token
Body:
{
"notification": {
"title": "Some title",
"body": "Some body",
"icon": "firebase-logo.png",
"click_action": ""
},
"to": "f3ea******q" //token generated by firebase using getToken method
}
And I am getting a success response as:
{
"multicast_id": 5************1,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "https://updates.push.services.mozilla./m/gAAAAA***********byb"
}
]
}
But, however I am not able to get the notification on my browser. If the notification is received then it must console log the statements I have put in setBackgroundMessageHandler
or messaging.onMessage
methods.
Am I missing or misconfigured something? P.S. All these codes are running on HTTPS on my linux server.
Share Improve this question edited Mar 14, 2018 at 16:31 Karl Taylor 5,2894 gold badges39 silver badges65 bronze badges asked Mar 6, 2018 at 6:46 DevDev 6,72013 gold badges71 silver badges112 bronze badges 2- Any experts available on Stackoverflow now-a-days? – Dev Commented Mar 12, 2018 at 4:53
-
just a guess but is your
firebase-messaging-sw.js
able to findmessaging
? I thinkmessaging
miiiight need to be only initialized in the service worker, not sure yet. – Ryan Taylor Commented Apr 24, 2019 at 21:27
2 Answers
Reset to default 1Instead of using the {{ HTML::script('firebase-messaging-sw.js')}}
Use <script src="/firebase-messaging-sw.js"></script>
From backend You need to make curl request:
$url='http://fcm.googleapis./fcm/send';
$fields =array("registration_ids"=> $registration_id,"data"=> $message,
"priority"=>'high');
$headers = array('Authorization: key=xxxxxx','Content-Type:
application/json');
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
You have to make curl request with a proper payload as firebase pliance. I have used $registration_id in the fields object, which means generated fcm_token to that particular device/web app.
According to the best practice described by Google,
Instead of having the service worker referenced in the file resources/views/layouts/master.blade.php
You can include the firebase initialization process in the Firebase messaging service worker (firebase-messaging-sw.js)
本文标签: javascriptFirebase Not able to receive notification on my web browserStack Overflow
版权声明:本文标题:javascript - Firebase: Not able to receive notification on my web browser - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744281451a2598672.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论