Push Notifications with ActionCable

Episode #205 by David Kimura

Summary

In this episode, we look into using Push Notifications within our Rails application and then using ActionCable to broadcast Push Notifications to the user.
rails websockets notifications actioncable 8:55

Resources

Summary

# Terminal
rails g channel notification

# app/javascript/packs/application.js
Notification.requestPermission().then(function (result) {})

# views/welcome/index.html.erb
<%= link_to 'Send Notification', welcome_index_path, remote: true %>

# views/welcome/index.js.erb
if (Notification.permission === 'granted') {
  var title = 'Push Notification'
  var body = 'Triggered by link on the <%= Rails.env %> environment.'
  var options = { body: body }
  new Notification(title, options)
}

# welcome_controller.rb
def index
  ActionCable.server.broadcast('notification_channel', 'You have visited the welcome page.')
end

# app/channels/notification_channel.rb
def subscribed
  stream_from "notification_channel"
end

# app/javascript/channels/notification_channel.js
import consumer from "./consumer"

consumer.subscriptions.create("NotificationChannel", {
  connected() {},
  disconnected() {},
  received(data) {
    if (Notification.permission === 'granted') {
      var title = 'Push Notification'
      var body = data
      var options = { body: body }
      new Notification(title, options)
    }
  }
});