Reputation: 1216
I've recently deployed a Rails app, and have heard back from a few users that it doesn't work in their work environments. It's clear that Websockets are blocked for them.
I've hunted through the Rails documentation on this but can't find any information on how to go about detecting if this has happened. My best guess would be to send an AJAX request out for an ActionCable broadcast, and when that broadcast is not received after a certain timeout, to conclude that Websockets must be blocked.
Are there any easy answers here, perhaps already part of the Rails API, to determine Websocket connectivity?
Upvotes: 4
Views: 2453
Reputation: 1542
I have a workaround that isn't great, but is better than anything else I've seen. Rails provides no interface, but you can get down to the native WebSocket and handle the error.
consumer.subscriptions.create("ChatChannel", { ... });
consumer.connection.webSocket.onerror = function () {
console.log('Websocket connection error!');
// Error handling goes here. Fallback to polling, perhaps.
};
ActionCable will keep trying to reconnect, and this only grabs the first failure, but that's enough to cover many cases.
Upvotes: 1
Reputation: 5521
Whenever an action cable connection fails it writes to the browser console failed: WebSocket is closed before the connection is established
You can leverage this to know if there was a connection error:
def action_cable_connection_errored?
page.driver.browser.manage.logs.get(:browser)
.map(&:message)
.join
.match('failed: WebSocket is closed before the connection is established')
end
Upvotes: 0
Reputation: 7505
There is a rejected
handler you can use. This should fire when the subscription is rejected by the server.
The below coffeescript example is from the official rails docs.
App.cable.subscriptions.create "AppearanceChannel",
# Called when the subscription is ready for use on the server.
connected: ->
// Do something
# Called when the subscription is rejected by the server.
rejected: ->
// Do something
Upvotes: 0