Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 Actioncable global message without channels

How can I send with javascript a global message to all of our subscribed websocket connections without the need of a channel etc. (like the ping message that the actioncable is sending by default globally to all open connections)?

like image 984
JohnDel Avatar asked Nov 07 '22 12:11

JohnDel


1 Answers

As far as I know, you cannot do it directly from JavaScript without channels (it needs to go over Redis first).

I would suggest you do that as a normal post action, and then send the message in Rails.

I would do something like this:

JavaScript:

$.ajax({type: "POST", url: "/notifications", data: {notification: {message: "Hello world"}}})

Controller:

class NotificationsController < ApplicationController
  def create
    ActionCable.server.broadcast(
      "notifications_channel",
      message: params[:notification][:message]
    )
  end
end

Channel:

class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_from("notifications_channel", coder: ActiveSupport::JSON) do |data|
      # data => {message: "Hello world"}
      transmit data
    end
  end
end

Listen JavaScript:

App.cable.subscriptions.create(
  {channel: "NotificationsChannel"},
  {
    received: function(json) {
      console.log("Received notification: " + JSON.stringify(json))
    }
  }
)
like image 157
kaspernj Avatar answered Nov 15 '22 14:11

kaspernj