Playwright.pm 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. =head2 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. =head2 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. =head3 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. =head3 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. =head1 CONSTRUCTOR
  57. =head2 new(HASH) = (Playwright)
  58. Creates a new browser and returns a handle to interact with it.
  59. =head3 INPUT
  60. debug (BOOL) : Print extra messages from the Playwright server process
  61. =cut
  62. our ($spec, $server_bin, %mapper, %methods_to_rename);
  63. BEGIN {
  64. my $path2here = File::Basename::dirname(Cwd::abs_path($INC{'Playwright.pm'}));
  65. my $specfile = "$path2here/../api.json";
  66. confess("Can't locate Playwright specification in '$specfile'!") unless -f $specfile;
  67. my $spec_raw = File::Slurper::read_text($specfile);
  68. my $decoder = JSON::MaybeXS->new();
  69. $spec = $decoder->decode($spec_raw);
  70. $mapper{mouse} = sub { my ($self, $res) = @_; return Playwright::Mouse->new( handle => $self, id => $res->{_guid}, type => 'Mouse' ) };
  71. $mapper{keyboard} = sub { my ($self, $res) = @_; return Playwright::Keyboard->new( handle => $self, id => $res->{_guid}, type => 'Keyboard' ) };
  72. %methods_to_rename = (
  73. '$' => 'select',
  74. '$$' => 'selectMulti',
  75. '$eval' => 'eval',
  76. '$$eval' => 'evalMulti',
  77. );
  78. foreach my $class (keys(%$spec)) {
  79. $mapper{$class} = sub {
  80. my ($self, $res) = @_;
  81. my $class = "Playwright::$class";
  82. return $class->new( handle => $self, id => $res->{_guid}, type => $class );
  83. };
  84. #All of the Playwright::* Classes are made by this MAGIC
  85. Sub::Install::install_sub({
  86. code => sub ($classname,%options) {
  87. @class::ISA = qw{Playwright::Base};
  88. $options{type} = $class;
  89. return Playwright::Base::new($classname,%options);
  90. },
  91. as => 'new',
  92. into => "Playwright::$class",
  93. });
  94. # Hack in mouse and keyboard objects for the Page class
  95. if ($class eq 'Page') {
  96. foreach my $hid (qw{keyboard mouse}) {
  97. Sub::Install::install_sub({
  98. code => sub {
  99. my $self = shift;
  100. $Playwright::mapper{$hid}->($self, { _type => $self->{type}, _guid => $self->{guid} }) if exists $Playwright::mapper{$hid};
  101. },
  102. as => $hid,
  103. into => "Playwright::$class",
  104. });
  105. }
  106. }
  107. # Install the subroutines if they aren't already
  108. foreach my $method ((keys(%{$spec->{$class}{members}}), 'on')) {
  109. next if grep { $_ eq $method } qw{keyboard mouse};
  110. my $renamed = exists $methods_to_rename{$method} ? $methods_to_rename{$method} : $method;
  111. print "Installing sub $renamed into Playwright::$class\n";
  112. Sub::Install::install_sub({
  113. code => sub {
  114. my $self = shift;
  115. Playwright::Base::_request($self, args => [@_], command => $method, object => $self->{guid}, type => $self->{type} );
  116. },
  117. as => $renamed,
  118. into => "Playwright::$class",
  119. });
  120. }
  121. }
  122. # Make sure it's possible to start the server
  123. $server_bin = "$path2here/../bin/playwright.js";
  124. confess("Can't locate Playwright server in '$server_bin'!") unless -f $specfile;
  125. }
  126. sub new ($class, %options) {
  127. #XXX yes, this is a race, so we need retries in _start_server
  128. my $port = Net::EmptyPort::empty_port();
  129. my $self = bless({
  130. ua => $options{ua} // LWP::UserAgent->new(),
  131. port => $port,
  132. debug => $options{debug},
  133. pid => _start_server( $port, $options{debug}),
  134. parent => $$,
  135. }, $class);
  136. return $self;
  137. }
  138. =head1 METHODS
  139. =head2 launch(HASH) = Playwright::Browser
  140. The Argument hash here is essentially those you'd see from browserType.launch(). See:
  141. L<https://playwright.dev/#version=v1.5.1&path=docs%2Fapi.md&q=browsertypelaunchoptions>
  142. There is an additional "special" argument, that of 'type', which is used to specify what type of browser to use, e.g. 'firefox'.
  143. =cut
  144. sub launch ($self, %args) {
  145. #TODO coerce types based on spec
  146. my $msg = Playwright::Util::request ('POST', 'session', $self->{port}, $self->{ua}, type => delete $args{type}, args => [\%args] );
  147. return $Playwright::mapper{$msg->{_type}}->($self,$msg) if (ref $msg eq 'HASH') && $msg->{_type} && exists $Playwright::mapper{$msg->{_type}};
  148. return $msg;
  149. }
  150. =head2 quit, DESTROY
  151. Terminate the browser session and wait for the Playwright server to terminate.
  152. Automatically called when the Playwright object goes out of scope.
  153. =cut
  154. sub quit ($self) {
  155. #Prevent destructor from firing in child processes so we can do things like async()
  156. return unless $$ == $self->{parent};
  157. Playwright::Util::request ('GET', 'shutdown', $self->{port}, $self->{ua} );
  158. return waitpid($self->{pid},0);
  159. }
  160. sub DESTROY ($self) {
  161. $self->quit();
  162. }
  163. sub _start_server($port, $debug) {
  164. $debug = $debug ? '-d' : '';
  165. $ENV{DEBUG} = 'pw:api' if $debug;
  166. my $pid = fork // confess("Could not fork");
  167. if ($pid) {
  168. print "Waiting for port to come up..." if $debug;
  169. Net::EmptyPort::wait_port($port,30) or confess("Server never came up after 30s!");
  170. print "done\n" if $debug;
  171. return $pid;
  172. }
  173. exec( $server_bin, "-p", $port, $debug);
  174. }
  175. 1;