Playwright.pm 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. package Playwright;
  2. use strict;
  3. use warnings;
  4. use sigtrap qw/die normal-signals/;
  5. use File::Basename();
  6. use Cwd();
  7. use URI::Query();
  8. use Net::EmptyPort();
  9. use LWP::UserAgent();
  10. use Sub::Install();
  11. use JSON::MaybeXS();
  12. use File::Slurper();
  13. use Carp qw{confess};
  14. use Playwright::Page();
  15. #ABSTRACT: Perl client for Playwright
  16. no warnings 'experimental';
  17. use feature qw{signatures state};
  18. =head2 SYNOPSIS
  19. use Playwright;
  20. my ($browser,$page) = Playwright->new( browser => "chrome" );
  21. $page->goto('http://www.google.com');
  22. my $browser_version = $browser->version();
  23. $browser->quit();
  24. =head2 DESCRIPTION
  25. Perl interface to a lightweight node.js webserver that proxies commands runnable by Playwright.
  26. Currently understands commands you can send to the following Playwright classes,
  27. commands for which can be sent via instances of the noted module
  28. =over 4
  29. =item B<Browser> - L<Playwright> L<https://playwright.dev/#version=master&path=docs%2Fapi.md&q=class-browser>
  30. =item B<BrowserContext> - L<Playwright> L<https://playwright.dev/#version=master&path=docs%2Fapi.md&q=class-browsercontext>
  31. =item B<Page> - L<Playwright::Page> L<https://playwright.dev/#version=v1.5.1&path=docs%2Fapi.md&q=class-page>
  32. =item B<Result> - L<Playwright::Result> L<https://playwright.dev/#version=v1.5.1&path=docs%2Fapi.md&q=class-response>
  33. =back
  34. The specification for the above classes can also be inspected with the 'spec' method for each respective class:
  35. use Data::Dumper;
  36. print Dumper($browser->spec , $page->spec, ...);
  37. =head1 CONSTRUCTOR
  38. =head2 new(HASH) = (Playwright,Playwright::Page)
  39. Creates a new browser and returns a handle to interact with it, along with a new page Handle to interact with therein.
  40. =head3 INPUT
  41. browser (STRING) : Name of the browser to use. One of (chrome, firefox, webkit).
  42. visible (BOOL) : Whether to start the browser such that it displays on your desktop (headless or not).
  43. debug (BOOL) : Print extra messages from the Playwright server process
  44. =cut
  45. our ($spec, $server_bin, %class_spec);
  46. my %transmogrify = (
  47. Page => sub {
  48. my ($self, $res) = @_;
  49. require Playwright::Page;
  50. return Playwright::Page->new( browser => $self, page => $res->{_guid} );
  51. },
  52. Result => sub {
  53. my ($self, $res) = @_;
  54. require Playwright::Response;
  55. return Playwright::Response->new( browser => $self, id => $res->{_guid} );
  56. },
  57. );
  58. BEGIN {
  59. my $path2here = File::Basename::dirname(Cwd::abs_path($INC{'Playwright.pm'}));
  60. my $specfile = "$path2here/../api.json";
  61. confess("Can't locate Playwright specification in '$specfile'!") unless -f $specfile;
  62. my $spec_raw = File::Slurper::read_text($specfile);
  63. my $decoder = JSON::MaybeXS->new();
  64. $spec = $decoder->decode($spec_raw);
  65. %class_spec = (
  66. %{$spec->{Browser}{members}},
  67. %{$spec->{BrowserContext}{members}}
  68. );
  69. # Install the subroutines if they aren't already
  70. foreach my $method (keys(%class_spec)) {
  71. Sub::Install::install_sub({
  72. code => sub { _request(shift, \%transmogrify, args => [@_], command => $method ) },
  73. as => $method,
  74. });
  75. }
  76. # Make sure it's possible to start the server
  77. $server_bin = "$path2here/../bin/playwright.js";
  78. confess("Can't locate Playwright server in '$server_bin'!") unless -f $specfile;
  79. 1;
  80. }
  81. sub new ($class, %options) {
  82. #XXX yes, this is a race, so we need retries in _start_server
  83. my $port = Net::EmptyPort::empty_port();
  84. my $self = bless({
  85. spec => $spec,
  86. ua => $options{ua} // LWP::UserAgent->new(),
  87. browser => $options{browser},
  88. visible => $options{visible},
  89. port => $port,
  90. debug => $options{debug},
  91. pid => _start_server($options{browser},$options{visible}, $port, $options{debug}),
  92. }, $class);
  93. my $res = $self->_request( \%transmogrify, url => 'session' );
  94. use Data::Dumper;
  95. print Dumper($res);
  96. confess("Could not create new session") if $res->{error};
  97. return ($self, Playwright::Page->new( browser => $self, page => 'default' ));
  98. }
  99. =head1 METHODS
  100. =head2 spec
  101. Return the relevant methods and their definitions for this module which are built dynamically from the Playwright API spec.
  102. =cut
  103. sub spec ($self) {
  104. return %class_spec;
  105. }
  106. =head2 quit, DESTROY
  107. Terminate the browser session and wait for the Playwright server to terminate.
  108. Automatically called when the Playwright object goes out of scope.
  109. =cut
  110. sub quit ($self) {
  111. $self->_request( \%transmogrify, url => 'shutdown' );
  112. return waitpid($self->{pid},0);
  113. }
  114. sub DESTROY ($self) {
  115. $self->quit();
  116. }
  117. sub _start_server($browser,$visible, $port, $debug) {
  118. confess("Invalid browser '$browser'") unless grep { $_ eq $browser } qw{chrome firefox webkit};
  119. $visible = $visible ? '-v' : '';
  120. $debug = $debug ? '-d' : '';
  121. $ENV{DEBUG} = 'pw:api';
  122. my $pid = fork // confess("Could not fork");
  123. if ($pid) {
  124. print "Waiting for port to come up..." if $debug;
  125. Net::EmptyPort::wait_port($port,30) or confess("Server never came up after 30s!");
  126. print "done\n" if $debug;
  127. return $pid;
  128. }
  129. exec( $server_bin, $browser, $visible, "-p", $port, $debug);
  130. }
  131. sub _request ($self, $translator, %args) {
  132. $translator //= \%transmogrify;
  133. my $qq = URI::Query->new(%args);
  134. my $url = $args{url} // 'command';
  135. my $fullurl = "http://localhost:$self->{port}/$url?$qq";
  136. my $request = HTTP::Request->new( 'GET', $fullurl );#, $header, $content );
  137. my $response = $self->{ua}->request($request);
  138. my $decoded = JSON::MaybeXS::decode_json($response->decoded_content());
  139. return $translator->{$decoded->{_type}}->($self,$decoded) if $decoded->{_type} && exists $translator->{$decoded->{_type}};
  140. return $decoded;
  141. }
  142. 1;