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.js
にonMessage
ファンクションを以下のように定義すればいいです。
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'
は役立つかどうかまだ分からないですが、、、。