ndrean
December 26, 2024, 9:46am
1
Is it possible to add a transport fallback to the LiveSocket? I wanted to evaluate a simple HTTP GET request to the params URL, no other state needed. The idea is to see if I can proxy this with a Service Worker. It makes sense in my case because all the dynamic parts are generated with a frontend framework.
Yes, there’s a built in long polling fallback that doesn’t depend on WebSockets: Phoenix.Socket — Phoenix v1.7.18
LiveSocket builds on top of Phoenix.Socket.
The project template when you create a Phoenix app with mix phx.new
includes the fallback by default in recent versions:
<%= if @html do %>
// Include phoenix_html to handle method=PUT/DELETE in forms and buttons.
import "phoenix_html"
// Establish Phoenix Socket and LiveView configuration.
<%= @live_comment %>import {Socket} from "<%= @phoenix_js_path %>"
<%= @live_comment %>import {LiveSocket} from "phoenix_live_view"
<%= @live_comment %>import topbar from "../vendor/topbar"
<%= @live_comment %>const csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
<%= @live_comment %>const liveSocket = new LiveSocket("/live", Socket, {
<%= @live_comment %> longPollFallbackMs: 2500,
<%= @live_comment %> params: {_csrf_token: csrfToken}
<%= @live_comment %>})
// Show progress bar on live navigation and form submits
<%= @live_comment %>topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"})
<%= @live_comment %>window.addEventListener("phx:page-loading-start", _info => topbar.show(300))
<%= @live_comment %>window.addEventListener("phx:page-loading-stop", _info => topbar.hide())
// connect if there are any LiveViews on the page
<%= @live_comment %>liveSocket.connect()
ndrean
December 26, 2024, 1:33pm
4
Thanks, good indeed, long poll goes through HTTP. I will check what does the url look like and see. Merry Xmas.