Skip to content

Instantly share code, notes, and snippets.

@hendricius
Created April 13, 2022 08:06
Show Gist options
  • Save hendricius/df8a35c5eb5572dc87baec0c9ec914a7 to your computer and use it in GitHub Desktop.
Save hendricius/df8a35c5eb5572dc87baec0c9ec914a7 to your computer and use it in GitHub Desktop.
# Small screenshot service that uses headless chrome to take a screenshot
# of your website.
#
class ScreenshotService
def initialize(url, options: {})
@url = url
@options = options
end
attr_reader :url, :options
def self.fetch(url, options: {})
new(url, options: options).fetch
end
def fetch
session = setup_capybara_session
session.visit(url)
resize(session)
target = random_filename
session.save_screenshot(target)
session.quit
target
end
private
def random_filename
"/tmp/#{SecureRandom.hex}.png"
end
def resize(session)
return session if width.blank? || height.blank?
session.current_window.resize_to(width, height)
end
def width
options[:width]
end
def height
options[:height]
end
def setup_capybara_session
Capybara.register_driver :headless_chrome do |app|
client = Selenium::WebDriver::Remote::Http::Default.new
client.read_timeout = 120 # instead of the default 60
options = Selenium::WebDriver::Chrome::Options.new
options.headless!
driver_parameters = {
browser: :chrome,
http_client: client,
capabilities: [options]
}
Capybara::Selenium::Driver.new(app, **driver_parameters)
end
Capybara.default_driver = :headless_chrome
Capybara.javascript_driver = :headless_chrome
Capybara::Session.new(:headless_chrome)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment