Skip to content

Instantly share code, notes, and snippets.

@opsb
Last active March 11, 2017 17:04
Show Gist options
  • Select an option

  • Save opsb/d276c392e870849571e267f945af9fa2 to your computer and use it in GitHub Desktop.

Select an option

Save opsb/d276c392e870849571e267f945af9fa2 to your computer and use it in GitHub Desktop.
set_text_helper
defmodule Helpers.Actions do
def set_text(parent, %Query{} = query, text) when is_binary(text) do
parent |> find(query)
case Query.compile(query) do
{:css, selector} ->
parent
|> pipeline_script("document.querySelector('#{selector}').value = '#{text}'")
|> pipeline_script("document.querySelector('#{selector}').dispatchEvent(new Event('input'))")
{:xpath, xpath} ->
parent |> pipeline_script(build_set_text_script(xpath, text))
end
wait_for(parent, %{ query | conditions: [text: text, visible: true] })
end
defp build_set_text_script(xpath, text) do
"""
var xpath = "#{escape_string xpath}";
var xpathResult = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null);
var element = xpathResult.iterateNext();
if (!element) {
throw new Error("No element found for xpath: " + xpath);
}
element.value = '#{escape_string text}';
element.dispatchEvent(new Event('input'));
"""
end
defp escape_string(string) do
string
|> String.replace("\"", "\\\"")
|> String.replace("'", "\\'")
end
def wait_for(session, %Query{} = query) do
session |> find(query)
session
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment