Notes on using FCM with Ruby on Rails

Reflect click_action

It seems that you should add the notificationclick event to the ** top ** of firebase-messaging-sw.js.

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);
      }
    })
  );
});

Get web push notifications even on open tabs (working tabs)

When working with normally open tabs, I don't get web push notifications.

You can define the onMessage function in firebase.js as follows.

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
              }
            }
          }
        }
      )
    });
  });

Have ActiveJob handle web pushes

The parameters that can be passed are: title: Notification title body: Notification content icon: Display icon click_action: URL that transitions with a click event (HTTPS only)

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

I'm still not sure if priority:'high' is useful, but ...

Recommended Posts

Notes on using FCM with Ruby on Rails
[Ruby on Rails] View test with RSpec
[Ruby on Rails] Code check using Rubocop-airbnb
[Ruby on Rails] Controller test with RSpec
[Ruby on Rails] Image slideshow using Skippr
[Ruby on Rails] Model test with RSpec
Ruby on Rails Elementary
Ruby on Rails basics
Ruby On Rails Association
Introducing Rspec with Ruby on Rails x Docker
Publish the app made with ruby on rails
Notes on building Rails6 / PostgreSQL with Docker Compose
[Rails] Procedure for linking databases with Ruby On Rails
Determine the current page with Ruby on Rails
[Ruby on Rails] Upload multiple images with refile
I made a portfolio with Ruby On Rails
Ruby on rails learning record -2020.10.03
Portfolio creation Ruby on Rails
Try using view_component with rails
[Ruby on Rails] Delete s3 images with Active Strage
[Ruby on Rails] Debug (binding.pry)
Ruby on rails learning record -2020.10.05
Run Ruby on Rails RSpec tests with GitHub Actions
Ruby on rails learning record -2020.10.09
Ruby on Rails config configuration
Japaneseize using i18n with Rails
Error encountered with notes when deploying docker on rails
Ruby on Rails basic learning ①
[Ruby on Rails] about has_secure_password
Ruby on rails learning record-2020.10.07 ②
[Ruby on Rails] Common processing between controllers (using concaves)
Solve the N + 1 problem with Ruby on Rails: acts-as-taggable-on
Commentary on partial! --Ruby on Rails
Ruby on rails learning record-2020.10.07 ①
Cancel Ruby on Rails migration
Ruby on Rails environment construction using VirtualBox, Vagrant, cyberduck
[Ruby] Notes on gets method
Ruby on rails learning record -2020.10.06
Ruby on Rails Tutorial Troublesome notes when running on Windows
Ruby on Rails validation summary
Created RSS / Atom format sitemap with Ruby on Rails
Ruby on Rails Basic Memorandum
Try using the query attribute of Ruby on Rails
Ruby on Rails Email automatic sending function setting (using gmail)
[Ruby on Rails] Add a column with a foreign key constraint
[Ruby on Rails] Easy scroll animation of javascript (using ScrollReveal.js)
[Ruby on Rails] Implement login function by add_token_to_users with API
[Apple login] Sign in with Apple implementation procedure (Ruby on Rails)
[Ruby on Rails] Infinite scrolling using gem kaminari and jscroll
Install Ruby on MSYS2 with pacman
Ruby on Rails Overview (Beginner Summary)
[Ruby on Rails] Read try (: [],: key)
[Ruby on Rails] yarn install --check-files
Ruby on Rails variable, constant summary
Installing Ruby + Rails on Ubuntu 18.04 (rbenv)
[Ruby on Rails] Introduced paging function
Basic knowledge of Ruby on Rails
Progate Ruby on Rails5 Looking Back
Install Ruby 2.5 on CentOS 7 using SCL
How to use Ruby on Rails
[Ruby on Rails] Add / Remove Columns