Class: HeadlessBrowserTool::Tools::ScreenshotTool

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

Instance Method Summary collapse

Instance Method Details

#execute(filename: nil, highlight_selectors: [], annotate: false, full_page: false) ⇒ Object



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
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/headless_browser_tool/tools/screenshot_tool.rb', line 19

def execute(filename: nil, highlight_selectors: [], annotate: false, full_page: false)
  screenshots_dir = "./.hbt/screenshots"
  timestamp = Time.now.strftime("%Y%m%d_%H%M%S_%L")

  # Generate filename with timestamp
  if filename
    # Remove .png extension if present to add timestamp before it
    base_name = filename.sub(/\.png$/i, "")
    filename = "#{base_name}_#{timestamp}.png"
  else
    filename = "screenshot_#{timestamp}.png"
  end

  file_path = File.join(screenshots_dir, filename)

  # Inject JavaScript to highlight elements
  inject_highlight_script(highlight_selectors, annotate) if highlight_selectors.any? || annotate

  # Take screenshot
  if full_page
    take_full_page_screenshot(file_path)
  else
    browser.save_screenshot(file_path)
  end

  # Remove highlights
  browser.execute_script("document.querySelectorAll('.ai-highlight').forEach(el => el.remove());")

  # Get file info
  file_size = File.size(file_path)

  {
    file_path: file_path,
    filename: filename,
    file_size: file_size,
    file_size_human: "#{(file_size / 1024.0).round(2)} KB",
    timestamp: timestamp,
    full_page: full_page,
    highlighted_elements: highlight_selectors.size,
    annotated: annotate,
    url: browser.current_url,
    title: browser.title
  }
end