Playwright.pm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. package Playwright;
  2. use strict;
  3. use warnings;
  4. use 5.006;
  5. use v5.28.0; # Before 5.006, v5.10.0 would not be understood.
  6. use sigtrap qw/die normal-signals/;
  7. use File::pushd;
  8. use File::ShareDir();
  9. use File::Basename();
  10. use Cwd();
  11. use LWP::UserAgent();
  12. use Sub::Install();
  13. use Net::EmptyPort();
  14. use JSON::MaybeXS();
  15. use File::Slurper();
  16. use File::Which();
  17. use Capture::Tiny qw{capture_stderr};
  18. use Carp qw{confess};
  19. use Playwright::Base();
  20. use Playwright::Util();
  21. #ABSTRACT: Perl client for Playwright
  22. use 5.006;
  23. use v5.28.0; # Before 5.006, v5.10.0 would not be understood.
  24. no warnings 'experimental';
  25. use feature qw{signatures};
  26. =head1 SYNOPSIS
  27. use JSON::PP;
  28. use Playwright;
  29. my $handle = Playwright->new();
  30. my $browser = $handle->launch( headless => JSON::PP::false, type => 'chrome' );
  31. my $page = $browser->newPage();
  32. my $res = $page->goto('http://google.com', { waitUntil => 'networkidle' });
  33. my $frameset = $page->mainFrame();
  34. my $kidframes = $frameset->childFrames();
  35. =head1 DESCRIPTION
  36. Perl interface to a lightweight node.js webserver that proxies commands runnable by Playwright.
  37. Checks and automatically installs a copy of the node dependencies in the local folder if needed.
  38. Currently understands commands you can send to all the playwright classes defined in api.json (installed wherever your OS puts shared files for CPAN distributions).
  39. See L<https://playwright.dev/#version=master&path=docs%2Fapi.md&q=>
  40. for what the classes do, and their usage.
  41. There are two major exceptions in how things work versus the documentation.
  42. =head2 Selectors
  43. The selector functions have to be renamed from starting with $ for obvious reasons.
  44. The renamed functions are as follows:
  45. =over 4
  46. =item $ => select
  47. =item $$ => selectMulti
  48. =item $eval => eval
  49. =item $$eval => evalMulti
  50. =back
  51. These functions are present as part of the Page, Frame and ElementHandle classes.
  52. =head2 Scripts
  53. The evaluate() and evaluateHandle() functions can only be run in string mode.
  54. To maximize the usefulness of these, I have wrapped the string passed with the following function:
  55. const fun = new Function (toEval);
  56. args = [
  57. fun,
  58. ...args
  59. ];
  60. As such you can effectively treat the script string as a function body.
  61. The same restriction on only being able to pass one arg remains from the upstream:
  62. L<https://playwright.dev/#version=master&path=docs%2Fapi.md&q=pageevaluatepagefunction-arg>
  63. You will have to refer to the arguments array as described here:
  64. L<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments>
  65. =head2 Asynchronous operations
  66. The waitFor* methods defined on various classes will return an instance of L<AsyncData>, a part of the L<Async> module.
  67. You will then need to wait on the result of the backgrounded action with the await() method documented below.
  68. # Assuming $handle is a Playwright object
  69. my $async = $page->waitForEvent('console');
  70. $page->evaluate('console.log("whee")');
  71. my $result = $handle->await( $async );
  72. my $logged = $result->text();
  73. =head1 INSTALLATION NOTE
  74. If you install this module from CPAN, you will likely encounter a croak() telling you to install node module dependencies.
  75. Follow the instructions and things should be just fine.
  76. =head1 CONSTRUCTOR
  77. =head2 new(HASH) = (Playwright)
  78. Creates a new browser and returns a handle to interact with it.
  79. =head3 INPUT
  80. debug (BOOL) : Print extra messages from the Playwright server process
  81. =cut
  82. our ( $spec, $server_bin, $node_bin, %mapper, %methods_to_rename );
  83. sub _check_node {
  84. my $global_install = '';
  85. my $path2here = File::Basename::dirname( Cwd::abs_path( $INC{'Playwright.pm'} ) );
  86. my $decoder = JSON::MaybeXS->new();
  87. # Make sure it's possible to start the server
  88. $server_bin = "$path2here/../bin/playwright_server";
  89. if (!-f $server_bin ) {
  90. $server_bin = File::Which::which('playwright_server');
  91. $global_install = 1;
  92. }
  93. confess("Can't locate Playwright server in '$server_bin'!")
  94. unless -f $server_bin;
  95. #TODO make this portable with File::Which etc
  96. # Check that node and npm are installed
  97. $node_bin = File::Which::which('node');
  98. confess("node must exist and be executable") unless -x $node_bin;
  99. # Check for the necessary modules, this relies on package.json
  100. my $npm_bin = File::Which::which('npm');
  101. confess("npm must exist and be executable") unless -x $npm_bin;
  102. my $dep_raw;
  103. {
  104. #XXX the node Depsolver is deranged, global modules DO NOT WORK
  105. my $curdir = pushd(File::Basename::dirname($server_bin));
  106. capture_stderr { $dep_raw = qx{$npm_bin list --json} };
  107. confess("Could not list available node modules!") unless $dep_raw;
  108. chomp $dep_raw;
  109. my $deptree = $decoder->decode($dep_raw);
  110. my @needed = qw{express uuid yargs playwright};
  111. my @has = keys( %{ $deptree->{dependencies} } );
  112. my @deps = grep {my $subj=$_; grep { $_ eq $subj } @needed } @has;
  113. my $need_deps = scalar(@deps) != scalar(@needed);
  114. #This is really just for developers
  115. if ( $need_deps ) {
  116. confess("Production install of node dependencies must be done manually by nonroot users. Run the following:\n\n pushd '$curdir' && sudo npm i yargs express playwright uuid; popd\n\n") if $global_install;
  117. my $err = capture_stderr { qx{npm i} };
  118. my $exit = $? >> 8;
  119. # Ignore failing for bogus reasons
  120. if ( $err !~ m/package-lock/ ) {
  121. confess("Error installing node dependencies:\n$err") if $exit;
  122. }
  123. }
  124. }
  125. }
  126. sub _build_classes {
  127. $mapper{mouse} = sub {
  128. my ( $self, $res ) = @_;
  129. return Playwright::Mouse->new(
  130. handle => $self,
  131. id => $res->{_guid},
  132. type => 'Mouse'
  133. );
  134. };
  135. $mapper{keyboard} = sub {
  136. my ( $self, $res ) = @_;
  137. return Playwright::Keyboard->new(
  138. handle => $self,
  139. id => $res->{_guid},
  140. type => 'Keyboard'
  141. );
  142. };
  143. %methods_to_rename = (
  144. '$' => 'select',
  145. '$$' => 'selectMulti',
  146. '$eval' => 'eval',
  147. '$$eval' => 'evalMulti',
  148. );
  149. foreach my $class ( keys(%$spec) ) {
  150. $mapper{$class} = sub {
  151. my ( $self, $res ) = @_;
  152. my $class = "Playwright::$class";
  153. return $class->new(
  154. handle => $self,
  155. id => $res->{_guid},
  156. type => $class
  157. );
  158. };
  159. #All of the Playwright::* Classes are made by this MAGIC
  160. Sub::Install::install_sub(
  161. {
  162. code => sub ( $classname, %options ) {
  163. @class::ISA = qw{Playwright::Base};
  164. $options{type} = $class;
  165. return Playwright::Base::new( $classname, %options );
  166. },
  167. as => 'new',
  168. into => "Playwright::$class",
  169. }
  170. ) unless "Playwright::$class"->can('new');;
  171. # Hack in mouse and keyboard objects for the Page class
  172. if ( $class eq 'Page' ) {
  173. foreach my $hid (qw{keyboard mouse}) {
  174. Sub::Install::install_sub(
  175. {
  176. code => sub {
  177. my $self = shift;
  178. $Playwright::mapper{$hid}->(
  179. $self,
  180. {
  181. _type => $self->{type},
  182. _guid => $self->{guid}
  183. }
  184. ) if exists $Playwright::mapper{$hid};
  185. },
  186. as => $hid,
  187. into => "Playwright::$class",
  188. }
  189. ) unless "Playwright::$class"->can($hid);
  190. }
  191. }
  192. # Install the subroutines if they aren't already
  193. foreach my $method ( ( keys( %{ $spec->{$class}{members} } ), 'on' ) ) {
  194. next if grep { $_ eq $method } qw{keyboard mouse};
  195. my $renamed =
  196. exists $methods_to_rename{$method}
  197. ? $methods_to_rename{$method}
  198. : $method;
  199. Sub::Install::install_sub(
  200. {
  201. code => sub {
  202. my $self = shift;
  203. Playwright::Base::_request(
  204. $self,
  205. args => [@_],
  206. command => $method,
  207. object => $self->{guid},
  208. type => $self->{type}
  209. );
  210. },
  211. as => $renamed,
  212. into => "Playwright::$class",
  213. }
  214. ) unless "Playwright::$class"->can($renamed);
  215. }
  216. }
  217. }
  218. sub BEGIN {
  219. our $SKIP_BEGIN;
  220. _check_node() unless $SKIP_BEGIN;
  221. }
  222. sub new ( $class, %options ) {
  223. #XXX yes, this is a race, so we need retries in _start_server
  224. my $port = Net::EmptyPort::empty_port();
  225. my $self = bless(
  226. {
  227. ua => $options{ua} // LWP::UserAgent->new(),
  228. port => $port,
  229. debug => $options{debug},
  230. pid => _start_server( $port, $options{debug} ),
  231. parent => $$,
  232. },
  233. $class
  234. );
  235. $self->_check_and_build_spec();
  236. _build_classes();
  237. return $self;
  238. }
  239. sub _check_and_build_spec ($self) {
  240. return $spec if ref $spec eq 'HASH';
  241. $spec = Playwright::Util::request(
  242. 'GET', 'spec', $self->{port}, $self->{ua},
  243. );
  244. confess("Could not retrieve Playwright specification. Check that your playwright installation is correct and complete.") unless ref $spec eq 'HASH';
  245. return $spec;
  246. }
  247. =head1 METHODS
  248. =head2 launch(HASH) = Playwright::Browser
  249. The Argument hash here is essentially those you'd see from browserType.launch(). See:
  250. L<https://playwright.dev/#version=v1.5.1&path=docs%2Fapi.md&q=browsertypelaunchoptions>
  251. There is an additional "special" argument, that of 'type', which is used to specify what type of browser to use, e.g. 'firefox'.
  252. =cut
  253. sub launch ( $self, %args ) {
  254. Playwright::Base::_coerce(
  255. $spec->{BrowserType}{members},
  256. args => [ \%args ],
  257. command => 'launch'
  258. );
  259. delete $args{command};
  260. my $msg = Playwright::Util::request(
  261. 'POST', 'session', $self->{port}, $self->{ua},
  262. type => delete $args{type},
  263. args => [ \%args ]
  264. );
  265. return $Playwright::mapper{ $msg->{_type} }->( $self, $msg )
  266. if ( ref $msg eq 'HASH' )
  267. && $msg->{_type}
  268. && exists $Playwright::mapper{ $msg->{_type} };
  269. return $msg;
  270. }
  271. =head2 await (AsyncData) = Object
  272. Waits for an asynchronous operation returned by the waitFor* methods to complete and returns the value.
  273. =cut
  274. sub await ( $self, $promise ) {
  275. confess("Input must be an AsyncData") unless $promise->isa('AsyncData');
  276. my $obj = $promise->result(1);
  277. return $obj unless $obj->{_type};
  278. my $class = "Playwright::$obj->{_type}";
  279. return $class->new(
  280. type => $obj->{_type},
  281. id => $obj->{_guid},
  282. handle => $self
  283. );
  284. }
  285. =head2 quit, DESTROY
  286. Terminate the browser session and wait for the Playwright server to terminate.
  287. Automatically called when the Playwright object goes out of scope.
  288. =cut
  289. sub quit ($self) {
  290. #Prevent destructor from firing in child processes so we can do things like async()
  291. return unless $$ == $self->{parent};
  292. Playwright::Util::request( 'GET', 'shutdown', $self->{port}, $self->{ua} );
  293. return waitpid( $self->{pid}, 0 );
  294. }
  295. sub DESTROY ($self) {
  296. $self->quit();
  297. }
  298. sub _start_server ( $port, $debug ) {
  299. $debug = $debug ? '-d' : '';
  300. $ENV{DEBUG} = 'pw:api' if $debug;
  301. my $pid = fork // confess("Could not fork");
  302. if ($pid) {
  303. print "Waiting for port to come up..." if $debug;
  304. Net::EmptyPort::wait_port( $port, 30 )
  305. or confess("Server never came up after 30s!");
  306. print "done\n" if $debug;
  307. return $pid;
  308. }
  309. exec( $node_bin, $server_bin, "-p", $port, $debug );
  310. }
  311. 1;