Playwright.pm 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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 Net::EmptyPort();
  8. use LWP::UserAgent();
  9. use Sub::Install();
  10. use JSON::MaybeXS();
  11. use File::Slurper();
  12. use Carp qw{confess};
  13. use Playwright::Page();
  14. #ABSTRACT: Perl client for Playwright
  15. no warnings 'experimental';
  16. use feature qw{signatures state};
  17. =head2 SYNOPSIS
  18. use Playwright;
  19. my ($browser,$page) = Playwright->new( browser => "chrome" );
  20. $page->goto('http://www.google.com');
  21. my $browser_version = $browser->version();
  22. $browser->quit();
  23. =head2 DESCRIPTION
  24. Perl interface to a lightweight node.js webserver that proxies commands runnable by Playwright.
  25. Currently understands commands you can send to the following Playwright classes,
  26. commands for which can be sent via instances of the noted module
  27. =over 4
  28. =item B<Browser> - L<Playwright> L<https://playwright.dev/#version=master&path=docs%2Fapi.md&q=class-browser>
  29. =item B<BrowserContext> - L<Playwright> L<https://playwright.dev/#version=master&path=docs%2Fapi.md&q=class-browsercontext>
  30. =item B<Page> - L<Playwright::Page> L<https://playwright.dev/#version=v1.5.1&path=docs%2Fapi.md&q=class-page>
  31. =item B<Response> - L<Playwright::Response> L<https://playwright.dev/#version=v1.5.1&path=docs%2Fapi.md&q=class-response>
  32. =back
  33. The specification for the above classes can also be inspected with the 'spec' method for each respective class:
  34. use Data::Dumper;
  35. print Dumper($browser->spec , $page->spec, ...);
  36. =head1 CONSTRUCTOR
  37. =head2 new(HASH) = (Playwright,Playwright::Page)
  38. Creates a new browser and returns a handle to interact with it, along with a new page Handle to interact with therein.
  39. =head3 INPUT
  40. browser (STRING) : Name of the browser to use. One of (chrome, firefox, webkit).
  41. visible (BOOL) : Whether to start the browser such that it displays on your desktop (headless or not).
  42. debug (BOOL) : Print extra messages from the Playwright server process
  43. =cut
  44. our ($spec, $server_bin, %class_spec);
  45. my %transmogrify = (
  46. Page => sub {
  47. my ($self, $res) = @_;
  48. require Playwright::Page;
  49. return Playwright::Page->new( browser => $self, page => $res->{_guid} );
  50. },
  51. );
  52. BEGIN {
  53. my $path2here = File::Basename::dirname(Cwd::abs_path($INC{'Playwright.pm'}));
  54. my $specfile = "$path2here/../api.json";
  55. confess("Can't locate Playwright specification in '$specfile'!") unless -f $specfile;
  56. my $spec_raw = File::Slurper::read_text($specfile);
  57. my $decoder = JSON::MaybeXS->new();
  58. $spec = $decoder->decode($spec_raw);
  59. %class_spec = (
  60. %{$spec->{Browser}{members}},
  61. %{$spec->{BrowserContext}{members}}
  62. );
  63. # Install the subroutines if they aren't already
  64. foreach my $method (keys(%class_spec)) {
  65. Sub::Install::install_sub({
  66. code => sub { _request(shift, \%transmogrify, args => [@_], command => $method ) },
  67. as => $method,
  68. });
  69. }
  70. # Make sure it's possible to start the server
  71. $server_bin = "$path2here/../bin/playwright.js";
  72. confess("Can't locate Playwright server in '$server_bin'!") unless -f $specfile;
  73. 1;
  74. }
  75. sub new ($class, %options) {
  76. #XXX yes, this is a race, so we need retries in _start_server
  77. my $port = Net::EmptyPort::empty_port();
  78. my $self = bless({
  79. spec => $spec,
  80. ua => $options{ua} // LWP::UserAgent->new(),
  81. browser => $options{browser},
  82. visible => $options{visible},
  83. port => $port,
  84. debug => $options{debug},
  85. pid => _start_server($options{browser},$options{visible}, $port, $options{debug}),
  86. }, $class);
  87. $self->_request( \%transmogrify, url => 'session' );
  88. return ($self, Playwright::Page->new( browser => $self, page => 'default' ));
  89. }
  90. =head1 METHODS
  91. =head2 spec
  92. Return the relevant methods and their definitions for this module which are built dynamically from the Playwright API spec.
  93. =cut
  94. sub spec ($self) {
  95. return %class_spec;
  96. }
  97. =head2 quit, DESTROY
  98. Terminate the browser session and wait for the Playwright server to terminate.
  99. Automatically called when the Playwright object goes out of scope.
  100. =cut
  101. sub quit ($self) {
  102. $self->_request( \%transmogrify, url => 'shutdown' );
  103. return waitpid($self->{pid},0);
  104. }
  105. sub DESTROY ($self) {
  106. $self->quit();
  107. }
  108. sub _start_server($browser,$visible, $port, $debug) {
  109. confess("Invalid browser '$browser'") unless grep { $_ eq $browser } qw{chrome firefox webkit};
  110. $visible = $visible ? '-v' : '';
  111. $debug = $debug ? '-d' : '';
  112. $ENV{DEBUG} = 'pw:api';
  113. my $pid = fork // confess("Could not fork");
  114. if ($pid) {
  115. print "Waiting for port to come up..." if $debug;
  116. Net::EmptyPort::wait_port($port,30) or confess("Server never came up after 30s!");
  117. print "done\n" if $debug;
  118. return $pid;
  119. }
  120. exec( $server_bin, $browser, $visible, "-p", $port, $debug);
  121. }
  122. sub _request ($self, $translator, %args) {
  123. $translator //= \%transmogrify;
  124. my $url = $args{url} // 'command';
  125. my $fullurl = "http://localhost:$self->{port}/$url";
  126. my $method = $url eq 'command' ? 'POST' : 'GET';
  127. my $request = HTTP::Request->new( $method, $fullurl);
  128. $request->header( 'Content-type' => 'application/json' );
  129. $request->content( JSON::MaybeXS::encode_json(\%args) );
  130. my $response = $self->{ua}->request($request);
  131. my $decoded = JSON::MaybeXS::decode_json($response->decoded_content());
  132. my $msg = $decoded->{message};
  133. confess($msg) if $decoded->{error};
  134. return $translator->{$msg->{_type}}->($self,$msg) if (ref $msg eq 'HASH') && $msg->{_type} && exists $translator->{$msg->{_type}};
  135. return $msg;
  136. }
  137. 1;