1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-11-10

click_actionを反映させる

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

public/firebase-messaging-sw.js
// 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ファンクションを以下のように定義すればいいです。

firebase.js
  // 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のみ)

app/jobs/push_notification_job.rb
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' は役立つかどうかまだ分からないですが、、、。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?