Javascript Firebase:无法在我的web浏览器上接收通知
我使用的是Javascript Firebase:无法在我的web浏览器上接收通知,javascript,laravel,firebase,firebase-notifications,Javascript,Laravel,Firebase,Firebase Notifications,我使用的是Laravel 5.4,我刚刚开始学习firebase messaging,如果有人发送通知,我想在我的web浏览器上获取该通知 我实现的是,在母版页中,我导入了firebase脚本,如下所示: resources/views/layouts/master.blade.php: <script src="https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js"></script> <script s
Laravel 5.4
,我刚刚开始学习firebase messaging
,如果有人发送通知,我想在我的web浏览器上获取该通知
我实现的是,在母版页
中,我导入了firebase脚本
,如下所示:
resources/views/layouts/master.blade.php:
<script src="https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/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>
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");
}
使用console登录浏览器,我将获得消息requestPermission通知权限。
和get token
以及生成的令牌
在Mozilla firefox中,似乎一切正常,但在chrome中,我遇到了以下javascript错误:
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.com/firebasejs/4.8.1/firebase-messaging.js:6:11342) ..."
现在,要发送消息,我使用post man:
Request type: post
URL: https://fcm.googleapis.com/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
}
我得到的成功回应如下:
{
"multicast_id": 5************1,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "https://updates.push.services.mozilla.com/m/gAAAAA***********byb"
}
]
}
但是,我无法在浏览器上获得通知。如果收到通知,则它必须控制台记录我在setBackgroundMessageHandler
或messaging.onMessage
方法中输入的语句
我是否遗漏了什么或是配置错误?
另外,所有这些代码都在我的linux服务器上的HTTPS上运行 而不是使用{{HTML::script('firebase-messaging-sw.js')}
使用
从后端,您需要发出curl请求:
$url='http://fcm.googleapis.com/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);
作为firebase合规性,您必须使用适当的负载发出curl请求。
我在fields对象中使用了$registration\u id,这意味着为特定设备/web应用程序生成了fcm\u令牌。根据
而不是在resources/views/layouts/master.blade.php文件中引用服务工作者
您可以在firebase messaging service worker(firebase messaging sw.js)中包含firebase初始化过程。现在每天都有Stackoverflow上可用的专家吗?只是猜测一下,但是您的firebase messaging sw.js
是否能够找到messaging
?我认为消息传递
miilight只需要在服务人员中初始化,还不确定。运气不好。我已经更新了脚本标记,并使用Post man发送了一个示例请求,如中所述。请求成功发送,并且返回多播_id,且成功标志为true。但在客户端,我无法收到通知。您是否已在参数中发送注册设备fcm令牌。当然可以。请求正文是:{“通知”:{“标题”:“背景消息标题”,“正文”:“背景消息正文”,“单击操作”:https://dummypage.com“}”,收件人:“f6KPKuqSeCU******************************************f”}
,URL:https://fcm.googleapis.com/fcm/send
,标题:Authorization:key=AAAA******************************************************g
,内容类型:application/json
。