Playwright.pm 7.8 KB

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