Rails 5 Actioncable Channel-Free Global Message

How can I send a global message with javascript to all our web subscriptions without the need for a channel, etc. (for example, the ping message that actioncable sends by default in all open connections by default)?

+5
source share
1 answer

As far as I know, you cannot do this directly with JavaScript without channels (Redis needs to be translated first).

I suggest you do it like a regular post action, and then send a message to 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 

A source:

 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 to JavaScript:

 App.cable.subscriptions.create( {channel: "NotificationsChannel"}, { received: function(json) { console.log("Received notification: " + JSON.stringify(json)) } } ) 
0
source

Source: https://habr.com/ru/post/1274621/


All Articles