1
0

Chrome.pm 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package Selenium::Chrome;
  2. # ABSTRACT: A convenience package for creating a Chrome instance
  3. use Selenium::Binary qw/start_binary_on_port/;
  4. use Moo;
  5. use namespace::clean;
  6. extends 'Selenium::Remote::Driver';
  7. =head1 SYNOPSIS
  8. my $driver = Selenium::Chrome->new;
  9. =head1 DESCRIPTION
  10. This class allows you to use the ChromeDriver without needing the JRE
  11. or a selenium server running. If you refrain from passing the
  12. C<remote_server_addr> and C<port> arguments, we will search for the
  13. chromedriver executable binary in your $PATH. We'll try to start the
  14. binary connect to it, shutting it down at the end of the test.
  15. If the chromedriver binary is not found, we'll fall back to the
  16. default L<Selenium::Remote::Driver> behavior of assuming defaults of
  17. 127.0.0.1:4444.
  18. If you specify a remote server address, or a port, we'll assume you
  19. know what you're doing and take no additional behavior.
  20. If you're curious whether your Selenium::Chrome instance is using a
  21. separate ChromeDriver binary, or through the selenium server, you can
  22. check the C<binary_mode> attr after instantiation.
  23. =cut
  24. use constant CHROMEDRIVER_PORT => 9515;
  25. has '+browser_name' => (
  26. is => 'ro',
  27. default => sub { 'chrome' }
  28. );
  29. # By shadowing the parent's port function, we can set the port in
  30. # _build_binary_mode's builder
  31. has '+port' => (
  32. is => 'lazy'
  33. );
  34. has 'binary_mode' => (
  35. is => 'ro',
  36. init_arg => undef,
  37. builder => 1
  38. );
  39. sub _build_binary_mode {
  40. my ($self) = @_;
  41. if (! $self->has_remote_server_addr && ! $self->has_port) {
  42. try {
  43. my $port = start_binary_on_port('chromedriver', CHROMEDRIVER_PORT);
  44. $self->port($port);
  45. return 1;
  46. }
  47. catch {
  48. warn $_;
  49. return 0;
  50. }
  51. }
  52. else {
  53. return 0;
  54. }
  55. }
  56. sub DEMOLISH {
  57. my ($self) = @_;
  58. if ($self->binary_mode) {
  59. my $port = $self->port;
  60. my $ua = LWP::UserAgent->new;
  61. $ua->get('127.0.0.1:' . $port . '/wd/hub/shutdown');
  62. }
  63. }
  64. 1;