【问题标题】:Firebase web push notification, on click not workingFirebase 网络推送通知,点击无效
【发布时间】:2019-10-03 01:37:59
【问题描述】:

从我试图完成它的几天开始,但我完全被困在这一点上。

这是我的 service worker 文件中的代码

importScripts('https://www.gstatic.com/firebasejs/6.0.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/6.0.2/firebase-messaging.js');

firebase.initializeApp({
    messagingSenderId: "xxxxxxxxxxxx"
});

var messaging = firebase.messaging();


messaging.setBackgroundMessageHandler(function(payload) {

    console.log('[firebase-messaging-sw.js] Received background message ', payload);
    // Customize notification here
    var notificationTitle = payload.data.title; //or payload.notification or whatever your payload is
    var notificationOptions = {
      body: payload.data.body,
      icon: payload.data.icon,
      image: payload.data.image,

      data: { url:payload.data.openURL }, //the url which we gonna use later
      actions: [{action: "open_url", title: "View"}]
    };

    return event.waitUntil(self.registration.showNotification(notificationTitle,
      notificationOptions));
});

 self.addEventListener('notificationclick', function(event) {


    console.log('event = ',event);
    event.notification.close();
    event.waitUntil(clients.openWindow(event.notification.data.url));

    switch(event.action){
      case 'open_url':
        window.open(event.notification.data.url);
      break;
      case 'any_other_action':
        window.open(event.notification.data.url);
      break;
    }


}, false);

数据就是这种格式

$data=[
        'title' => 'message title',
        'body' => 'description body',
        'icon' => 'https://i.ytimg.com/vi/gXSyP9ga-ag/hqdefault.jpg',
        'image'=>'https://i.ytimg.com/vi/gXSyP9ga-ag/mqdefault.jpg',
        'openURL'=>'https://google.com'
      ];

现在有很多问题。

  • 在手机上点击推送通知正文时,不会打开url,只会关闭它(只有点击动作按钮会打开链接

  • 我在网上看了一些,发现

    event.waitUntil(clients.openWindow(event.notification.data.url));
    

    不适用于 safari 和 safari iPhone,谁能帮我找到 了解如何实现一个可以与苹果一起使用的点击甚至监听器 设备?

任何帮助将不胜感激

【问题讨论】:

    标签: javascript firebase push-notification firebase-cloud-messaging service-worker


    【解决方案1】:

    在搜索了许多解决方案后,我找到了自己。这是完整的工作示例:

    // firebase-messaging-sw.js (client side)
    
    importScripts('https://www.gstatic.com/firebasejs/8.1.2/firebase-app.js');
    importScripts('https://www.gstatic.com/firebasejs/8.1.2/firebase-messaging.js');
    
    self.addEventListener('notificationclick', function (event) {
      console.debug('SW notification click event', event)
      const url = '<get your url from event>'
      event.waitUntil(
        clients.matchAll({type: 'window'}).then( windowClients => {
            // Check if there is already a window/tab open with the target URL
            for (var i = 0; i < windowClients.length; i++) {
                var client = windowClients[i];
                // If so, just focus it.
                if (client.url === url && 'focus' in client) {
                    return client.focus();
                }
            }
            // If not, then open the target URL in a new window/tab.
            if (clients.openWindow) {
                return clients.openWindow(url);
            }
        })
    );
    })
    
    firebase.initializeApp({
      apiKey: "",
      authDomain: "",
      projectId: "",
      storageBucket: "",
      messagingSenderId: "",
      appId: "",
      measurementId: "",
    })
    
    const messaging = firebase.messaging();
    
    messaging.onBackgroundMessage(function(payload) {
      console.log('[firebase-messaging-sw.js] Received background message ', payload);
    })
    

    NodeJS 端的代码如下:

    var admin = require("firebase-admin");
    // This is a specific account key file generated through the firebase UI
    var serviceAccount = require("./serviceAccountKey.json");
    
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
    });
    const payload = {
      "token": "FCM TOKEN HERE",
      "notification": {
        "title":"James",
        body: '14100000'
      },
      "webpush": {
        "fcm_options": {
            "link": "https://google.com"
        },
      },
    };
    admin.messaging().send(payload).then(res => {
      console.log('SUCCESS ', res);
    }).catch(err => {
      console.log(err);
    }).finally(() => {
      process.exit(0);
    });
    

    问题是如果我将notificationclick 放在底部,它不会触发,真的不知道为什么,然后我将它移到顶部并且它可以工作。我可以从服务器发送推送通知(使用firebase-admin),推送通知将显示(当应用程序在后台时),点击通知打开我想要的链接。

    【讨论】:

    • 嗨@Duc Trung Mai,您能否编辑您的回复并包括您在服务器中用于发送通知的代码?
    • @zeljazouli,我更新了我的答案,请检查
    【解决方案2】:

    您正在使用数据消息,但您需要使用通知消息。 见:https://firebase.google.com/docs/cloud-messaging/js/receive

    由于数据消息不支持 fcm_options.link,因此建议您为所有数据消息添加通知负载。或者,您可以使用 service worker 处理通知。

    有关通知和数据消息之间区别的说明,请参阅消息类型。

    这是工作通知的 JSON 负载。 click_action 用于处理点击。

    {
      "data": {
        "badge": "23",
        "b": "xxxx",
        "t": "yyyy",
        "android_channel_id": "com.example.fcm"
      },
      "from": "11111111111",
      "notification": {
        "title": "Title",
        "body": "Body",
        "icon": "https://example.com/icon.png",
        "click_action": "https://example.com"
      },
      "collapse_key": "do_not_collapse"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 2019-05-13
      相关资源
      最近更新 更多