Cuộc sống Nhật Bản
Yuto Blog

Ruby on Rails でFCMを使う時のメモ

Nội dung chính

click_actionを反映させる

firebase-messaging-sw.jsトップnotificationclickイベントを追加すればいいらしいです。

Copy public/firebase-messaging-sw.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Notification click
self.addEventListener('notificationclick', function(event) {
  let url = event.notification.data.FCM_MSG.data.url;

  event.notification.close(); // Android needs explicit close.
  event.waitUntil(
    clients.matchAll({ includeUncontrolled: true, type: 'window' }).then( windowClients => {
      // Check if there is already a window/tab open with the target URL
      for (let i = 0; i < windowClients.length; i++) {
        let 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.jsonMessageファンクションを以下のように定義すればいいです。

Copy firebase.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  // Handle incoming messages while focusing
  messaging.onMessage(function(payload) {
    const { title, body, icon } = payload.notification
    const url = payload.data.url
    navigator.serviceWorker.getRegistration('/firebase-cloud-messaging-push-scope').then(registration => {
      registration.showNotification(
        title,
        {
          body,
          icon,
          data: {
            FCM_MSG: {
              data: {
                url
              }
            }
          }
        }
      )
    });
  });

ActiveJobでウエブプッシュを処理させる

渡せるパラメータは:
title: 通知タイトル
body: 通知内容
icon: 表示のアイコン
click_action: クリックイベントで遷移するURL(HTTPSのみ)

Copy app/jobs/push_notification_job.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class PushNotificationJob < ApplicationJob
  queue_as :default

  DEFAULT_ICON = 'https://hogehoge.ico'

  def perform(token, options = {})
    fcm = FCM.new(ENV['FIREBASE_SERVER_KEY'])

    options = {
      priority: 'high',
      notification: {
        title: options[:title],
        body: options[:body],
        icon: options[:icon] || DEFAULT_ICON,
      },
      data: {
        url: options[:url] || '/'
      }
    }

    registration_ids = [token]

    fcm.send(registration_ids, options) if registration_ids.any?
  end
end

priority: 'high' は役立つかどうかまだ分からないですが、、、。

Updated at 2023-05-09
Nếu bài viết có ích thì các bạn hãy chia sẻ nhé
Rate this article: 5/5 (38 ratings)
You didn't rate yet
Le Minh Thien Toan

Tác giả:Yuto Yasunaga

Xin chào các bạn. Mình là kỹ sư IT đang làm việc ở Nhật Bản. Mình tạo blog này để chia sẻ về cuộc sống và những kinh nghiệm trong quá trình học tập và làm việc.
Hy vọng bài viết này sẽ có ích cho bạn.