Playwright.pm 14 KB

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