简体   繁体   English

Firebase云消息传递/使用JavaScript将通知推送到Web平台未收到消息

[英]Firebase Cloud Messaging / Pushing Notification to Web platform using JavaScript is not receiving the message

Now I am developing a Web application that needs to use the live-notification feature. 现在,我正在开发一个需要使用实时通知功能的Web应用程序。 I am using Google Firebase's Cloud Messaging service. 我正在使用Google Firebase的Cloud Messaging服务。 I can successfully register the service and retrieve the token value using JavaScript. 我可以成功注册服务并使用JavaScript检索令牌值。 But when I push the message from the REST Client, my platform is not triggering the onMessage event. 但是,当我从REST Client推送消息时,我的平台没有触发onMessage事件。

This is my full code. 这是我的完整代码。

<html>
<head>
    <title>FCM</title>
</head>
<body>
<h1>This is the FCM</h1>

<script src="https://www.gstatic.com/firebasejs/5.3.1/firebase-app.js"></script>
<!-- Add additional services that you want to use -->
<script src="https://www.gstatic.com/firebasejs/5.3.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.3.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.3.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.3.1/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.3.1/firebase-functions.js"></script>

<script>
    // Initialize Firebase
    var config = {
        apiKey: "xxx",
        authDomain: "fcm-web-testing.firebaseapp.com",
        databaseURL: "https://fcm-web-testing.firebaseio.com",
        projectId: "fcm-web-testing",
        storageBucket: "fcm-web-testing.appspot.com",
        messagingSenderId: "xxxx"
    };
    firebase.initializeApp(config);

    const messaging = firebase.messaging();
    messaging.requestPermission().then(function(){
        console.log(messaging.getToken());
        return messaging.getToken();
    }).then(function(token){
        //I get the token here. I use this token to push the notification
        console.log(token);
    })
        .catch(function(err){
            alert('Permission denied');
        })

    messaging.onMessage(function(payload){
        //I am expecting to trigger this event when I push the message using the REST client
        alert('Message ' + payload)
    })
</script>
</body>
</html>

I commented out in the code to highlight what I am expecting to get. 我在代码中注释掉以突出显示我期望得到的结果。 I can retrieve the token which I commented in the code. 我可以检索在代码中注释过的令牌。 When I get the token, I push the message from the REST client like this. 当获得令牌时,我像这样从REST客户端推送消息。

My request body is something like this 我的请求正文是这样的

{
    "to" : "dJA57nVCZ7A:APA91bFFaYODxZQ4tbyy6RupRvH-jhmM1xh8F3iBQ1BWwdnvHA-dbB50cY1OyYNLpNhZLIKZm7Aqs4nTnQDsd2sExvNIglAeMSw3VLDXGjgaeqBEYFgz6PqbOJIS0Qki6m9XQ931H1xt",
    "notification" : {
        "body" : "SOMETHING",
        "title" : "SOMETHING"
    },
    "data" : {
      "message" : "This is data message"
    }
}

As you can see I pass the token retrieved previously to the request body. 如您所见,我将先前获取的令牌传递给请求主体。 I also passed server key in the header as well. 我还在标头中传递了服务器密钥。 Post request was successful. 发布请求成功。 I got the following response message. 我收到以下响应消息。

在此处输入图片说明

But on successful request, the event in the Javascript code should be fired. 但是,如果请求成功,则应触发Javascript代码中的事件。

messaging.onMessage(function(payload){
            //I am expecting to trigger this event when I push the message using the REST client
            alert('Message ' + payload)
        })

But, it was not triggered. 但是,它没有被触发。 Actually, it is supposed to be trigged after the successful post request has been made. 实际上,应该在成功发布请求后触发它。 What is wrong with or missing in my code? 我的代码有什么问题或遗漏了什么?

How do you serve your web app? 您如何服务您的Web应用程序? It must be served over http S (Description) , otherwise the ServiceWorker / Messaging won't work. 它必须通过http S (描述)提供 ,否则ServiceWorker /消息系统将无法工作。

Have a look at the Developer Console (Chrome) -> Application -> Service Workers, your SW should appear here. 看一下开发者控制台(Chrome)->应用程序->服务工作者,您的软件应该出现在这里。


Edit: 编辑:

For testing you can also upload your project into firebase hosting. 为了进行测试,您还可以将项目上传到Firebase托管中。 There is a free ssl cert. 有一个免费的SSL证书。 included. 包括在内。 To do so, install the firebase cli (via npm ): 为此,请安装firebase cli(通过npm ):

npm install -g firebase-tools

Then, first run the login command to log into your google account: 然后,首先运行login命令登录到您的Google帐户:

firebase login

and 'init' a new project (like npm init ): 然后“初始化”一个新项目(例如npm init ):

firebase init

Deploying then is as easy as typing 然后部署就像输入一样容易

firebase deploy

Have a look here for more details. 在这里查看更多详细信息。

You no need to have https when testing locally. 在本地测试时,无需使用https。 Just http://localhost :<< port>> works fine. 只是http:// localhost :<< port >>可以正常工作。 If you deploy your site on to a domain(not localhost), then it has to be http s to get firebase service worker working. 如果你到一个域(非本地主机)部署你的网站,那么它必须是http s到获得火力点服务人员的工作。

  1. you will get notification only when the window is minimised/not focused. 仅当窗口最小化/未聚焦时,您才会收到通知。
  2. if window is in focus, directly onmessage event will be fired. 如果窗口处于焦点位置,则将直接触发onmessage事件。
  3. Try below JSON Posts: 请尝试以下JSON帖子:

Below push handled by firebase serviceworker internally(if you use firebase hosting) you don't need to handle it with setBackgroundMessageHandler in your sw. 在以下情况下,firebase服务工作人员在内部处理了推送(如果您使用firebase托管),则无需在sw中使用setBackgroundMessageHandler对其进行处理。

{
  "notification": {
    "title": "Portugal vs. Denmark",
    "body": "5 to 1",
    "icon": "firebase-logo.png"
  },
  "to": "ecce7xlo9CA:APA91bEXPT-NCnl9evVE....",
  "priority": "high"
}

Below will not be handled internally, you need to setBackgroundMessageHandler in your sw. 下面将不会在内部处理,您需要在sw中设置setBackgroundMessageHandler。

{
  "data":{
    "id": 1,
    "missedRequests": 5,
    "addAnyDataHere": 123
  },
  "to": "ecce7xlo9CA:APA91bEXPT-NCnl9evVE....",
  "priority": "high"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM