Skip to content

Switching browser tabs / windows / frames #162

Description

@michallepicki

Hello!

When opening a link in the new tab, when running a not headless Chrome browser I can see that it is automatically brought to front. But the connection page_id / frame_id that phoenix_test uses for commands is still the old tab.

It would be great to have possibility to list open windows / pages / frames and be able to switch between them.

For now, as a workaround we came up with this helper:

  def click_and_focus_new_tab(%Playwright{} = conn, text) when is_binary(text) do
    run_click_and_focus_new_tab(conn, fn conn -> click_link(conn, text) end)
  end

  def click_and_focus_new_tab(%Playwright{} = conn, selector, text)
      when is_binary(selector) and is_binary(text) do
    run_click_and_focus_new_tab(conn, fn conn -> click_link(conn, selector, text) end)
  end

  defp run_click_and_focus_new_tab(%Playwright{} = conn, click_fun)
       when is_function(click_fun, 1) do
    timeout_ms = 5_000
    PlaywrightEx.subscribe(conn.context_id)

    try do
      conn = click_fun.(conn)
      {page_id, frame_id} = wait_for_new_page(conn.context_id, conn.page_id, timeout_ms)
      %{conn | page_id: page_id, frame_id: frame_id}
    after
      PlaywrightEx.unsubscribe(conn.context_id)
    end
  end

  defp wait_for_new_page(context_id, current_page_id, timeout_ms) do
    receive do
      {:playwright_msg,
       %{
         guid: ^context_id,
         method: :__create__,
         params: %{
           type: "Page",
           guid: page_id,
           initializer: %{main_frame: %{guid: frame_id}}
         }
       }}
      when page_id != current_page_id ->
        {page_id, frame_id}
    after
      timeout_ms ->
        raise "Timed out waiting for newly opened page in context #{inspect(context_id)}"
    end
  end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions