-
Notifications
You must be signed in to change notification settings - Fork 12
/
Chrome.pm
5637 lines (4329 loc) · 162 KB
/
Chrome.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package WWW::Mechanize::Chrome;
use strict;
use warnings;
use Filter::signatures;
no warnings 'experimental::signatures';
use feature 'signatures';
use PerlX::Maybe;
use File::Spec;
use HTTP::Response;
use HTTP::Headers;
use Scalar::Util qw( blessed weaken);
use File::Basename;
use Carp qw(croak carp);
use WWW::Mechanize::Link;
use IO::Socket::INET;
use Chrome::DevToolsProtocol;
use Chrome::DevToolsProtocol::Target;
use WWW::Mechanize::Chrome::Node;
use JSON;
use MIME::Base64 'decode_base64';
use Data::Dumper;
use Time::HiRes qw(usleep);
use Storable 'dclone';
use HTML::Selector::XPath 'selector_to_xpath';
use HTTP::Cookies::ChromeDevTools;
use POSIX ':sys_wait_h';
our $VERSION = '0.40';
our @CARP_NOT;
=encoding utf-8
=head1 NAME
WWW::Mechanize::Chrome - automate the Chrome browser
=head1 SYNOPSIS
use Log::Log4perl qw(:easy);
use WWW::Mechanize::Chrome;
Log::Log4perl->easy_init($ERROR); # Set priority of root logger to ERROR
my $mech = WWW::Mechanize::Chrome->new();
$mech->get('https://google.com');
$mech->eval_in_page('alert("Hello Chrome")');
my $png = $mech->content_as_png();
A collection of other L<Examples|WWW::Mechanize::Chrome::Examples> is available
to help you get started.
=head1 DESCRIPTION
Like L<WWW::Mechanize>, this module automates web browsing with a Perl object.
Fetching and rendering of web pages is delegated to the Chrome (or Chromium)
browser by starting an instance of the browser and controlling it with L<Chrome
DevTools|https://developers.google.com/web/tools/chrome-devtools/>.
=head2 Advantages Over L<WWW::Mechanize>
The Chrome browser provides advanced abilities useful for automating modern
web applications that are not (yet) possible with L<WWW::Mechanize> alone:
=over 4
=item *
Page content can be created or modified with JavaScript. You can also execute
custom JavaScript code on the page content.
=item *
Page content can be selected with CSS selectors.
=item *
Screenshots of the rendered page as an image or PDF file.
=back
=head2 Disadvantages
Installation of a Chrome compatible browser is required. There are some quirks
including sporadic, but harmless, error messages issued by the browser when
run with with DevTools.
=head2 A Brief Operational Overview
C<WWW::Mechanize::Chrome> (WMC) leverages developer tools built into Chrome and
Chrome-like browsers to control a browser instance programatically. You can use
WMC to automate tedious tasks, test web applications, and perform web scraping
operations.
Typically, WMC is used to launch both a I<host> instance of the browser and
provide a I<client> instance of the browser. The host instance of the browser is
visible to you on your desktop (unless the browser is running in "headless"
mode, in which case it will not open in a window). The client instance is the
Perl program you write with the WMC module to issue commands to control the host
instance. As you navigate and "click" on various nodes in the client browser,
you watch the host browser respond to these actions as if by magic.
This magic happens as a result of commands that are issued from your client to
the host using Chrome's DevTools Protocol which implements the http protocol to
send JSON data structures. The host also responds to the client with JSON to
describe the web pages it has loaded. WMC conveniently hides the complexity of
the lower level communications between the client and host browsers and wraps
them in a Perl object to provide the easy-to-use methods documented here.
=head1 OPTIONS
=head2 C<< WWW::Mechanize::Chrome->new( %options ) >>
my $mech = WWW::Mechanize::Chrome->new();
=over 4
=item B<autodie>
autodie => 0 # make HTTP errors non-fatal
By default, C<autodie> is set to true. If an HTTP error is encountered, the
program dies along with its associated browser instances. This frees you from
having to write error checks after every request. Setting this value to false
makes HTTP errors non-fatal, allowing the program to continue running if
there is an error.
=item B<host>
Set the host the browser listens on:
host => '192.168.1.2'
host => 'localhost'
Defaults to C<127.0.0.1>. The browser will listen for commands on the
specified host. The host address should be inaccessible from the internet.
=item B<port>
port => 9223 # set port the launched browser will use for remote operation
Defaults to C<9222>. Commands to the browser will be issued through this port.
=item B<tab>
Specify the browser tab the Chrome browser will use:
tab => 'current'
tab => qr/PerlMonks/
By default, a web page is opened in a new browser tab. Setting C<tab> to
C<current> will use the current, active tab instead. Alternatively, to use an
existing inactive tab, you can pass a regular expression to match against the
existing tab's title. A false value implements the default behavior and a new
tab will be created.
=item B<autoclose>
autoclose => 0 # keep tab open after program end
By default, C<autoclose> is set to true, closing the tab opened when running
your code. If C<autoclose> is set to a false value, the tab will remain open
even after the program has finished.
=item B<host>
Set the host the browser listens on:
host => '192.168.1.2'
host => 'localhost'
Defaults to C<127.0.0.1>. The browser will listen for commands on the
specified host. The host address should be inaccessible from the internet.
=item B<log>
log => $object # specify the object used for logging
Can be used to supply a L<Log::Log4perl> object that has been manually
constructed.
=item B<launch_exe>
Set the name and/or path to the browser's executable program:
launch_exe => 'name-of-chrome-executable' # for non-standard executable names
launch_exe => '/path/to/executable' # for non-standard paths
launch_exe => '/path/to/executable/chrome' # full path
By default, C<WWW::Mechanize::Chrome> will search the appropriate paths for
Chrome's executable file based on the operating system. Use this option to set
the path to your executable if it is in a non-standard location or if the
executable has a non-standard name.
The default paths searched are those found in C<$ENV{PATH}>. For OS X, the user
and system C<Application> directories are also searched. The default values for
the executable file's name are C<chrome> on Windows, C<Google Chrome> on OS X,
and C<google-chrome> elsewhere.
If you want to use Chromium, you must specify that explicitly with something
like:
launch_exe => 'chromium-browser', # if Chromium is named chromium-browser on your OS
Results my vary for your operating system. Use the full path to the browser's
executable if you are having issues. You can also set the name of the executable
file with the C<$ENV{CHROME_BIN}> environment variable.
=item B<cleanup_signal>
cleanup_signal => 'SIGKILL'
The signal that is sent to Chrome to shut it down. On Linuxish OSes, this
will be C<TERM>, on OSX and Windows it will be C<KILL>.
=item B<start_url>
start_url => 'http://perlmonks.org' # Immediately navigate to a given URL
By default, the browser will open with a blank tab. Use the C<start_url> option
to open the browser to the specified URL. More typically, the C<< ->get >>
method is use to navigate to URLs.
=item B<launch_arg>
Pass additional switches and parameters to the browser's executable:
launch_arg => [ "--some-new-parameter=foo", "--another-option" ]
Examples of other useful parameters include:
'--start-maximized',
'--window-size=1280x1696'
'--ignore-certificate-errors'
'--disable-web-security',
'--allow-running-insecure-content',
'--load-extension'
'--no-sandbox'
=item B<profile>
profile => '/path/to/profile/directory' # set the profile directory
By default, your current user profile directory is used. Use this setting
to change the profile directory for the browsing session.
=item B<incognito>
incognito => 1 # open the browser in incognito mode
Defaults to false. Set to true to launch the browser in incognito mode.
=item B<data_directory>
data_directory => '/path/to/data/directory' # set the data directory
By default, the current data directory is used. Use this setting to change the
base data directory for the browsing session.
use File::Temp 'tempdir';
# create a fresh Chrome every time
my $mech = WWW::Mechanize::Chrome->new(
data_directory => tempdir(CLEANUP => 1 ),
);
=item B<wait_file>
wait_file => "$tempdir/CrashpadMetrics-active.pma"
When shutting down, wait until this file does not exist anymore or can be
deleted. This can help making sure that the Chrome process has really shut
down.
=item B<startup_timeout>
startup_timeout => 5 # set the startup timeout value
Defaults to 20, the maximum number of seconds to wait for the browser to launch.
Higher or lower values can be set based on the speed of the machine. The
process attempts to connect to the browser once each second over the duration
of this setting.
=item B<listen_host>
listen_host => '192.1.168.7' # set an IP address for listening
Specifies an IP address the launched browser process should listen on. This
option is useful for controlling the browser from another machine on your
network.
=item B<driver>
driver => $driver_object # specify the driver object
Use a L<Chrome::DevToolsProtocol::Target> object that has been manually constructed.
=item B<report_js_errors>
report_js_errors => 1 # turn javascript error reporting on
Defaults to false. If true, tests for Javascript errors and warns after each
request are run. This is useful for testing with C<use warnings qw(fatal)>.
=item B<mute_audio>
mute_audio => 0 # turn sounds on
Defaults to true (sound off). A false value turns the sound on.
=item B<background_networking>
background_networking => 1 # turn background networking on
Defaults to false (off). A true value enables background networking.
=item B<client_side_phishing_detection>
client_side_phishing_detection => 1 # turn client side phishing detection on
Defaults to false (off). A true value enables client side phishing detection.
=item B<component_update>
component_update => 1 # turn component updates on
Defaults to false (off). A true value enables component updates.
=item B<default_apps>
default_apps => 1 # turn default apps on
Defaults to false (off). A true value enables default apps.
=item B<hang_monitor>
hang_monitor => 1 # turn the hang monitor on
Defaults to false (off). A true value enables the hang monitor.
=item B<hide_scrollbars>
hide_scrollbars => 1 # hide the scrollbars
Defaults to false (off). A true value will hide the scrollbars.
=item B<infobars>
infobars => 1 # turn infobars on
Defaults to false (off). A true value will turn infobars on.
=item B<popup_blocking>
popup_bloacking => 1 # block popups
Defaults to false (off). A true value will block popups.
=item B<prompt_on_repost>
prompt_on_repost => 1 # allow prompts when reposting
Defaults to false (off). A true value will allow prompts when reposting.
=item B<save_password_bubble>
save_password_bubble => 1 # allow the display of the save password bubble
Defaults to false (off). A true value allows the save password bubble to be
displayed.
=item B<sync>
sync => 1 # turn syncing on
Defaults to false (off). A true value turns syncing on.
=item B<web_resources>
web_resources => 1 # turn web resources on
Defaults to false (off). A true value turns web resources on.
=back
The C<< $ENV{WWW_MECHANIZE_CHROME_TRANSPORT} >> variable can be set to a
different transport class to override the default L<transport
class|Chrome::DevToolsProtcol::Transport>. This is primarily used for testing
but can also help eliminate introducing bugs from the underlying websocket
implementation(s).
The C<< $ENV{WWW_MECHANIZE_CHROME_CONNECTION_STYLE} >> variable can be set to
either C<websocket> or C<pipe> to specify the kind of transport that you
want to use.
The C<pipe> transport is only available on unixish OSes and only with Chrome
v72 onwards.
=head1 METHODS
=cut
sub build_command_line {
my( $class, $options )= @_;
my @program_names = $class->default_executable_names( $options->{launch_exe} );
my( $program, $error) = $class->find_executable(\@program_names);
croak $error if ! $program;
# Convert the path to an absolute filename, so we can chdir() later
$program = File::Spec->rel2abs( $program ) || $program;
$options->{ launch_arg } ||= [];
# We want to read back the URL we can use to talk to Chrome
if( $^O =~ /mswin/i ) {
#push @{ $options->{launch_arg}}, '--v=0', '--enable-logging'; # v79 bad, v78 bad, v77 bad, v76 bad, v75 bad, v70 bad
push @{ $options->{launch_arg}}, '--v=0'; # v79 OK, v62 OK, v61 bad
};
if( $options->{pipe}) {
push @{ $options->{ launch_arg }}, "--remote-debugging-pipe";
} else {
$options->{port} //= 9222
if ! exists $options->{port};
if (exists $options->{port}) {
$options->{port} ||= 0;
push @{ $options->{ launch_arg }}, "--remote-debugging-port=$options->{ port }";
};
if ($options->{listen_host}) {
push @{ $options->{ launch_arg }}, "--remote-debugging-address==$options->{ listen_host }";
};
};
if ($options->{incognito}) {
push @{ $options->{ launch_arg }}, "--incognito";
};
if ($options->{data_directory}) {
push @{ $options->{ launch_arg }}, "--user-data-dir=$options->{ data_directory }";
};
if ($options->{profile}) {
push @{ $options->{ launch_arg }}, "--profile-directory=$options->{ profile }";
};
if( ! exists $options->{enable_automation} || $options->{enable_automation}) {
push @{ $options->{ launch_arg }}, "--enable-automation";
};
if( ! exists $options->{enable_first_run} || ! $options->{enable_first_run}) {
push @{ $options->{ launch_arg }}, "--no-first-run";
};
if( ! exists $options->{mute_audio} || $options->{mute_audio}) {
push @{ $options->{ launch_arg }}, "--mute-audio";
};
if( ! exists $options->{no_zygote} || $options->{no_zygote}) {
push @{ $options->{ launch_arg }}, "--no-zygote";
};
if( ! exists $options->{no_zygote} || $options->{no_sandbox}) {
push @{ $options->{ launch_arg }}, "--no-sandbox";
};
if( $options->{hide_scrollbars}) {
push @{ $options->{ launch_arg }}, "--hide-scrollbars";
};
# Yes, that name is horrible
if( $options->{safebrowsing_auto_update}) {
} else {
push @{ $options->{ launch_arg }}, "--safebrowsing-disable-auto-update";
};
if( exists $options->{disable_prompt_on_repost}) {
carp "Option 'disable_prompt_on_repost' is deprecated, use prompt_on_repost instead";
$options->{prompt_on_repost} = !$options->{disable_prompt_on_repost};
};
for my $option (qw(
background_networking
breakpad
client_side_phishing_detection
component_update
hang_monitor
prompt_on_repost
sync
translate
web_resources
default_apps
infobars
popup_blocking
gpu
save-password-bubble
)) {
(my $optname = $option) =~ s!_!-!g;
if( ! exists $options->{$option}) {
push @{ $options->{ launch_arg }}, "--disable-$optname";
} elsif( ! (my $value = delete $options->{$option})) {
push @{ $options->{ launch_arg }}, "--disable-$optname";
};
};
push @{ $options->{ launch_arg }}, "--headless"
if $options->{ headless };
push @{ $options->{ launch_arg }}, "$options->{start_url}"
if exists $options->{start_url};
my $quoted_program = ($^O =~ /mswin/i and $program =~ /[\s|<>&]/)
? qq("$program")
: $program;
my @cmd=( $program, @{ $options->{launch_arg}} );
@cmd
};
=head2 C<< WWW::Mechanize::Chrome->find_executable >>
my $chrome = WWW::Mechanize::Chrome->find_executable();
my $chrome = WWW::Mechanize::Chrome->find_executable(
'chromium.exe',
'.\\my-chrome-66\\',
);
my( $chrome, $diagnosis ) = WWW::Mechanize::Chrome->find_executable(
['chromium-browser','google-chrome'],
'./my-chrome-66/',
);
die $diagnosis if ! $chrome;
Finds the first Chrome executable in the path (C<$ENV{PATH}>). For Windows, it
also looks in C<< $ENV{ProgramFiles} >>, C<< $ENV{ProgramFiles(x86)} >>
and C<< $ENV{"ProgramFilesW6432"} >>. For OSX it also looks in the user home
directory as given through C<< $ENV{HOME} >>.
This is used to find the default Chrome executable if none was given through
the C<launch_exe> option or if the executable is given and does not exist
and does not contain a directory separator.
=cut
sub default_executable_names( $class, @other ) {
my @program_names
= grep { defined($_) } (
$ENV{CHROME_BIN},
@other,
);
if( ! @program_names ) {
push @program_names,
$^O =~ /mswin/i ? 'chrome.exe'
: $^O =~ /darwin/i ? ('Google Chrome', 'Chromium')
: ('google-chrome', 'chromium-browser', 'chromium')
};
@program_names
}
# Returns additional directories where the default executable can be found
# on this OS
sub additional_executable_search_directories( $class, $os_style=$^O ) {
my @search;
if( $os_style =~ /MSWin/i ) {
push @search,
map { "$_\\Google\\Chrome\\Application\\" }
grep {defined}
($ENV{'ProgramFiles'},
$ENV{'ProgramFiles(x86)'},
$ENV{"ProgramFilesW6432"},
$ENV{"LOCALAPPDATA"},
);
} elsif( $os_style =~ /darwin/i ) {
for my $path ('/Applications/Google Chrome.app/Contents/MacOS',
'/Applications/Chromium.app/Contents/MacOS') {
push @search,
grep { -d $_ }
$path,
$ENV{"HOME"} . "/$path";
};
}
@search
}
sub find_executable( $class, $program=[$class->default_executable_names], @search) {
my $looked_for = '';
if( ! ref $program) {
$program = [$program]
};
my $program_name = join ", ", map { qq('$_') } @$program;
if( my($first_program) = grep { -x $_ } @$program) {
# We've got a complete path, done!
return $first_program
};
# Not immediately found, so we need to search
my @without_path = grep { !m![/\\]! } @$program;
if( @without_path) {
push @search, File::Spec->path();
push @search, $class->additional_executable_search_directories();
$looked_for = ' in searchpath ' . join " ", @search;
};
my $found;
for my $path (@search) {
for my $p (@without_path) {
my $this = File::Spec->catfile( $path, $p );
if( -x $this ) {
$found = $this;
last;
};
};
};
if( wantarray ) {
my $msg;
if( ! $found) {
$msg = "No executable like $program_name found$looked_for";
};
return $found, $msg
} else {
return $found
};
}
sub _find_free_port( $class, $start ) {
my $port = $start;
while (1) {
$port++, next unless IO::Socket::INET->new(
Listen => 5,
Proto => 'tcp',
Reuse => 1,
LocalPort => $port
);
last;
}
$port;
}
sub _wait_for_socket_connection( $class, $host, $port, $timeout=20 ) {
my $wait = time + $timeout;
while ( time < $wait ) {
my $t = time;
my $socket = IO::Socket::INET->new(
PeerHost => $host,
PeerPort => $port,
Proto => 'tcp',
);
if( $socket ) {
close $socket;
sleep(1);
last;
};
sleep(1) if time - $t < 1;
}
my $res = 1;
if( time >= $wait ) {
# No logger available yet
#warn "Got timeout while waiting for Chrome at $host:$port";
$res = 0;
};
$res
};
sub spawn_child_win32( $self, $method, @cmd ) {
croak "Only websocket communication is supported on $^O, not '$method'"
if $method ne 'websocket';
# Our store for the filehandles
my (%child, %parent);
require IPC::Open3;
require Symbol;
$parent{child_output} = Symbol::gensym();
my $pid = IPC::Open3::open3(
undef, $parent{ child_output }, $parent{ child_output },
@cmd
);
return $pid, $parent{write}, $parent{read}, $parent{child_output};
}
sub spawn_child_posix( $self, $method, @cmd ) {
require POSIX;
POSIX->import("setsid");
# Our store for the filehandles
my (%child, %parent);
if( $method eq 'pipe' ) {
# Now, we want to have file handles with fileno=3 and fileno=4
# to talk to Chrome v72+
# Just open some filehandles to push the filenos above 4 for sure:
open my $dummy_fh, '>', '/dev/null';
open my $dummy_fh2, '>', '/dev/null';
pipe $child{read}, $parent{write};
pipe $parent{read}, $child{write};
close $dummy_fh;
close $dummy_fh2;
} else {
# We want to read back the websocket URL from the STDOUT (well STDERR)
# of the child
pipe $parent{child_output}, $child{stdout};
$parent{child_output}->autoflush(1);
};
# daemonize
defined(my $pid = fork()) || die "can't fork: $!";
if( $pid ) { # non-zero now means I am the parent
# Close all child filehandles
for my $v (values(%child)) {
close $v;
};
return $pid, $parent{write}, $parent{read}, $parent{child_output};
};
# We are the child, close about everything, then exec
chdir("/") || die "can't chdir to /: $!";
(setsid() != -1) || die "Can't start a new session: $!";
open(STDIN, "< /dev/null") || die "can't read /dev/null: $!";
if( 'pipe' eq $method ) {
open(STDERR, ">&", STDOUT) || die "can't dup stdout: $!";
open(STDOUT, "> /dev/null") || die "can't talk to new STDOUT: $!";
} else {
open(STDERR, ">&", $child{stdout}) || die "can't dup stdout: $!";
open(STDOUT, ">&", $child{stdout}) || die "can't talk to new STDOUT: $!";
};
my ($from_chrome, $to_chrome);
if( $method eq 'pipe' ) {
# We want handles 0,1,2,3,4 to be inherited by Chrome
$^F = 4;
# Set up FD 3 and 4 for Chrome to read/write
open($from_chrome, '<&', $child{read})|| die "can't open reader pipe: $!";
open($to_chrome, '>&', $child{write}) || die "can't open writer pipe: $!";
}
for my $v (values(%parent)) {
close $v;
};
#close $parent{child_output};
exec @cmd;
warn "Child couldn't launch [@cmd]: $!";
exit 1;
}
sub spawn_child( $self, $method, @cmd ) {
my ($pid, $to_chrome, $from_chrome, $chrome_stdout);
if( $^O =~ /mswin/i ) {
($pid,$to_chrome,$from_chrome, $chrome_stdout) = $self->spawn_child_win32($method, @cmd)
} else {
($pid,$to_chrome,$from_chrome, $chrome_stdout) = $self->spawn_child_posix($method, @cmd)
};
$self->log('debug', "Spawned child as $pid");
return ($pid,$to_chrome,$from_chrome, $chrome_stdout)
}
sub read_devtools_url( $self, $fh, $lines = 10 ) {
# We expect the output within the first 10 lines...
my $devtools_url;
while( $lines-- and ! defined $devtools_url and ! eof($fh)) {
my $line = <$fh>;
last unless defined $line;
$line =~ s!\s+$!!;
#$self->log('trace', "[[$line]]");
if( $line =~ m!^DevTools listening on (ws:\S+)$!) {
$devtools_url = $1;
$self->log('trace', "Found ws endpoint from child output as '$devtools_url'");
last;
};
};
$devtools_url
};
sub _build_log( $self ) {
require Log::Log4perl;
Log::Log4perl->get_logger(__PACKAGE__);
}
# The generation of node ids
sub _generation( $self, $val=undef ) {
@_ == 2 and $self->{_generation} = $_[1];
$self->{_generation}
};
sub new_generation( $self ) {
$self->_generation( ($self->_generation() ||0) +1 );
}
sub log( $self, $level, $message, @args ) {
my $logger = $self->{log};
if( !@args ) {
$logger->$level( $message )
} else {
my $enabled = "is_$level";
$logger->$level( join " ", $message, Dumper @args )
if( $logger->$enabled );
};
}
# Find out what connection style (websocket, pipe) the user wants:
sub connection_style( $class, $options ) {
if( $options->{pipe} ) {
return 'pipe'
} else {
my $t = ref( $options->{ transport } )
|| $options->{ transport }
|| 'Chrome::DevToolsProtocol::Transport';
;
eval "require $t; 1"
or warn $@;
return $t->new->type || 'websocket';
};
};
sub new($class, %options) {
if (! exists $options{ autodie }) {
$options{ autodie } = 1
};
if( ! exists $options{ frames }) {
$options{ frames }= 1;
};
if( ! exists $options{ download_directory }) {
$options{ download_directory }= '';
};
$options{ startup_timeout } //= 20;
$options{ js_events } ||= [];
if( ! exists $options{ transport }) {
$options{ transport } ||= $ENV{ WWW_MECHANIZE_CHROME_TRANSPORT };
};
$options{start_url} = 'about:blank'
unless exists $options{start_url};
my $host = $options{ host } || '127.0.0.1';
$options{ reuse } ||= defined $options{ tab };
$options{ extra_headers } ||= {};
if( $options{ tab } and $options{ tab } eq 'current' ) {
$options{ tab } = 0; # use tab at index 0
};
# Find out what connection style we need/the user wants
my $connection_style = $options{ connection_style }
|| $ENV{ WWW_MECHANIZE_CHROME_CONNECTION_STYLE }
|| $class->connection_style( \%options );
if( ! $options{ port } and ! $options{ pid } and ! $options{ reuse }) {
if( $options{ pipe } ) {
#if( $^O !~ /mswin32/i ) {
$connection_style = 'pipe';
};
};
if( ! exists $options{ pipe }) {
$options{ pipe } = 'pipe' eq $connection_style;
};
$options{ cleanup_signal } ||= $^O =~ /mswin32/i ? 'SIGKILL'
: $^O =~ /darwin/i ? 'SIGKILL'
: 'SIGTERM';
my $self= bless \%options => $class;
$self->{log} ||= $self->_build_log;
my( $to_chrome, $from_chrome );
if( $options{ pid } or $options{ reuse }) {
# Assume some defaults for the already running Chrome executable
$options{ port } //= 9222;
} else {
#if ( ! defined $options{ port } and ! $options{ pipe }) {
#unless ( defined $options{ port } ) {
# # Find free port for Chrome to listen on
# $options{ port } = $class->_find_free_port( 9222 );
#};
# We want Chrome to tell us the address to use
$options{ port } = 0;
my @cmd= $class->build_command_line( \%options );
$self->log('debug', "Spawning", \@cmd);
(my( $pid ), $to_chrome, $from_chrome, my $chrome_stdout )
= $self->spawn_child( $connection_style, @cmd );
$options{ writer_fh } = $to_chrome;
$options{ reader_fh } = $from_chrome;
$self->{pid} = $pid;
$self->{ kill_pid } = 1;
if( $connection_style eq 'pipe') {
$options{ writer_fh } = $to_chrome;
$options{ reader_fh } = $from_chrome;
} else {
if( $chrome_stdout ) {
# Synchronously wait for the URL we can connect to
# Maybe this should become part of the transport, or a second
# class to asynchronously wait on a filehandle?!
$options{ endpoint } = $self->read_devtools_url( $chrome_stdout );
close $chrome_stdout;
} else {
# Try a fresh socket connection, blindly
# Just to give Chrome time to start up, make sure it accepts connections
my $ok = $self->_wait_for_socket_connection(
$host,
$self->{port},
$self->{startup_timeout}
);
if( ! $ok) {
die join ' ',
"Timeout while connecting to $host:$self->{port}.",
"Do you maybe have a non-debug instance of Chrome",
"already running?";
};
};
};
};
my @connection;
if( 'pipe' eq $connection_style ) {
@connection = (
writer_fh => $options{ writer_fh },
reader_fh => $options{ reader_fh },
);
} elsif( $options{ endpoint }) {
@connection = (
endpoint => $options{ endpoint },
);
} else {
@connection = (
port => $options{ port },
host => $host,
);
};
# Connect to it via TCP or local pipe
$options{ driver_transport } ||= Chrome::DevToolsProtocol->new(
@connection,
transport => $options{ transport },
log => $options{ log },
);
$options{ target } ||= Chrome::DevToolsProtocol::Target->new(
auto_close => 0,
transport => delete $options{ driver_transport },
error_handler => sub {
#warn ref$_[0];
#warn "<<@CARP_NOT>>";
#warn ((caller($_))[0,1,2])
# for 1..4;
local @CARP_NOT = (@CARP_NOT, ref $_[0],'Try::Tiny');
# Reraise the error
croak $_[1]
},
#transport => $options{ transport },
log => $options{ log },
);
# Synchronously connect here, just for easy API compatibility
$self->_connect(%options);
$self
};
sub _setup_driver_future( $self, %options ) {
$self->target->connect(
new_tab => !$options{ reuse },
tab => $options{ tab },
#writer_fh => $options{ writer_fh },
#reader_fh => $options{ reader_fh },
)->catch( sub(@args) {
my $err = $args[0];
if( ref $args[1] eq 'HASH') {
$err .= $args[1]->{Reason};
};
Future->fail( $err );
})
}
# This (tries to) connects to the devtools in the browser
sub _connect( $self, %options ) {
my $err;
$self->_setup_driver_future( %options )
->catch( sub(@args) {