LiveView Dynamic Favicon?

@BartOtten thanks for the info and links. Here’s the solution I used…

First, have a collection of favicon images that follow a regular file naming convention.

/priv/images/favicon-black.ico
/priv/images/favicon-blue.ico
/priv/images/favicon-red.ico
/priv/images/favicon-green.ico

In layouts/root_live.html.heex, put a favicon tag in your head section.

<link id="favicon" rel="icon" type="image/x-icon" href="/images/favicon-black.ico"/>

Add an event listener in app.js

window.addEventListener("phx:newfav", (e) => {
  var color = e.detail.color 
  var fabtag = document.getElementById('favicon') 
  fabtag.href = `/images/favicon-${color}.ico`
}) 

Then add an event handler to mypage_live.ex

def handle_info({"newfav", newcolor}, socket) do 
  {:noreply, push_event(socket, "newfav", %{color: newcolor})}
end

When it’s time to update the favicon, send a message to your LiveView:

send(self(), {"newfav", "blue"})

Dynamic favicons are super handy for notices and status indicators!

An automagic live_favicon_tag function would be ideal, but this approach seems workable.

1 Like