1

I have a Phoenix (1.4) LiveView (0.8) application, and I'd like to have the browser window open automatically upon starting the server. Does anyone know if this can be done, and if so how?

I tried seeing if I could configure the option in Webpack like I've done for FE applications, but I wasn't able to get that to work.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
ernbrn
  • 387
  • 3
  • 6

1 Answers1

1

The clearest way would be to go with a custom mix task, the only question is how do you actually open the browser. This was already implemented in docs:

defp browser_open(path) do
    start_browser_command =
      case :os.type do
        {:win32, _} ->
          "start"
        {:unix, :darwin} ->
          "open"
        {:unix, _} ->
          "xdg-open"
      end

    if System.find_executable(start_browser_command) do
      System.cmd(start_browser_command, [path])
    else
      Mix.raise "Command not found: #{start_browser_command}"
    end
  end

All what is left now is to make a custom task, take the host and port from config and call the phx.server task inside of it and open browser:

defmodule Mix.Tasks.Hello do
  use Mix.Task

  def run(_) do
    Mix.Task.run("phx.server")
    env = Application.fetch_env!(:phoenix_test, PhoenixTestWeb.Endpoint)
    browser_open("http://#{env[:url][:host]}:#{env[:http][:port]}")
  end
end

Then you can call the task with mix hello.

Daniel
  • 2,320
  • 1
  • 14
  • 27