Playwright.pm 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 LWP::UserAgent();
  8. use Sub::Install();
  9. use Net::EmptyPort();
  10. use JSON::MaybeXS();
  11. use File::Slurper();
  12. use Carp qw{confess};
  13. use Playwright::Base();
  14. use Playwright::Util();
  15. #ABSTRACT: Perl client for Playwright
  16. no warnings 'experimental';
  17. use feature qw{signatures state};
  18. =head1 SYNOPSIS
  19. use JSON::PP;
  20. use Playwright;
  21. my $handle = Playwright->new();
  22. my $browser = $handle->launch( headless => JSON::PP::false, type => 'chrome' );
  23. my $page = $browser->newPage();
  24. my $res = $page->goto('http://google.com', { waitUntil => 'networkidle' });
  25. my $frameset = $page->mainFrame();
  26. my $kidframes = $frameset->childFrames();
  27. =head1 DESCRIPTION
  28. Perl interface to a lightweight node.js webserver that proxies commands runnable by Playwright.
  29. Currently understands commands you can send to all the playwright classes defined in api.json.
  30. See L<https://playwright.dev/#version=master&path=docs%2Fapi.md&q=>
  31. for what the classes do, and their usage.
  32. There are two major exceptions in how things work versus the documentation.
  33. =head2 Selectors
  34. The selector functions have to be renamed from starting with $ for obvious reasons.
  35. The renamed functions are as follows:
  36. =over 4
  37. =item $ => select
  38. =item $$ => selectMulti
  39. =item $eval => eval
  40. =item $$eval => evalMulti
  41. =back
  42. These functions are present as part of the Page, Frame and ElementHandle classes.
  43. =head2 Scripts
  44. The evaluate() and evaluateHandle() functions can only be run in string mode.
  45. To maximize the usefulness of these, I have wrapped the string passed with the following function:
  46. const fun = new Function (toEval);
  47. args = [
  48. fun,
  49. ...args
  50. ];
  51. As such you can effectively treat the script string as a function body.
  52. The same restriction on only being able to pass one arg remains from the upstream:
  53. L<https://playwright.dev/#version=master&path=docs%2Fapi.md&q=pageevaluatepagefunction-arg>
  54. You will have to refer to the arguments array as described here:
  55. L<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments>
  56. =head2 Asynchronous operations
  57. The waitFor* methods defined on various classes will return an instance of L<AsyncData>, a part of the L<Async> module.
  58. You will then need to wait on the result of the backgrounded action with the await() method documented below.
  59. # Assuming $handle is a Playwright object
  60. my $async = $page->waitForEvent('console');
  61. $page->evaluate('console.log("whee")');
  62. my $result = $handle->await( $async );
  63. my $logged = $result->text();
  64. =head1 CONSTRUCTOR
  65. =head2 new(HASH) = (Playwright)
  66. Creates a new browser and returns a handle to interact with it.
  67. =head3 INPUT
  68. debug (BOOL) : Print extra messages from the Playwright server process
  69. =cut
  70. our ($spec, $server_bin, %mapper, %methods_to_rename);
  71. BEGIN {
  72. my $path2here = File::Basename::dirname(Cwd::abs_path($INC{'Playwright.pm'}));
  73. my $specfile = "$path2here/../api.json";
  74. confess("Can't locate Playwright specification in '$specfile'!") unless -f $specfile;
  75. my $spec_raw = File::Slurper::read_text($specfile);
  76. my $decoder = JSON::MaybeXS->new();
  77. $spec = $decoder->decode($spec_raw);
  78. $mapper{mouse} = sub { my ($self, $res) = @_; return Playwright::Mouse->new( handle => $self, id => $res->{_guid}, type => 'Mouse' ) };
  79. $mapper{keyboard} = sub { my ($self, $res) = @_; return Playwright::Keyboard->new( handle => $self, id => $res->{_guid}, type => 'Keyboard' ) };
  80. %methods_to_rename = (
  81. '$' => 'select',
  82. '$$' => 'selectMulti',
  83. '$eval' => 'eval',
  84. '$$eval' => 'evalMulti',
  85. );
  86. foreach my $class (keys(%$spec)) {
  87. $mapper{$class} = sub {
  88. my ($self, $res) = @_;
  89. my $class = "Playwright::$class";
  90. return $class->new( handle => $self, id => $res->{_guid}, type => $class );
  91. };
  92. #All of the Playwright::* Classes are made by this MAGIC
  93. Sub::Install::install_sub({
  94. code => sub ($classname,%options) {
  95. @class::ISA = qw{Playwright::Base};
  96. $options{type} = $class;
  97. return Playwright::Base::new($classname,%options);
  98. },
  99. as => 'new',
  100. into => "Playwright::$class",
  101. });
  102. # Hack in mouse and keyboard objects for the Page class
  103. if ($class eq 'Page') {
  104. foreach my $hid (qw{keyboard mouse}) {
  105. Sub::Install::install_sub({
  106. code => sub {
  107. my $self = shift;
  108. $Playwright::mapper{$hid}->($self, { _type => $self->{type}, _guid => $self->{guid} }) if exists $Playwright::mapper{$hid};
  109. },
  110. as => $hid,
  111. into => "Playwright::$class",
  112. });
  113. }
  114. }
  115. # Install the subroutines if they aren't already
  116. foreach my $method ((keys(%{$spec->{$class}{members}}), 'on')) {
  117. next if grep { $_ eq $method } qw{keyboard mouse};
  118. my $renamed = exists $methods_to_rename{$method} ? $methods_to_rename{$method} : $method;
  119. Sub::Install::install_sub({
  120. code => sub {
  121. my $self = shift;
  122. Playwright::Base::_request($self, args => [@_], command => $method, object => $self->{guid}, type => $self->{type} );
  123. },
  124. as => $renamed,
  125. into => "Playwright::$class",
  126. });
  127. }
  128. }
  129. # Make sure it's possible to start the server
  130. $server_bin = "$path2here/../bin/playwright.js";
  131. confess("Can't locate Playwright server in '$server_bin'!") unless -f $specfile;
  132. }
  133. sub new ($class, %options) {
  134. #XXX yes, this is a race, so we need retries in _start_server
  135. my $port = Net::EmptyPort::empty_port();
  136. my $self = bless({
  137. ua => $options{ua} // LWP::UserAgent->new(),
  138. port => $port,
  139. debug => $options{debug},
  140. pid => _start_server( $port, $options{debug}),
  141. parent => $$,
  142. }, $class);
  143. return $self;
  144. }
  145. =head1 METHODS
  146. =head2 launch(HASH) = Playwright::Browser
  147. The Argument hash here is essentially those you'd see from browserType.launch(). See:
  148. L<https://playwright.dev/#version=v1.5.1&path=docs%2Fapi.md&q=browsertypelaunchoptions>
  149. There is an additional "special" argument, that of 'type', which is used to specify what type of browser to use, e.g. 'firefox'.
  150. =cut
  151. sub launch ($self, %args) {
  152. #TODO coerce types based on spec
  153. my $msg = Playwright::Util::request ('POST', 'session', $self->{port}, $self->{ua}, type => delete $args{type}, args => [\%args] );
  154. return $Playwright::mapper{$msg->{_type}}->($self,$msg) if (ref $msg eq 'HASH') && $msg->{_type} && exists $Playwright::mapper{$msg->{_type}};
  155. return $msg;
  156. }
  157. =head2 await (AsyncData) = Object
  158. Waits for an asynchronous operation returned by the waitFor* methods to complete and returns the value.
  159. =cut
  160. sub await ($self, $promise) {
  161. confess("Input must be an AsyncData") unless $promise->isa('AsyncData');
  162. my $obj = $promise->result(1);
  163. use Data::Dumper;
  164. print Dumper($obj);
  165. my $class = "Playwright::$obj->{_type}";
  166. return $obj unless $class;
  167. return $class->new( type => $obj->{_type}, id => $obj->{_guid}, handle => $self );
  168. }
  169. =head2 quit, DESTROY
  170. Terminate the browser session and wait for the Playwright server to terminate.
  171. Automatically called when the Playwright object goes out of scope.
  172. =cut
  173. sub quit ($self) {
  174. #Prevent destructor from firing in child processes so we can do things like async()
  175. return unless $$ == $self->{parent};
  176. Playwright::Util::request ('GET', 'shutdown', $self->{port}, $self->{ua} );
  177. return waitpid($self->{pid},0);
  178. }
  179. sub DESTROY ($self) {
  180. $self->quit();
  181. }
  182. sub _start_server($port, $debug) {
  183. $debug = $debug ? '-d' : '';
  184. $ENV{DEBUG} = 'pw:api' if $debug;
  185. my $pid = fork // confess("Could not fork");
  186. if ($pid) {
  187. print "Waiting for port to come up..." if $debug;
  188. Net::EmptyPort::wait_port($port,30) or confess("Server never came up after 30s!");
  189. print "done\n" if $debug;
  190. return $pid;
  191. }
  192. exec( $server_bin, "-p", $port, $debug);
  193. }
  194. 1;