How to alert client that LiveSocket is Disconnect

I am wanting to implement an alert message for the user, when his internet connection is lost. Is this possible with LiveView?

It can’t conceptually…

Once the server knows that the client is offline, it can’t tell the client anymore, as it is offline…

You need to use client side JavaScript, though you can not properly detect whether or not you are offline using it. You might be able to detect if you still can reach the server, or if the browser still has a network. But there are so many different components on the way, that one can still be connected to the internet, without beeing able to connect to your server, while one could even connect to your server while the rest of the internet appears to be dead. Also the browser might have network but not internet connection because some router inbetween still serves as a switch for the local network, while connection to the ISP is broken.


think (or know) you can use the phx:page-loading-start js event -

app.js (or whatever you’re loading in)

window.addEventListener("phx:page-loading-start", (info) => {
  if (info.detail && info.detail.kind && info.detail.kind === "error") {
    alert("my error message for disconnected");

but maybe test how it exactly behaves.

edit: (of course don’t use an alert, but add/remove css class to something etc)

1 Like