Skip to content

Document common use-case examples #9

@andrewvy

Description

@andrewvy

Should benefit by providing some common use-case examples.

These examples are built on unstable version and is not guaranteed to be working in the near future!


Taking a screenshot, quick and dirty, error-prone

defmodule CriExample do
  require Logger

  def init() do
    server = ChromeRemoteInterface.Session.new()
    {:ok, pages} = ChromeRemoteInterface.Session.list_pages(server)
    List.first(pages)
  end

  def take_screenshot(page, url, file_path) do
    start_time = System.monotonic_time()
    {:ok, page_pid} = ChromeRemoteInterface.PageSession.start_link(page)

    ChromeRemoteInterface.PageSession.subscribe(page_pid, "Page.frameStoppedLoading")
    ChromeRemoteInterface.RPC.Page.enable(page_pid)
    ChromeRemoteInterface.RPC.Page.navigate(page_pid, %{url: url})

    receive do
      {:chrome_remote_interface, "Page.frameStoppedLoading", _payload} ->
        {:ok, %{"result" => %{"data" => data}}} = ChromeRemoteInterface.RPC.Page.captureScreenshot(page_pid)
        binary_data = Base.decode64!(data)
        {:ok, file} = File.open(file_path, [:write])
        IO.binwrite(file, binary_data)
        File.close(file)

        stop_time = System.monotonic_time()
        diff = System.convert_time_unit(stop_time - start_time, :native, :micro_seconds)

        Logger.info("url=#{url} file_path=#{file_path} total_time=#{formatted_diff(diff)}")
        ChromeRemoteInterface.PageSession.stop(page_pid)
    after
      10_000 ->
        :error
    end
  end

  defp formatted_diff(diff) when diff > 1000, do: [diff |> div(1000) |> Integer.to_string, "ms"]
  defp formatted_diff(diff), do: [Integer.to_string(diff), "µs"]
end
CriExample.init()
|> CriExample.take_screenshot("https://google.com", "test.png")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions