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)?
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))
}
}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With