Class: HeadlessBrowserTool::Tools::FindElementsContainingTextTool

Inherits:
BaseTool
  • Object
show all
Defined in:
lib/headless_browser_tool/tools/find_elements_containing_text_tool.rb

Instance Method Summary collapse

Instance Method Details

#execute(text:, exact_match: false, case_sensitive: false, visible_only: true) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/headless_browser_tool/tools/find_elements_containing_text_tool.rb', line 18

def execute(text:, exact_match: false, case_sensitive: false, visible_only: true)
  script = build_search_script(text, exact_match, case_sensitive, visible_only)
  elements_data = browser.execute_script(script)

  # Ensure we have an array to work with
  elements_data = [] if elements_data.nil?
  elements_data = [elements_data] unless elements_data.is_a?(Array)

  # Process and enrich the results
  results = elements_data.map do |element|
    # Skip if element is not a hash
    next unless element.is_a?(Hash)

    # Safely extract values with defaults
    {
      tag: element["tag"] || "unknown",
      text: (element["text"] || "").to_s,
      selector: element["selector"] || "",
      xpath: element["xpath"] || "",
      attributes: element["attributes"] || {},
      parent: element["parent"] || nil,
      clickable: element["clickable"] == true,
      visible: element["visible"] == true,
      position: element["position"] || {}
    }
  end.compact

  {
    query: text,
    total_found: results.size,
    elements: results
  }
end