Playwright.pm 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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);
  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. foreach my $class (keys(%$spec)) {
  71. $mapper{$class} = sub {
  72. my ($self, $res) = @_;
  73. my $class = "Playwright::$class";
  74. return $class->new( handle => $self, id => $res->{_guid}, type => $class );
  75. };
  76. #All of the Playwright::* Classes are made by this MAGIC
  77. Sub::Install::install_sub({
  78. code => sub ($classname,%options) {
  79. @class::ISA = qw{Playwright::Base};
  80. $options{type} = $class;
  81. return Playwright::Base::new($classname,%options);
  82. },
  83. as => 'new',
  84. into => "Playwright::$class",
  85. });
  86. }
  87. $mapper{mouse} = sub { my ($self, $res) = @_; return Playwright::Mouse->new( handle => $self, id => $res->{_guid}, type => 'Mouse' ) };
  88. $mapper{keyboard} = sub { my ($self, $res) = @_; return Playwright::Keyboard->new( handle => $self, id => $res->{_guid}, type => 'Keyboard' ) };
  89. # Make sure it's possible to start the server
  90. $server_bin = "$path2here/../bin/playwright.js";
  91. confess("Can't locate Playwright server in '$server_bin'!") unless -f $specfile;
  92. }
  93. sub new ($class, %options) {
  94. #XXX yes, this is a race, so we need retries in _start_server
  95. my $port = Net::EmptyPort::empty_port();
  96. my $self = bless({
  97. ua => $options{ua} // LWP::UserAgent->new(),
  98. port => $port,
  99. debug => $options{debug},
  100. pid => _start_server( $port, $options{debug}),
  101. }, $class);
  102. return $self;
  103. }
  104. =head1 METHODS
  105. =head2 launch(HASH) = Playwright::Browser
  106. The Argument hash here is essentially those you'd see from browserType.launch(). See:
  107. L<https://playwright.dev/#version=v1.5.1&path=docs%2Fapi.md&q=browsertypelaunchoptions>
  108. There is an additional "special" argument, that of 'type', which is used to specify what type of browser to use, e.g. 'firefox'.
  109. =cut
  110. sub launch ($self, %args) {
  111. #TODO coerce types based on spec
  112. my $msg = Playwright::Util::request ('POST', 'session', $self->{port}, $self->{ua}, type => delete $args{type}, args => [\%args] );
  113. return $Playwright::mapper{$msg->{_type}}->($self,$msg) if (ref $msg eq 'HASH') && $msg->{_type} && exists $Playwright::mapper{$msg->{_type}};
  114. return $msg;
  115. }
  116. =head2 quit, DESTROY
  117. Terminate the browser session and wait for the Playwright server to terminate.
  118. Automatically called when the Playwright object goes out of scope.
  119. =cut
  120. sub quit ($self) {
  121. Playwright::Util::request ('GET', 'shutdown', $self->{port}, $self->{ua} );
  122. return waitpid($self->{pid},0);
  123. }
  124. sub DESTROY ($self) {
  125. $self->quit();
  126. }
  127. sub _start_server($port, $debug) {
  128. $debug = $debug ? '-d' : '';
  129. $ENV{DEBUG} = 'pw:api' if $debug;
  130. my $pid = fork // confess("Could not fork");
  131. if ($pid) {
  132. print "Waiting for port to come up..." if $debug;
  133. Net::EmptyPort::wait_port($port,30) or confess("Server never came up after 30s!");
  134. print "done\n" if $debug;
  135. return $pid;
  136. }
  137. exec( $server_bin, "-p", $port, $debug);
  138. }
  139. 1;