【问题标题】:Firebase: Not able to receive notification on my web browserFirebase:无法在我的网络浏览器上接收通知
【发布时间】:2018-08-13 23:01:21
【问题描述】:

我正在使用Laravel 5.4,我刚刚开始学习firebase messaging,如果有人发送,我想在我的网络浏览器上获取notification

我实现的是,在master page 中,我导入了firebase scripts,如下所示:

资源/视图/布局/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>

还有

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

通过浏览器上的控制台登录,我收到消息requestPermission Notification permission granted.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) ..."

现在,我使用邮递员发送消息:

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"
        }
    ]
}

但是,我无法在浏览器上收到通知。如果收到通知,那么它必须控制台记录我在setBackgroundMessageHandlermessaging.onMessage 方法中放入的语句。

我是否遗漏或配置错误? 附言所有这些代码都在我的 linux 服务器上的 HTTPS 上运行。

【问题讨论】:

  • 现在 Stackoverflow 上有没有专家可用?
  • 只是猜测,但您的firebase-messaging-sw.js 能找到messaging 吗?我认为messagingmiiiight 只需要在服务工作者中初始化,还不确定。

标签: javascript laravel firebase firebase-notifications


【解决方案1】:

而不是使用 {{ HTML::script('firebase-messaging-sw.js')}}

使用&lt;script src="/firebase-messaging-sw.js"&gt;&lt;/script&gt;

你需要从后端发出 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);

您必须使用适当的有效负载发出 curl 请求,以符合 Firebase 要求。 我在字段对象中使用了 $registration_id,这意味着为该特定设备/Web 应用程序生成了 fcm_token。

【讨论】:

  • 不走运。如firebase.google.com/docs/cloud-messaging/js/receive 中所述,我已更新脚本标签并使用 Post-man 发送示例请求。请求成功发送,并且它返回了成功标志为 true 的 multicast_id。但是在客户端,但是我无法收到通知。
  • 参数中是否发送了注册的设备fcm token。
  • 当然可以。请求正文为:{ "notification": { "title": "Background Message Title", "body": "Background message body", "click_action" : "https://dummypage.com" }, "to" : "f6KPKuqSeCU*************************************f" },URL:https://fcm.googleapis.com/fcm/send,标头:Authorization:key=AAAA************************************************gContent-Type:application/json
【解决方案2】:

根据Google描述的最佳实践,

而不是在文件 resources/views/layouts/master.blade.php 中引用 service worker

您可以在 Firebase 消息传递服务工作线程 (firebase-messaging-sw.js) 中包含 firebase 初始化过程

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 2012-05-10
    • 2013-02-14
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多