WWW/Mechanize/Chrome.pm

filter: Statementstmt 11.5% 231 / 1997 Branchbran 4.6% 41 / 874 Conditioncond 3.5% 23 / 645 MC/DCmcdc 0.2% 1 / 365 Subroutinesub 17.3% 54 / 312 Podpod 64.2% 104 / 162 totaltotal 10.4% 454 / 4355 CC 736 SCAR 59.3
CC
736
Cov
8%
build_command_line
2474.7
httpMessageFromEvents
1892.0
_match_any_link_params
1640.0
CRAP 377.9
↑ Summary Chrome/DevToolsProtocol/Target.pm »
1 package WWW::Mechanize::Chrome;
2 69 ▶use 5.020;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 69 ▶use experimental 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 69 ▶use stable 'postderef';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 69 ▶use feature 'current_sub';
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 69 ▶use PerlX::Maybe;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 69 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 69 ▶use HTTP::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 69 ▶use HTTP::Headers;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 69 ▶use Scalar::Util qw( blessed weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 69 ▶use File::Basename;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 69 ▶use Carp qw(croak carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 69 ▶use WWW::Mechanize::Link;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 69 ▶use IO::Socket::INET;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 69 ▶use Chrome::DevToolsProtocol;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 69 ▶use Chrome::DevToolsProtocol::Target;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 69 ▶use WWW::Mechanize::Chrome::Node;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 69 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 69 ▶use MIME::Base64 'decode_base64';
Subroutine BEGIN: called CC=1 SCAR=0.0
22 69 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 69 ▶use Storable 'dclone';
Subroutine BEGIN: called CC=1 SCAR=0.0
24 69 ▶use HTML::Selector::XPath 'selector_to_xpath';
Subroutine BEGIN: called CC=1 SCAR=0.0
25 69 ▶use HTTP::Cookies::ChromeDevTools;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 69 ▶use POSIX ':sys_wait_h';
Subroutine BEGIN: called CC=1 SCAR=0.0
27 #use Future::IO;
28 69 ▶use Future::Utils 'repeat';
Subroutine BEGIN: called CC=1 SCAR=0.0
29 69 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
30 69 ▶use Encode 'encode';
Subroutine BEGIN: called CC=1 SCAR=0.0
31 69 ▶use Text::ParseWords 'shellwords';
Subroutine BEGIN: called CC=1 SCAR=0.0
32 69 ▶use File::Temp 'tempdir';
Subroutine BEGIN: called CC=1 SCAR=0.0
33  
34 69 our $VERSION = '0.80';
35 69 our @CARP_NOT;
36  
37 # We don't yet inherit from Moo 2, so patch up things manually
38 69 ▶use parent 'MooX::Role::EventEmitter';
Subroutine BEGIN: called CC=1 SCAR=0.0
39  
40 # add Browser.setPermission , .grantPermission for
41 # restricting/allowing recording, clipboard, idleDetection, ...
42  
43 =encoding utf-8
44  
45 =head1 NAME
46  
47 WWW::Mechanize::Chrome - automate the Chrome browser
48  
49 =head1 SYNOPSIS
50  
51 use Log::Log4perl qw(:easy);
52 use WWW::Mechanize::Chrome;
53  
54 Log::Log4perl->easy_init($ERROR); # Set priority of root logger to ERROR
55 my $mech = WWW::Mechanize::Chrome->new();
56 $mech->get('https://google.com');
57  
58 $mech->eval_in_page('alert("Hello Chrome")');
59 my $png = $mech->content_as_png();
60  
61 A collection of other L<Examples|WWW::Mechanize::Chrome::Examples> is available
62 to help you get started.
63  
64 =head1 DESCRIPTION
65  
66 Like L<WWW::Mechanize>, this module automates web browsing with a Perl object.
67 Fetching and rendering of web pages is delegated to the Chrome (or Chromium)
68 browser by starting an instance of the browser and controlling it with L<Chrome
69 DevTools|https://developers.google.com/web/tools/chrome-devtools/>.
70  
71 =head2 Advantages Over L<WWW::Mechanize>
72  
73 The Chrome browser provides advanced abilities useful for automating modern
74 web applications that are not (yet) possible with L<WWW::Mechanize> alone:
75  
76 =over 4
77  
78 =item *
79  
80 Page content can be created or modified with JavaScript. You can also execute
81 custom JavaScript code on the page content.
82  
83 =item *
84  
85 Page content can be selected with CSS selectors.
86  
87 =item *
88  
89 Screenshots of the rendered page as an image or PDF file.
90  
91 =back
92  
93 =head2 Disadvantages
94  
95 Installation of a Chrome compatible browser is required. There are some quirks
96 including sporadic, but harmless, error messages issued by the browser when
97 run with with DevTools.
98  
99 =head2 A Brief Operational Overview
100  
101 C<WWW::Mechanize::Chrome> (WMC) leverages developer tools built into Chrome and
102 Chrome-like browsers to control a browser instance programmatically. You can use
103 WMC to automate tedious tasks, test web applications, and perform web scraping
104 operations.
105  
106 Typically, WMC is used to launch both a I<host> instance of the browser and
107 provide a I<client> instance of the browser. The host instance of the browser is
108 visible to you on your desktop (unless the browser is running in "headless"
109 mode, in which case it will not open in a window). The client instance is the
110 Perl program you write with the WMC module to issue commands to control the host
111 instance. As you navigate and "click" on various nodes in the client browser,
112 you watch the host browser respond to these actions as if by magic.
113  
114 This magic happens as a result of commands that are issued from your client to
115 the host using Chrome's DevTools Protocol which implements the http protocol to
116 send JSON data structures. The host also responds to the client with JSON to
117 describe the web pages it has loaded. WMC conveniently hides the complexity of
118 the lower level communications between the client and host browsers and wraps
119 them in a Perl object to provide the easy-to-use methods documented here.
120  
121 =head1 OPTIONS
122  
123 =head2 C<< WWW::Mechanize::Chrome->new( %options ) >>
124  
125 my $mech = WWW::Mechanize::Chrome->new(
126 headless => 0,
127 );
128  
129 =over 4
130  
131 =item B<autodie>
132  
133 autodie => 0 # make HTTP errors non-fatal
134  
135 By default, C<autodie> is set to true. If an HTTP error is encountered, the
136 program dies along with its associated browser instances. This frees you from
137 having to write error checks after every request. Setting this value to false
138 makes HTTP errors non-fatal, allowing the program to continue running if
139 there is an error.
140  
141 =item B<headless>
142  
143 Don't display a browser window. Default is to display a browser
144 window.
145  
146 =item B<host>
147  
148 =item B<listen_host>
149  
150 Set the host the browser listens on:
151  
152 host => '192.168.1.2'
153 host => 'localhost'
154  
155 Defaults to C<127.0.0.1>. The browser will listen for commands on the
156 specified host. The host address should be inaccessible from the internet.
157  
158 =item B<port>
159  
160 port => 9223 # set port the launched browser will use for remote operation
161  
162 Defaults to C<9222>. Commands to the browser will be issued through this port.
163  
164 =item B<tab>
165  
166 Specify the browser tab the Chrome browser will use:
167  
168 tab => 'current'
169 tab => qr/PerlMonks/
170  
171 By default, a web page is opened in a new browser tab. Setting C<tab> to
172 C<current> will use the current, active tab instead. Alternatively, to use an
173 existing inactive tab, you can pass a regular expression to match against the
174 existing tab's title. A false value implements the default behavior and a new
175 tab will be created.
176  
177 =item B<autoclose>
178  
179 autoclose => 0 # keep tab open after program end
180  
181 By default, C<autoclose> is set to true, closing the tab opened when running
182 your code. If C<autoclose> is set to a false value, the tab will remain open
183 even after the program has finished.
184  
185 =item B<launch_exe>
186  
187 Set the name and/or path to the browser's executable program:
188  
189 launch_exe => 'name-of-chrome-executable' # for non-standard executable names
190 launch_exe => '/path/to/executable' # for non-standard paths
191 launch_exe => '/path/to/executable/chrome' # full path
192  
193 By default, C<WWW::Mechanize::Chrome> will search the appropriate paths for
194 Chrome's executable file based on the operating system. Use this option to set
195 the path to your executable if it is in a non-standard location or if the
196 executable has a non-standard name.
197  
198 The default paths searched are those found in C<$ENV{PATH}>. For OS X, the user
199 and system C<Application> directories are also searched. The default values for
200 the executable file's name are C<chrome> on Windows, C<Google Chrome> on OS X,
201 and C<google-chrome> elsewhere.
202  
203 If you want to use Chromium, you must specify that explicitly with something
204 like:
205  
206 launch_exe => 'chromium-browser', # if Chromium is named chromium-browser on your OS
207  
208 Results my vary for your operating system. Use the full path to the browser's
209 executable if you are having issues. You can also set the name of the executable
210 file with the C<$ENV{CHROME_BIN}> environment variable.
211  
212 Additional arguments for the command are also read from the C<<$ENV{WWW_MECHANIZE_CHROME_ARGS}>>
213 variable and prepended to the C<launch_arg> array.
214  
215 =item B<cleanup_signal>
216  
217 cleanup_signal => 'SIGKILL'
218  
219 The signal that is sent to Chrome to shut it down. On Linuxish OSes, this
220 will be C<TERM>, on OSX and Windows it will be C<KILL>.
221  
222 =item B<start_url>
223  
224 start_url => 'http://perlmonks.org' # Immediately navigate to a given URL
225  
226 By default, the browser will open with a blank tab. Use the C<start_url> option
227 to open the browser to the specified URL. More typically, the C<< ->get >>
228 method is use to navigate to URLs. Using C<start_url> means you don't
229 get notified when the URL has finished loading.
230  
231 =item B<launch_arg>
232  
233 Pass additional switches and parameters to the browser's executable:
234  
235 launch_arg => [ "--some-new-parameter=foo", "--another-option" ]
236  
237 Examples of other useful parameters include:
238  
239 '--start-maximized',
240 '--window-size=1280x1696'
241 '--ignore-certificate-errors'
242  
243 '--disable-web-security',
244 '--allow-running-insecure-content',
245  
246 '--load-extension'
247 '--no-sandbox'
248  
249 If you don't want the browser to use your OS password store, add:
250  
251 '--password-store=basic'
252  
253 Also see
254 L<https://peter.sh/experiments/chromium-command-line-switches/>
255 for a list of command line arguments that Chrome actually has in the source
256 code.
257  
258 Additional arguments for the command are also read from the
259 C<<$ENV{WWW_MECHANIZE_CHROME_ARGS}>>
260 variable and prepended to the C<launch_arg> array.
261  
262  
263 =item B<separate_session>
264  
265 separate_session => 1 # create a new, empty session
266  
267 This creates an empty, fresh Chrome session without any cookies. Setting this
268 will disregard any B<data_directory> setting.
269  
270 =item B<incognito>
271  
272 incognito => 1 # open the browser in incognito mode
273  
274 Defaults to false. Set to true to launch the browser in incognito mode.
275  
276 Most likely, you want to use B<separate_session> instead.
277  
278 =item B<data_directory>
279  
280 data_directory => '/path/to/data/directory' # set the data directory
281  
282 By default, a temporary data directory is used. Use this setting to change the
283 base data directory for the browsing session.
284  
285 use File::Temp 'tempdir';
286 # create a fresh Chrome every time, this is the default
287 my $mech = WWW::Mechanize::Chrome->new(
288 data_directory => tempdir(CLEANUP => 1 ),
289 );
290  
291 Using the "main" Chrome cookies:
292  
293 my $mech = WWW::Mechanize::Chrome->new(
294 data_directory => '/home/corion/.config/chromium',
295 );
296  
297 =item B<profile>
298  
299 profile => 'ProfileDirectory' # set the profile directory
300  
301 By default, your current user profile directory is used. Use this setting
302 to change the profile directory for the browsing session.
303  
304 You will need to set the B<data_directory> as well, so that Chrome finds the
305 profile within the data directory. The profile directory/name itself needs
306 to be a single directory name, not the full path. That single directory name
307 will be relative to the data directory.
308  
309 =item B<wait_file>
310  
311 wait_file => "$tempdir/CrashpadMetrics-active.pma"
312  
313 When shutting down, wait until this file does not exist anymore or can be
314 deleted. This can help making sure that the Chrome process has really shut
315 down.
316  
317 =item B<startup_timeout>
318  
319 startup_timeout => 5 # set the startup timeout value
320  
321 Defaults to 20, the maximum number of seconds to wait for the browser to launch.
322 Higher or lower values can be set based on the speed of the machine. The
323 process attempts to connect to the browser once each second over the duration
324 of this setting.
325  
326 =item B<driver>
327  
328 driver => $driver_object # specify the driver object
329  
330 Use a L<Chrome::DevToolsProtocol::Target> object that has been manually constructed.
331  
332 =item B<report_js_errors>
333  
334 report_js_errors => 1 # turn javascript error reporting on
335  
336 Defaults to false. If true, tests for Javascript errors and warns after each
337 request are run. This is useful for testing with C<use warnings qw(fatal)>.
338  
339 =item B<mute_audio>
340  
341 mute_audio => 0 # turn sounds on
342  
343 Defaults to true (sound off). A false value turns the sound on.
344  
345 =item B<background_networking>
346  
347 background_networking => 1 # turn background networking on
348  
349 Defaults to false (off). A true value enables background networking.
350  
351 =item B<client_side_phishing_detection>
352  
353 client_side_phishing_detection => 1 # turn client side phishing detection on
354  
355 Defaults to false (off). A true value enables client side phishing detection.
356  
357 =item B<component_update>
358  
359 component_update => 1 # turn component updates on
360  
361 Defaults to false (off). A true value enables component updates.
362  
363 =item B<default_apps>
364  
365 default_apps => 1 # turn default apps on
366  
367 Defaults to false (off). A true value enables default apps.
368  
369 =item B<hang_monitor>
370  
371 hang_monitor => 1 # turn the hang monitor on
372  
373 Defaults to false (off). A true value enables the hang monitor.
374  
375 =item B<hide_scrollbars>
376  
377 hide_scrollbars => 1 # hide the scrollbars
378  
379 Defaults to false (off). A true value will hide the scrollbars.
380  
381 =item B<infobars>
382  
383 infobars => 1 # turn infobars on
384  
385 Defaults to false (off). A true value will turn infobars on.
386  
387 =item B<popup_blocking>
388  
389 popup_blocking => 1 # block popups
390  
391 Defaults to false (off). A true value will block popups.
392  
393 =item B<prompt_on_repost>
394  
395 prompt_on_repost => 1 # allow prompts when reposting
396  
397 Defaults to false (off). A true value will allow prompts when reposting.
398  
399 =item B<save_password_bubble>
400  
401 save_password_bubble => 1 # allow the display of the save password bubble
402  
403 Defaults to false (off). A true value allows the save password bubble to be
404 displayed.
405  
406 =item B<sync>
407  
408 sync => 1 # turn syncing on
409  
410 Defaults to false (off). A true value turns syncing on.
411  
412 =item B<web_resources>
413  
414 web_resources => 1 # turn web resources on
415  
416 Defaults to false (off). A true value turns web resources on.
417  
418 =item B<json_log_file>
419  
420 Filename to log all JSON communications to, one line per message/event/reply
421  
422 =item B<json_log_fh>
423  
424 Filehandle to log all JSON communications to, one line per message/event/reply
425  
426 Open this filehandle via
427  
428 open my $fh, '>:utf8', $logfilename
429 or die "Couldn't create '$logfilename': $!";
430  
431 =back
432  
433 The C<< $ENV{WWW_MECHANIZE_CHROME_TRANSPORT} >> variable can be set to a
434 different transport class to override the default L<transport
435 class|Chrome::DevToolsProtcol::Transport>. This is primarily used for testing
436 but can also help eliminate introducing bugs from the underlying websocket
437 implementation(s).
438  
439 The C<< $ENV{WWW_MECHANIZE_CHROME_CONNECTION_STYLE} >> variable can be set to
440 either C<websocket> or C<pipe> to specify the kind of transport that you
441 want to use.
442  
443 The C<pipe> transport is only available on unixish OSes and only with Chrome
444 v72 onwards.
445  
446 =head1 METHODS
447  
448 =cut
449  
450 4 ▶sub build_command_line {
Subroutine build_command_line: called CC=51 SCAR=78.1
Pod undocumented
451 4 my( $class, $options )= @_;
452  
453 4 my @program_names = $class->default_executable_names( $options->{launch_exe} );
454  
455 4 my( $program, $error) = $class->find_executable(\@program_names);
456 4 ▶ croak $error if ! $program;
Branch: 1 branch
BranchTrueFalseTotal
unless $program 4 0 4
457  
458 # Convert the path to an absolute filename, so we can chdir() later
459 0 ▶ $program = File::Spec->rel2abs( $program ) || $program;
Condition0%0/3
'File::Spec'->rel2abs($program) || $program
l!l&&r!l&&!r
000
MC/DC0%0/2
'File::Spec'->rel2abs($program) || $program
'File::Spec'->rel2abs($program) $program
Truth table0%0/3
A || B
A= 'File::Spec'->rel2abs($program)B= $program
ABresult
1X1
011
000
460  
461 0 my $is_root = ($> == 0);
462 0 ▶ $options->{ no_sandbox } = 1
Branch: 1 branch
BranchTrueFalseTotal
if $is_root 0 0 0
463 if $is_root; # We need this when running as root
464  
465 0 ▶ $options->{ launch_arg } //= [];
Condition0%0/2
$options->{"launch_arg"} //= []
l!l
00
MC/DC0%0/1
$options->{"launch_arg"} //= []
$options->{"launch_arg"}
Truth table0%0/2
A
A= $options->{"launch_arg"}
Aresult
11
00
466 0 ▶ $options->{ exclude_switches } ||= [];
Condition0%0/2
$options->{"exclude_switches"} ||= []
l!l
00
MC/DC0%0/1
$options->{"exclude_switches"} ||= []
$options->{"exclude_switches"}
Truth table0%0/2
A
A= $options->{"exclude_switches"}
Aresult
11
00
467  
468 0 ▶ if( my $env = $ENV{WWW_MECHANIZE_CHROME_ARGS}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $env = $ENV{"WWW_MECHANIZE_CHROME_ARGS"}) 0 0 0
469 0 unshift $options->{launch_arg}->@*, shellwords( $env );
470 }
471  
472 # We want to read back the URL we can use to talk to Chrome
473 0 ▶ if( $^O =~ /mswin/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O =~ /mswin/iu) 0 0 0
474 #push @{ $options->{launch_arg}}, '--v=0', '--enable-logging'; # v79 bad, v78 bad, v77 bad, v76 bad, v75 bad, v70 bad
475 0 push @{ $options->{launch_arg}}, '--v=0'; # v79 OK, v62 OK, v61 bad
476 };
477  
478 0 ▶ if( $options->{pipe}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{'pipe'}) { } 0 0 0
479 0 push @{ $options->{ launch_arg }}, "--remote-debugging-pipe";
480 } else {
481  
482 $options->{port} //= 9222
483 0 ▶ if ! exists $options->{port};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $options->{"port"} 0 0 0
Condition0%0/2
$options->{"port"} //= 9222
l!l
00
MC/DC0%0/1
$options->{"port"} //= 9222
$options->{"port"}
Truth table0%0/2
A
A= $options->{"port"}
Aresult
11
00
484  
485 0 ▶ if (exists $options->{port}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options->{"port"}) 0 0 0
486 0 ▶ $options->{port} ||= 0;
Condition0%0/2
$options->{"port"} ||= 0
l!l
00
MC/DC0%0/1
$options->{"port"} ||= 0
$options->{"port"}
Truth table0%0/2
A
A= $options->{"port"}
Aresult
11
00
487 0 push @{ $options->{ launch_arg }}, "--remote-debugging-port=$options->{ port }";
488 0 push @{ $options->{ launch_arg }}, "--remote-allow-origins=*";
489 };
490  
491 0 ▶ if ($options->{listen_host} || $options->{host} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"listen_host"} or $options->{"host"}) 0 0 0
Condition0%0/3
$options->{"listen_host"} or $options->{"host"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$options->{"listen_host"} or $options->{"host"}
$options->{"listen_host"} $options->{"host"}
Truth table0%0/3
A or B
A= $options->{"listen_host"}B= $options->{"host"}
ABresult
1X1
011
000
492 0 ▶ my $host = $options->{listen_host} || $options->{host};
Condition0%0/3
$options->{'listen_host'} || $options->{'host'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$options->{'listen_host'} || $options->{'host'}
$options->{'listen_host'} $options->{'host'}
Truth table0%0/3
A || B
A= $options->{'listen_host'}B= $options->{'host'}
ABresult
1X1
011
000
493 0 push @{ $options->{ launch_arg }}, "--remote-debugging-address=$host";
494 };
495 };
496  
497 0 ▶ if ($options->{incognito}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"incognito"}) 0 0 0
498 0 push @{ $options->{ launch_arg }}, "--incognito";
499 };
500  
501 0 ▶ if( ! exists $options->{data_directory}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options->{"data_directory"}) 0 0 0
502 0 $options->{data_directory} = tempdir( CLEANUP => 1 );
503 };
504  
505 0 ▶ if ($options->{data_directory}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"data_directory"}) 0 0 0
506 0 push @{ $options->{ launch_arg }}, "--user-data-dir=$options->{ data_directory }";
507 };
508  
509 0 ▶ if (my $profile = $options->{profile}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $profile = $options->{"profile"}) 0 0 0
510 0 ▶ if(! $options->{data_directory}) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $options->{'data_directory'}) { } 0 0 0
elsif ($profile =~ m([/\\])u) { } 0 0 0
511 0 croak "Cannot use the 'profile' option without also having 'data_directory'";
512 } elsif( $profile =~ m![/\\]! ) {
513 0 my $rel = File::Spec->rel2abs($profile, $options->{data_directory});
514 0 ▶ if( $rel =~ m![/\\]!) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rel =~ m([/\\])u) { } 0 0 0
515 0 croak "The 'profile' option may not contain the path separator";
516 } else {
517 0 $profile = $rel;
518 };
519 }
520  
521 0 push @{ $options->{ launch_arg }}, "--profile-directory=$profile";
522 };
523  
524 0 ▶ if( $options->{temp_profile}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"temp_profile"}) 0 0 0
525 0 ▶ if( $options->{profile} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"profile"}) 0 0 0
526 0 croak "Cannot use the 'profile' option together with 'temp_profile'";
527 }
528 0 push @{ $options->{ launch_arg }}, "--temp-profile";
529 }
530  
531 0 ▶ if( $options->{silent_launch}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"silent_launch"}) 0 0 0
532 0 push @{ $options->{ launch_arg }}, "--silent-launch";
533 }
534  
535 0 ▶ if( $options->{enable_automation}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"enable_automation"}) 0 0 0
536 0 push @{ $options->{ launch_arg }}, "--enable-automation";
537 };
538  
539 0 ▶ if( $options->{infobars}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"infobars"}) 0 0 0
540 0 push @{ $options->{ launch_arg }}, "--enable-infobars";
541 };
542  
543 0 ▶ if( ! exists $options->{enable_first_run} || ! $options->{enable_first_run}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options->{"enable_first_run"} and $options->{"enable_first_run"}) 0 0 0
Condition0%0/3
exists $options->{"enable_first_run"} and $options->{"enable_first_run"}
!ll&&!rl&&r
000
MC/DC0%0/2
exists $options->{"enable_first_run"} and $options->{"enable_first_run"}
exists $options->{"enable_first_run"} $options->{"enable_first_run"}
Truth table0%0/3
A and B
A= exists $options->{"enable_first_run"}B= $options->{"enable_first_run"}
ABresult
0X0
100
111
544 0 push @{ $options->{ launch_arg }}, "--no-first-run";
545 };
546  
547 0 ▶ if( ! exists $options->{mute_audio} || $options->{mute_audio}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not exists $options->{"mute_audio"} or $options->{"mute_audio"}) 0 0 0
Condition0%0/3
not exists $options->{"mute_audio"} or $options->{"mute_audio"}
l!l&&r!l&&!r
000
MC/DC0%0/2
not exists $options->{"mute_audio"} or $options->{"mute_audio"}
not exists $options->{"mute_audio"} $options->{"mute_audio"}
Truth table0%0/3
not(A) or B
A= not exists $options->{"mute_audio"}B= $options->{"mute_audio"}
ABresult
1X1
011
000
548 0 push @{ $options->{ launch_arg }}, "--mute-audio";
549 };
550  
551 0 ▶ if( ! exists $options->{default_browser_check} || $options->{default_browser_check}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not exists $options->{"default_browser_check"} or $options->{"default_browser_check"}) 0 0 0
Condition0%0/3
not exists $options->{"default_browser_check"} or $options->{"default_browser_check"}
l!l&&r!l&&!r
000
MC/DC0%0/2
not exists $options->{"default_browser_check"} or $options->{"default_browser_check"}
not exists $options->{"default_browser_check"} $options->{"default_browser_check"}
Truth table0%0/3
not(A) or B
A= not exists $options->{"default_browser_check"}B= $options->{"default_browser_check"}
ABresult
1X1
011
000
552 0 push @{ $options->{ launch_arg }}, "--no-default-browser-check";
553 };
554  
555 #my $no_sandbox = $options->{no_sandbox} || ! (exists $options->{no_zygote});
556 0 ▶ if( $options->{no_zygote}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"no_zygote"}) 0 0 0
557 0 push @{ $options->{ launch_arg }}, "--no-zygote";
558 };
559  
560 #my $no_sandbox = $options->{no_sandbox} || ! (exists $options->{no_zygote});
561 0 ▶ if( $options->{no_sandbox} || $is_root ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"no_sandbox"} or $is_root) 0 0 0
Condition0%0/3
$options->{"no_sandbox"} or $is_root
l!l&&r!l&&!r
000
MC/DC0%0/2
$options->{"no_sandbox"} or $is_root
$options->{"no_sandbox"} $is_root
Truth table0%0/3
A or B
A= $options->{"no_sandbox"}B= $is_root
ABresult
1X1
011
000
562 0 push @{ $options->{ launch_arg }}, "--no-sandbox";
563 };
564  
565 0 ▶ if( $options->{hide_scrollbars}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"hide_scrollbars"}) 0 0 0
566 0 push @{ $options->{ launch_arg }}, "--hide-scrollbars";
567 };
568  
569 # Yes, that name is horrible
570 0 ▶ if( $options->{safebrowsing_auto_update}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{'safebrowsing_auto_update'}) { } 0 0 0
571 } else {
572 0 push @{ $options->{ launch_arg }}, "--safebrowsing-disable-auto-update";
573 };
574  
575 0 ▶ if( exists $options->{disable_prompt_on_repost}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options->{"disable_prompt_on_repost"}) 0 0 0
576 0 carp "Option 'disable_prompt_on_repost' is deprecated, use prompt_on_repost instead";
577 0 $options->{prompt_on_repost} = !$options->{disable_prompt_on_repost};
578 };
579  
580 0 for my $option (qw(
581 background_networking
582 background_timer_throttling
583 backgrounding_occluded_windows
584 breakpad
585 default_apps
586 dev_shm_usage
587 domain_reliability
588 gpu
589 ipc_flooding_protection
590 client_side_phishing_detection
591 component_update
592 hang_monitor
593 popup_blocking
594 prompt_on_repost
595 renderer_backgrounding
596 sync
597 translate
598 web_resources
599 )) {
600 0 (my $optname = $option) =~ s!_!-!g;
601 0 ▶ if( ! exists $options->{$option}) {
Branch: 2 branches
BranchTrueFalseTotal
if (not exists $options->{$option}) { } 0 0 0
elsif (not my $value = delete $options->{$option}) { } 0 0 0
602 0 push @{ $options->{ launch_arg }}, "--disable-$optname";
603 } elsif( ! (my $value = delete $options->{$option})) {
604 0 push @{ $options->{ launch_arg }}, "--disable-$optname";
605 };
606 };
607  
608 0 push @{ $options->{ launch_arg }}, "--headless"
609 0 ▶ if $options->{ headless };
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"headless"} 0 0 0
610  
611 0 ▶ if( $options->{ app } ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($options->{'app'}) { } 0 0 0
elsif (my $dir = $options->{'app_dir'}) { } 0 0 0
elsif (exists $options->{'start_url'}) { } 0 0 0
612 0 ▶ $options->{start_url} //= 'data:text/html,<html></html>';
Condition0%0/2
$options->{"start_url"} //= "data:text/html,<html></html>"
l!l
00
MC/DC0%0/1
$options->{"start_url"} //= "data:text/html,<html></html>"
$options->{"start_url"}
Truth table0%0/2
A
A= $options->{"start_url"}
Aresult
11
00
613 0 push @{ $options->{ launch_arg }}, "--app=$options->{start_url}";
614  
615 } elsif( my $dir = $options->{ app_dir } ) {
616 # Be Electron-like
617 #$options->{start_url} //= 'data:text/html,<html></html>';
618 0 push @{ $options->{ launch_arg }}, "--load-and-launch-app=$dir";
619  
620 } elsif( exists $options->{start_url}) {
621 0 push @{ $options->{ launch_arg }}, "$options->{start_url}"
622 ;
623 }
624  
625 0 ▶ if( @{ $options->{exclude_switches}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$options->{"exclude_switches"};}) 0 0 0
626 0 push @{ $options->{ launch_arg }}, "--exclude-switches=" . join ",", @{ $options->{exclude_switches }}
627 }
628  
629 0 ▶ my $quoted_program = ($^O =~ /mswin/i and $program =~ /[\s|<>&]/)
Branch: 1 branch
BranchTrueFalseTotal
$^O =~ /mswin/iu && $program =~ /[\s|<>&]/u ? : 0 0 0
Condition0%0/3
$^O =~ /mswin/iu and $program =~ /[\s|<>&]/u
!ll&&!rl&&r
000
MC/DC0%0/2
$^O =~ /mswin/iu and $program =~ /[\s|<>&]/u
$^O =~ /mswin/iu $program =~ /[\s|<>&]/u
Truth table0%0/3
A and B
A= $^O =~ /mswin/iuB= $program =~ /[\s|<>&]/u
ABresult
0X0
100
111
630 ? qq("$program")
631 : $program;
632  
633 0 my @cmd=( $program, @{ $options->{launch_arg}} );
634  
635 @cmd
636 0 };
637  
638 =head2 C<< WWW::Mechanize::Chrome->find_executable >>
639  
640 my $chrome = WWW::Mechanize::Chrome->find_executable();
641  
642 my $chrome = WWW::Mechanize::Chrome->find_executable(
643 'chromium.exe',
644 '.\\my-chrome-66\\',
645 );
646  
647 my( $chrome, $diagnosis ) = WWW::Mechanize::Chrome->find_executable(
648 ['chromium-browser','google-chrome'],
649 './my-chrome-66/',
650 );
651 die $diagnosis if ! $chrome;
652  
653 Finds the first Chrome executable in the path (C<$ENV{PATH}>). For Windows, it
654 also looks in C<< $ENV{ProgramFiles} >>, C<< $ENV{ProgramFiles(x86)} >>
655 and C<< $ENV{"ProgramFilesW6432"} >>. For OSX it also looks in the user home
656 directory as given through C<< $ENV{HOME} >>.
657  
658 This is used to find the default Chrome executable if none was given through
659 the C<launch_exe> option or if the executable is given and does not exist
660 and does not contain a directory separator.
661  
662 =cut
663  
664 133 ▶sub default_executable_names( $class, @other ) {
Subroutine default_executable_names: called CC=4 SCAR=14.1
Pod undocumented
665 my @program_names
666 138 = grep { defined($_) } (
667 $ENV{CHROME_BIN},
668 133 @other,
669 );
670 133 ▶ if( ! @program_names ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@program_names) 131 2 133
671 131 ▶ push @program_names,
Branch: 2 branches
BranchTrueFalseTotal
$^O =~ /mswin/iu ? : 0 131 131
$^O =~ /darwin/iu ? : 0 131 131
672 $^O =~ /mswin/i ? 'chrome.exe'
673 : $^O =~ /darwin/i ? ('Google Chrome', 'Chromium')
674 : ('google-chrome', 'chromium-browser', 'chromium')
675 };
676 @program_names
677 133 }
678  
679 # Returns additional directories where the default executable can be found
680 # on this OS
681 132 ▶sub additional_executable_search_directories( $class, $os_style=$^O ) {
Subroutine additional_executable_search_directories: called CC=5 SCAR=22.7
Pod undocumented
682 132 my @search;
683 132 ▶ if( $os_style =~ /MSWin/i ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($os_style =~ /MSWin/iu) { } 0 132 132
elsif ($os_style =~ /darwin/iu) { } 0 132 132
684 push @search,
685 0 map { "$_\\Google\\Chrome\\Application\\" }
686 0 grep {defined}
687 ($ENV{'ProgramFiles'},
688 $ENV{'ProgramFiles(x86)'},
689 $ENV{"ProgramFilesW6432"},
690 0 $ENV{"LOCALAPPDATA"},
691 );
692 } elsif( $os_style =~ /darwin/i ) {
693 0 for my $path ('/Applications/Google Chrome.app/Contents/MacOS',
694 '/Applications/Chromium.app/Contents/MacOS') {
695 push @search,
696 0 grep { -d $_ }
697 $path,
698 0 $ENV{"HOME"} . "/$path";
699 };
700 }
701 @search
702 132 }
703  
704 133 ▶sub find_executable( $class, $program=[$class->default_executable_names], @search) {
Subroutine find_executable: called CC=10 SCAR=23.8
Pod documented
705 133 my $looked_for = '';
706 133 ▶ if( ! ref $program) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $program) 1 132 133
707 1 $program = [$program]
708 };
709 133 my $program_name = join ", ", map { qq('$_') } @$program;
710  
711 133 ▶ if( my($first_program) = grep { -x $_ } @$program) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($first_program) = grep({-x $_;} @$program)) 0 133 133
712 # We've got a complete path, done!
713 0 return $first_program
714 };
715  
716 # Not immediately found, so we need to search
717 133 my @without_path = grep { !m![/\\]! } @$program;
718  
719 133 ▶ if( @without_path) {
Branch: 1 branch
BranchTrueFalseTotal
if (@without_path) 132 1 133
720 132 push @search, File::Spec->path();
721 132 push @search, $class->additional_executable_search_directories();
722 132 $looked_for = ' in searchpath ' . join " ", @search;
723 };
724  
725 133 my $found;
726  
727 133 for my $path (@search) {
728 1300 for my $p (@without_path) {
729 3880 my $this = File::Spec->catfile( $path, $p );
730 3880 ▶ if( -x $this ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-x $this) 0 3880 3880
731 0 $found = $this;
732 0 last;
733 };
734 };
735 };
736  
737 133 ▶ if( wantarray ) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 133 0 133
738 133 my $msg;
739 133 ▶ if( ! $found) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($found) 133 0 133
740 133 $msg = "No executable like $program_name found$looked_for";
741 };
742 133 return $found, $msg
743 } else {
744 0 return $found
745 };
746 }
747  
748 0 ▶sub _find_free_port( $class, $start ) {
Subroutine _find_free_port: not called CC=2 SCAR=17.9
749 0 my $port = $start;
750 0 while (1) {
751 0 ▶ $port++, next unless IO::Socket::INET->new(
Branch: 1 branch
BranchTrueFalseTotal
unless "IO::Socket::INET"->new("Listen", 5, "Proto", "tcp", "Reuse", 1, "LocalPort", $port) 0 0 0
752 Listen => 5,
753 Proto => 'tcp',
754 Reuse => 1,
755 LocalPort => $port
756 );
757 0 last;
758 }
759 0 $port;
760 }
761  
762 0 ▶sub _wait_for_socket_connection( $class, $host, $port, $timeout=20 ) {
Subroutine _wait_for_socket_connection: not called CC=5 SCAR=34.0
763 0 my $res = 0;
764 0 my $wait = time + $timeout;
765 0 ▶ while ( time < $wait ) {
Branch: 1 branch
BranchTrueFalseTotal
if (time < $wait) 0 0 0
766 0 my $t = time;
767 0 my $socket = IO::Socket::INET->new(
768 PeerHost => $host,
769 PeerPort => $port,
770 Proto => 'tcp',
771 );
772 0 ▶ if( $socket ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($socket) 0 0 0
773 0 close $socket;
774 #Time::HiRes::sleep(0.5);
775 0 $res = 1;
776 0 last;
777 };
778 0 ▶ Time::HiRes::sleep(0.1) if time - $t < 1;
Branch: 1 branch
BranchTrueFalseTotal
if time - $t < 1 0 0 0
779 }
780  
781 0 return $res
782 };
783  
784 0 ▶sub spawn_child_win32( $self, $method, @cmd ) {
Subroutine spawn_child_win32: not called CC=2 SCAR=17.9
Pod undocumented
785 0 ▶ croak "Only websocket communication is supported on $^O, not '$method'"
Branch: 1 branch
BranchTrueFalseTotal
if $method ne "websocket" 0 0 0
786 if $method ne 'websocket';
787  
788 # Our store for the filehandles
789 0 my (%child, %parent);
790  
791 0 require IPC::Open3;
792 0 require Symbol;
793 0 $parent{child_output} = Symbol::gensym();
794 my $pid = IPC::Open3::open3(
795 undef, $parent{ child_output }, $parent{ child_output },
796 @cmd
797 0 );
798  
799 0 return $pid, $parent{write}, $parent{read}, $parent{child_output};
800 }
801  
802 0 ▶sub spawn_child_posix( $self, $method, @cmd ) {
Subroutine spawn_child_posix: not called CC=17 SCAR=57.2
Pod undocumented
803 0 require POSIX;
804 0 POSIX->import("setsid");
805  
806 # Our store for the filehandles
807 0 my (%child, %parent);
808  
809 0 ▶ if( $method eq 'pipe' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq 'pipe') { } 0 0 0
810 # Now, we want to have file handles with fileno=3 and fileno=4
811 # to talk to Chrome v72+
812  
813 # Just open some filehandles to push the filenos above 4 for sure:
814 0 open my $dummy_fh, '>', '/dev/null';
815 0 open my $dummy_fh2, '>', '/dev/null';
816  
817 0 pipe $child{read}, $parent{write};
818 0 pipe $parent{read}, $child{write};
819  
820 0 close $dummy_fh;
821 0 close $dummy_fh2;
822 } else {
823 # We want to read back the websocket URL from the STDOUT (well STDERR)
824 # of the child
825 0 pipe $parent{child_output}, $child{stdout};
826 0 $parent{child_output}->autoflush(1);
827 };
828  
829 # daemonize
830 0 ▶ defined(my $pid = fork()) || die "can't fork: $!";
Branch: 1 branch
BranchTrueFalseTotal
defined(my $pid = fork) or die "can't fork: $!" 0 0 0
831 0 ▶ if( $pid ) { # non-zero now means I am the parent
Branch: 1 branch
BranchTrueFalseTotal
if ($pid) 0 0 0
832  
833 # Close all child filehandles
834 0 for my $v (values(%child)) {
835 0 close $v;
836 };
837 0 return $pid, $parent{write}, $parent{read}, $parent{child_output};
838 };
839  
840 # We are the child, close about everything, then exec
841 0 ▶ chdir("/") || die "can't chdir to /: $!";
Branch: 1 branch
BranchTrueFalseTotal
chdir "/" or die "can't chdir to /: $!" 0 0 0
842 0 ▶ (setsid() != -1) || die "Can't start a new session: $!";
Branch: 1 branch
BranchTrueFalseTotal
setsid() != -1 or die "Can't start a new session: $!" 0 0 0
843 0 ▶ open(STDIN, "< /dev/null") || die "can't read /dev/null: $!";
Branch: 1 branch
BranchTrueFalseTotal
open STDIN, "< /dev/null" or die "can't read /dev/null: $!" 0 0 0
844 0 ▶ if( 'pipe' eq $method ) {
Branch: 1 branch
BranchTrueFalseTotal
if ('pipe' eq $method) { } 0 0 0
845 0 ▶ open(STDERR, ">&", STDOUT) || die "can't dup stdout: $!";
Branch: 1 branch
BranchTrueFalseTotal
open STDERR, ">&", "STDOUT" or die "can't dup stdout: $!" 0 0 0
846 0 ▶ open(STDOUT, "> /dev/null") || die "can't talk to new STDOUT: $!";
Branch: 1 branch
BranchTrueFalseTotal
open STDOUT, "> /dev/null" or die "can't talk to new STDOUT: $!" 0 0 0
847 } else {
848 0 ▶ open(STDERR, ">&", $child{stdout}) || die "can't dup stdout: $!";
Branch: 1 branch
BranchTrueFalseTotal
open STDERR, ">&", $child{"stdout"} or die "can't dup stdout: $!" 0 0 0
849 0 ▶ open(STDOUT, ">&", $child{stdout}) || die "can't talk to new STDOUT: $!";
Branch: 1 branch
BranchTrueFalseTotal
open STDOUT, ">&", $child{"stdout"} or die "can't talk to new STDOUT: $!" 0 0 0
850 };
851  
852 0 my ($from_chrome, $to_chrome);
853 0 local $^F;
854 0 ▶ if( $method eq 'pipe' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "pipe") 0 0 0
855 # We want handles 0,1,2,3,4 to be inherited by Chrome
856 0 $^F = 4;
857  
858 # Set up FD 3 and 4 for Chrome to read/write
859 0 ▶ open($from_chrome, '<&', $child{read})|| die "can't open reader pipe: $!";
Branch: 1 branch
BranchTrueFalseTotal
open $from_chrome, "<&", $child{"read"} or die "can't open reader pipe: $!" 0 0 0
860 0 ▶ open($to_chrome, '>&', $child{write}) || die "can't open writer pipe: $!";
Branch: 1 branch
BranchTrueFalseTotal
open $to_chrome, ">&", $child{"write"} or die "can't open writer pipe: $!" 0 0 0
861 }
862 0 for my $v (values(%parent)) {
863 0 close $v;
864 };
865 #close $parent{child_output};
866 0 exec @cmd;
867 0 warn "Child couldn't launch [@cmd]: $!";
868 0 exit 1;
869 }
870  
871 0 ▶sub spawn_child( $self, $method, @cmd ) {
Subroutine spawn_child: not called CC=2 SCAR=17.9
Pod undocumented
872 0 my ($pid, $to_chrome, $from_chrome, $chrome_stdout);
873 0 ▶ if( $^O =~ /mswin/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O =~ /mswin/iu) { } 0 0 0
874 0 ($pid,$to_chrome,$from_chrome, $chrome_stdout) = $self->spawn_child_win32($method, @cmd)
875 } else {
876 0 ($pid,$to_chrome,$from_chrome, $chrome_stdout) = $self->spawn_child_posix($method, @cmd)
877 };
878 0 $self->log('debug', "Spawned child as $pid, communicating via $method");
879  
880 0 return ($pid,$to_chrome,$from_chrome, $chrome_stdout)
881 }
882  
883 0 ▶sub read_devtools_url( $self, $fh, $lines = 50 ) {
Subroutine read_devtools_url: not called CC=11 SCAR=48.8
Pod undocumented
884 # We expect the output within the first 50 lines...
885 0 my $devtools_url;
886  
887 my %pids;
888 0 for my $pid ($self->{pid}->@*) {
889 0 $pids{ $pid }++;
890 }
891  
892 0 ▶ while( $lines-- and ! defined $devtools_url and ! eof($fh)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lines-- and not defined $devtools_url and not eof $fh) 0 0 0
Condition0%0/6
$lines-- and not defined $devtools_url and not eof $fh
!ll&&!rl&&r
000
$lines-- and not defined $devtools_url
!ll&&!rl&&r
000
MC/DC0%0/3
$lines-- and not defined $devtools_url and not eof $fh
$lines-- not defined $devtools_url not eof $fh
Truth table0%0/4
A and not(B) and not(C)
A= $lines--B= not defined $devtools_urlC= not eof $fh
ABCresult
0XX0
10X0
1100
1111
893 0 my $line = <$fh>;
894 0 ▶ last unless defined $line;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line 0 0 0
895 0 $line =~ s!\s+$!!;
896 0 $self->log('trace', "[[$line]]");
897 0 ▶ if( $line =~ m!^DevTools listening on (ws:\S+)$!) {
Branch: 3 branches
BranchTrueFalseTotal
if ($line =~ /^DevTools listening on (ws:\S+)$/u) { } 0 0 0
elsif ($line =~ /^\[(\d+):(\d+):/u) { } 0 0 0
elsif ($line =~ /ERROR:headless_shell.cc/u) { } 0 0 0
898 0 $devtools_url = $1;
899 0 $self->log('trace', "Found ws endpoint from child output as '$devtools_url'");
900 0 last;
901 } elsif( $line =~ m!^\[(\d+):(\d+):!) {
902 0 my $pid = $1;
903 0 ▶ if( !$pids{ $pid }++ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pids{$pid}++) 0 0 0
904 0 $self->log('trace', "Found a pid as '$pid', original pid is $self->{pid}->@*");
905 0 push $self->{pid}->@*, $pid;
906 };
907 } elsif( $line =~ m!ERROR:headless_shell.cc! ) {
908 0 die "Chrome launch error: $line";
909 }
910 };
911 0 $devtools_url
912 };
913  
914 1 ▶sub _build_log( $self ) {
Subroutine _build_log: called CC=1 SCAR=0.0
915 1 require Log::Log4perl;
916 1 Log::Log4perl->get_logger(__PACKAGE__);
917 }
918  
919 # The generation of node ids
920 0 ▶sub _generation( $self, $val=undef ) {
Subroutine _generation: not called CC=3 SCAR=24.8
921 0 ▶ if( defined $val ) { $self->{_generation} = $val; };
Branch: 1 branch
BranchTrueFalseTotal
if (defined $val) 0 0 0
922 $self->{_generation}
923 0 };
924  
925 0 ▶sub new_generation( $self ) {
Subroutine new_generation: not called CC=2 SCAR=17.9
Pod undocumented
926 0 ▶ $self->_generation( ($self->_generation() ||0) +1 );
Condition0%0/2
$self->_generation || 0
l!l
00
MC/DC0%0/1
$self->_generation || 0
$self->_generation
Truth table0%0/2
A
A= $self->_generation
Aresult
11
00
927 }
928  
929 0 ▶sub log( $self, $level, $message, @args ) {
Subroutine log: not called CC=3 SCAR=24.8
Pod undocumented
930 0 my $logger = $self->{log};
931 0 ▶ if( !@args ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not @args) { } 0 0 0
932 0 $logger->$level( $message )
933 } else {
934 0 my $enabled = "is_$level";
935 0 ▶ $logger->$level( join " ", $message, Dumper @args )
Branch: 1 branch
BranchTrueFalseTotal
if $logger->$enabled 0 0 0
936 if( $logger->$enabled );
937 };
938 }
939  
940 4 ▶sub _preferred_transport($class, $options) {
Subroutine _preferred_transport: called CC=4 SCAR=14.3
941 ref( $options->{ transport } )
942 || $options->{ transport }
943 || $ENV{ WWW_MECHANIZE_CHROME_TRANSPORT }
944 4 ▶ || 'Chrome::DevToolsProtocol::Transport'
Branch: 1 branch
BranchTrueFalseTotal
ref $options->{"transport"} or $options->{"transport"} or $ENV{"WWW_MECHANIZE_CHROME_TRANSPORT"} or "Chrome::DevToolsProtocol::Transport" 1 3 4
Condition66%4/6
ref $options->{"transport"} or $options->{"transport"} or $ENV{"WWW_MECHANIZE_CHROME_TRANSPORT"}
l!l&&r!l&&!r
103
ref $options->{"transport"} or $options->{"transport"}
l!l&&r!l&&!r
013
MC/DC33%1/3
ref $options->{"transport"} or $options->{"transport"} or $ENV{"WWW_MECHANIZE_CHROME_TRANSPORT"}
ref $options->{"transport"} $options->{"transport"} $ENV{"WWW_MECHANIZE_CHROME_TRANSPORT"}
Truth table50%2/4
A or B or C
A= ref $options->{"transport"}B= $options->{"transport"}C= $ENV{"WWW_MECHANIZE_CHROME_TRANSPORT"}
ABCresult
1XX1
01X1
0011
0000
945 }
946  
947 # Find out what connection style (websocket, pipe) the user wants:
948 1 ▶sub connection_style( $class, $options ) {
Subroutine connection_style: called CC=4 SCAR=15.6
Pod undocumented
949 1 ▶ if( $options->{pipe} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{'pipe'}) { } 0 1 1
950 0 return 'pipe'
951 } else {
952 1 my $t = $class->_preferred_transport($options);
953 1 ▶ eval "require $t; 1"
Branch: 1 branch
BranchTrueFalseTotal
eval "require $t; 1" or warn $@ 1 0 1
954 or warn $@;
955 1 ▶ return $t->new->type || 'websocket';
Condition50%1/2
$t->new->type || 'websocket'
l!l
10
MC/DC0%0/1
$t->new->type || 'websocket'
$t->new->type
Truth table50%1/2
A
A= $t->new->type
Aresult
11
00
956 };
957 };
958  
959 1 ▶sub new_future($class, %options) {
Subroutine new_future: called CC=41 SCAR=58.1
Pod undocumented
960  
961 1 ▶ if (! exists $options{ autodie }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options{"autodie"}) 1 0 1
962 1 $options{ autodie } = 1
963 };
964  
965 1 ▶ if (! exists $options{ autoclose }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options{"autoclose"}) 1 0 1
966 1 $options{ autoclose } = 1
967 };
968  
969 1 ▶ if (! exists $options{ autoclose_tab }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options{"autoclose_tab"}) 1 0 1
970 $options{ autoclose_tab } = $options{ autoclose }
971 1 };
972  
973 1 ▶ if( ! exists $options{ frames }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options{"frames"}) 1 0 1
974 1 $options{ frames }= 1;
975 };
976  
977 1 ▶ if( ! exists $options{ download_directory }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options{"download_directory"}) 1 0 1
978 1 $options{ download_directory }= '';
979 };
980  
981 1 ▶ $options{ startup_timeout } //= 20;
Condition50%1/2
$options{"startup_timeout"} //= 20
l!l
01
MC/DC0%0/1
$options{"startup_timeout"} //= 20
$options{"startup_timeout"}
Truth table50%1/2
A
A= $options{"startup_timeout"}
Aresult
11
00
982  
983 1 ▶ $options{ js_events } ||= [];
Condition50%1/2
$options{"js_events"} ||= []
l!l
01
MC/DC0%0/1
$options{"js_events"} ||= []
$options{"js_events"}
Truth table50%1/2
A
A= $options{"js_events"}
Aresult
11
00
984 1 ▶ if( ! exists $options{ transport }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options{"transport"}) 1 0 1
985 1 $options{ transport } = $class->_preferred_transport(\%options);
986 };
987  
988 $options{start_url} = 'about:blank'
989 1 ▶ unless exists $options{start_url};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $options{"start_url"} 1 0 1
990  
991 1 ▶ my $host = $options{ host } || '127.0.0.1';
Condition50%1/2
$options{'host'} || '127.0.0.1'
l!l
01
MC/DC0%0/1
$options{'host'} || '127.0.0.1'
$options{'host'}
Truth table50%1/2
A
A= $options{'host'}
Aresult
11
00
992 1 $options{ host } = $host;
993  
994 1 ▶ $options{ extra_headers } ||= {};
Condition50%1/2
$options{"extra_headers"} ||= {}
l!l
01
MC/DC0%0/1
$options{"extra_headers"} ||= {}
$options{"extra_headers"}
Truth table50%1/2
A
A= $options{"extra_headers"}
Aresult
11
00
995  
996 1 ▶ if( $options{ separate_session }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{'separate_session'}) { } 0 1 1
997 0 ▶ $options{ tab } ||= undef;
Condition0%0/2
$options{"tab"} ||= undef
l!l
00
MC/DC0%0/1
$options{"tab"} ||= undef
$options{"tab"}
Truth table0%0/2
A
A= $options{"tab"}
Aresult
11
00
998 } else {
999 1 ▶ $options{ tab } ||= 0;
Condition50%1/2
$options{"tab"} ||= 0
l!l
01
MC/DC0%0/1
$options{"tab"} ||= 0
$options{"tab"}
Truth table50%1/2
A
A= $options{"tab"}
Aresult
11
00
1000 }
1001 1 ▶ $options{ existing_tab } ||= defined $options{ tab };
Condition33%1/3
$options{"existing_tab"} ||= defined $options{"tab"}
l!l&&r!l&&!r
010
MC/DC0%0/2
$options{"existing_tab"} ||= defined $options{"tab"}
$options{"existing_tab"} defined $options{"tab"}
Truth table33%1/3
A ||= B
A= $options{"existing_tab"}B= defined $options{"tab"}
ABresult
1X1
011
000
1002  
1003 1 ▶ if( $options{ tab } and $options{ tab } eq 'current' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{"tab"} and $options{"tab"} eq "current") 0 1 1
Condition33%1/3
$options{"tab"} and $options{"tab"} eq "current"
!ll&&!rl&&r
100
MC/DC0%0/2
$options{"tab"} and $options{"tab"} eq "current"
$options{"tab"} $options{"tab"} eq "current"
Truth table33%1/3
A and B
A= $options{"tab"}B= $options{"tab"} eq "current"
ABresult
0X0
100
111
1004 # We will let Target.pm handle 'current' by looking for 'attached' or 'focused'
1005 };
1006  
1007 # Find out what connection style we need/the user wants
1008 my $connection_style = $options{ connection_style }
1009 || $ENV{ WWW_MECHANIZE_CHROME_CONNECTION_STYLE }
1010 1 ▶ || $class->connection_style( \%options );
Condition33%2/6
$options{'connection_style'} || $ENV{'WWW_MECHANIZE_CHROME_CONNECTION_STYLE'} || $class->connection_style(\%options)
l!l&&r!l&&!r
010
$options{"connection_style"} or $ENV{"WWW_MECHANIZE_CHROME_CONNECTION_STYLE"}
l!l&&r!l&&!r
001
MC/DC0%0/3
$options{'connection_style'} || $ENV{'WWW_MECHANIZE_CHROME_CONNECTION_STYLE'} || $class->connection_style(\%options)
$options{"connection_style"} $ENV{"WWW_MECHANIZE_CHROME_CONNECTION_STYLE"} $class->connection_style(\%options)
Truth table25%1/4
A or B || C
A= $options{"connection_style"}B= $ENV{"WWW_MECHANIZE_CHROME_CONNECTION_STYLE"}C= $class->connection_style(\%options)
ABCresult
1XX1
01X1
0011
0000
1011 1 ▶ if( ! $options{ port } and ! $options{ pid } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options{"port"} or $options{"pid"}) 1 0 1
Condition33%1/3
$options{"port"} or $options{"pid"}
l!l&&r!l&&!r
001
MC/DC0%0/2
$options{"port"} or $options{"pid"}
$options{"port"} $options{"pid"}
Truth table33%1/3
A or B
A= $options{"port"}B= $options{"pid"}
ABresult
1X1
011
000
1012 1 ▶ if( $options{ pipe } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{"pipe"}) 0 1 1
1013 #if( $^O !~ /mswin32/i ) {
1014 0 $connection_style = 'pipe';
1015 };
1016 };
1017 1 $options{ connection_style } = $connection_style;
1018  
1019 1 ▶ if( ! exists $options{ pipe }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options{"pipe"}) 1 0 1
1020 1 $options{ pipe } = 'pipe' eq $connection_style;
1021 };
1022  
1023 1 ▶ $options{ cleanup_signal } ||= $^O =~ /mswin32/i ? 'SIGKILL'
Branch: 2 branches
BranchTrueFalseTotal
$^O =~ /mswin32/iu ? : 0 1 1
$^O =~ /darwin/iu ? : 0 1 1
Condition33%1/3
$options{"cleanup_signal"} ||= $^O =~ /mswin32/iu ? "SIGKILL" : ($^O =~ /darwin/iu ? "SIGKILL" : "SIGTERM")
l!l&&r!l&&!r
010
MC/DC0%0/2
$options{"cleanup_signal"} ||= $^O =~ /mswin32/iu ? "SIGKILL" : ($^O =~ /darwin/iu ? "SIGKILL" : "SIGTERM")
$options{"cleanup_signal"} $^O =~ /mswin32/iu ? "SIGKILL" : ($^O =~ /darwin/iu ? "SIGKILL" : "SIGTERM")
Truth table33%1/3
A ||= B
A= $options{"cleanup_signal"}B= $^O =~ /mswin32/iu ? "SIGKILL" : ($^O =~ /darwin/iu ? "SIGKILL" : "SIGTERM")
ABresult
1X1
011
000
1024 : $^O =~ /darwin/i ? 'SIGKILL'
1025 : 'SIGTERM';
1026  
1027 1 ▶ my $self= bless \%options => (ref $class || $class);
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
010
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table33%1/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
1028  
1029 1 ▶ $self->{log} ||= $self->_build_log;
Condition33%1/3
$self->{"log"} ||= $self->_build_log
l!l&&r!l&&!r
010
MC/DC0%0/2
$self->{"log"} ||= $self->_build_log
$self->{"log"} $self->_build_log
Truth table33%1/3
A ||= B
A= $self->{"log"}B= $self->_build_log
ABresult
1X1
011
000
1030  
1031 1 ▶ if( $options{ pid } ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($options{'pid'}) { } 0 1 1
elsif ($options{'driver'} and $options{'driver_transport'}) { } 0 1 1
elsif ($options{'port'}) { } 0 1 1
1032 # Assume some defaults for the already running Chrome executable
1033 0 ▶ $options{ port } //= 9222;
Condition0%0/2
$options{"port"} //= 9222
l!l
00
MC/DC0%0/1
$options{"port"} //= 9222
$options{"port"}
Truth table0%0/2
A
A= $options{"port"}
Aresult
11
00
1034  
1035 ▶ } elsif ( $options{ driver } and $options{ driver_transport }) {
Condition33%1/3
$options{"driver"} and $options{"driver_transport"}
!ll&&!rl&&r
100
MC/DC0%0/2
$options{"driver"} and $options{"driver_transport"}
$options{"driver"} $options{"driver_transport"}
Truth table33%1/3
A and B
A= $options{"driver"}B= $options{"driver_transport"}
ABresult
0X0
100
111
1036 # We already have a connection to some Chrome running
1037  
1038 } elsif( $options{ port }) {
1039 # User has specified a port, so we will tell Chrome to use it
1040 # Check whether the port is readily available
1041 my $ok = $self->_wait_for_socket_connection(
1042 $host,
1043 $self->{port},
1044 0 2 # we don't need a long timeout here since Chrome either runs already
1045 # or we need to start it ourselves. But we seem to need two
1046 # seconds in most cases on my (fast) machine ...
1047 );
1048 # If not, launch Chrome with that debugging port
1049 0 ▶ if( ! $ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 0 0
1050 0 $self->log('debug', "No response on $host:$self->{ port }, launching fresh instance");
1051 0 $self->_spawn_new_chrome_instance( \%options );
1052 };
1053  
1054 } else {
1055 # We want Chrome to tell us the address to use
1056 1 $options{ port } = 0;
1057  
1058 1 $self->_spawn_new_chrome_instance( \%options );
1059 };
1060  
1061 0 my @connection;
1062 0 ▶ if( 'pipe' eq $connection_style ) {
Branch: 2 branches
BranchTrueFalseTotal
if ('pipe' eq $connection_style) { } 0 0 0
elsif ($options{'endpoint'}) { } 0 0 0
1063 @connection = (
1064 writer_fh => $options{ writer_fh },
1065 reader_fh => $options{ reader_fh },
1066 0 );
1067 } elsif( $options{ endpoint }) {
1068 @connection = (
1069 endpoint => $options{ endpoint },
1070 0 );
1071 } else {
1072 @connection = (
1073 port => $options{ port },
1074 0 host => $host,
1075 );
1076 };
1077  
1078 0 ▶ if( my $fn = delete $options{ json_log_file }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $fn = delete $options{"json_log_file"}) 0 0 0
1079 0 ▶ open $options{ json_log_fh }, '>:utf8', $fn
Branch: 1 branch
BranchTrueFalseTotal
open $options{"json_log_fh"}, ">:utf8", $fn or die "Couldn't create '${fn}': $!" 0 0 0
1080 or die "Couldn't create '$fn': $!";
1081 };
1082  
1083 # Connect to it via TCP or local pipe
1084 $options{ driver_transport } ||= Chrome::DevToolsProtocol->new(
1085 @connection,
1086 transport => $options{ transport },
1087 log => $options{ log },
1088 maybe json_log_fh => delete $options{ json_log_fh },
1089 0 ▶ );
Condition0%0/3
$options{"driver_transport"} ||= "Chrome::DevToolsProtocol"->new(@connection, "transport", $options{"transport"}, "log", $options{"log"}, &maybe("json_log_fh", scalar delete $options{"json_log_fh"}))
l!l&&r!l&&!r
000
MC/DC0%0/2
$options{"driver_transport"} ||= "Chrome::DevToolsProtocol"->new(@connection, "transport", $options{"transport"}, "log", $options{"log"}, &maybe("json_log_fh", scalar delete $options{"json_log_fh"}))
$options{"driver_transport"} "Chrome::DevToolsProtocol"->new(@connection, "transport", $options{"transport"}, "log", $options{"log"}, &maybe("json_log_fh", scalar delete $options{"json_log_fh"}))
Truth table0%0/3
A ||= B
A= $options{"driver_transport"}B= "Chrome::DevToolsProtocol"->new(@connection, "transport", $options{"transport"}, "log", $options{"log"}, &maybe("json_log_fh", scalar delete $options{"json_log_fh"}))
ABresult
1X1
011
000
1090 $options{ target } //= Chrome::DevToolsProtocol::Target->new(
1091 auto_close => 0,
1092 transport => delete $options{ driver_transport },
1093 0 ▶ error_handler => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1094 #warn ref$_[0];
1095 #warn "<<@CARP_NOT>>";
1096 #warn ((caller($_))[0,1,2])
1097 # for 1..4;
1098 0 local @CARP_NOT = (@CARP_NOT, ref $_[0],'Try::Tiny');
1099 # Reraise the error
1100 0 croak $_[1]
1101 },
1102 #transport => $options{ transport },
1103 #log => $options{ log },
1104 0 ▶ );
Condition0%0/3
$options{"target"} //= "Chrome::DevToolsProtocol::Target"->new("auto_close", 0, "transport", delete $options{"driver_transport"}, "error_handler", sub { local(@CARP_NOT) = (@CARP_NOT, ref $_[0], "Try::Tiny"); croak($_[1]); } )
l!l&&r!l&&!r
000
MC/DC0%0/2
$options{"target"} //= "Chrome::DevToolsProtocol::Target"->new("auto_close", 0, "transport", delete $options{"driver_transport"}, "error_handler", sub { local(@CARP_NOT) = (@CARP_NOT, ref $_[0], "Try::Tiny"); croak($_[1]); } )
$options{"target"} "Chrome::DevToolsProtocol::Target"->new("auto_close", 0, "transport", delete $options{"driver_transport"}, "error_handler", sub { local(@CARP_NOT) = (@CARP_NOT, ref $_[0], "Try::Tiny"); croak($_[1]); } )
Truth table0%0/3
A //= B
A= $options{"target"}B= "Chrome::DevToolsProtocol::Target"->new("auto_close", 0, "transport", delete $options{"driver_transport"}, "error_handler", sub { local(@CARP_NOT) = (@CARP_NOT, ref $_[0], "Try::Tiny"); croak($_[1]); } )
ABresult
1X1
011
000
1105  
1106 0 my $reuse_transport = delete $options{ reuse_transport };
1107 my $res = $self->_connect(
1108 reuse => $reuse_transport,
1109 %options,
1110 0 ▶ )->then(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1111 0 return Future->done( $self )
1112 0 });
1113  
1114 0 return $res
1115 };
1116  
1117 1 ▶sub _spawn_new_chrome_instance( $self, $options ) {
Subroutine _spawn_new_chrome_instance: called CC=5 SCAR=32.3
1118 1 my $class = ref $self;
1119 1 my @cmd = $class->build_command_line( $options );
1120 0 $self->log('debug', "Spawning for $options->{ connection_style }", \@cmd);
1121 (my( $pid , $to_chrome, $from_chrome, $chrome_stdout ))
1122 0 = $self->spawn_child( $options->{ connection_style }, @cmd );
1123 0 $options->{ writer_fh } = $to_chrome;
1124 0 $options->{ reader_fh } = $from_chrome;
1125 0 push $self->{pid}->@*, $pid;
1126 0 $self->{ kill_pid } = 1;
1127 0 ▶ if( $options->{ connection_style } eq 'pipe') {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{'connection_style'} eq 'pipe') { } 0 0 0
1128 0 $options->{ writer_fh } = $to_chrome;
1129 0 $options->{ reader_fh } = $from_chrome;
1130  
1131 } else {
1132 0 ▶ if( $chrome_stdout ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chrome_stdout) { } 0 0 0
1133 # Synchronously wait for the URL we can connect to
1134 # Maybe this should become part of the transport, or a second
1135 # class to asynchronously wait on a filehandle?!
1136 0 $options->{ endpoint } = $self->read_devtools_url( $chrome_stdout );
1137 0 close $chrome_stdout;
1138  
1139 0 ▶ if( ! $options->{endpoint} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options->{"endpoint"}) 0 0 0
1140 0 die join ' ',
1141 "Could not read websocket endpoint from Chrome output.",
1142 "Do you maybe have a non-debug instance of Chrome",
1143 "already running?"
1144 ;
1145 };
1146  
1147 # set up host/port here so it can be used later by other instances
1148 0 my $ws = URI->new( $options->{endpoint});
1149 0 $options->{port} = $ws->port;
1150 0 $options->{host} = $ws->host;
1151  
1152 } else {
1153  
1154 # Try a fresh socket connection, blindly
1155 # Just to give Chrome time to start up, make sure it accepts connections
1156 my $ok = $self->_wait_for_socket_connection(
1157 $options->{ host },
1158 $self->{port},
1159 $self->{startup_timeout}
1160 0 );
1161 0 ▶ if( ! $ok) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $ok) 0 0 0
1162 0 die join ' ',
1163 "Timeout while connecting to $options->{ host }:$self->{port}.",
1164 "Do you maybe have a non-debug instance of Chrome",
1165 "already running?";
1166 };
1167 };
1168 };
1169 }
1170  
1171 1 ▶sub new( $class, %args ) {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
1172 # Synchronously connect here, just for easy API compatibility
1173 1 return $class->new_future(%args)->get;
1174 }
1175  
1176 0 ▶sub _setup_driver_future( $self, %options ) {
Subroutine _setup_driver_future: not called CC=4 SCAR=26.3
1177 0 ▶ if( $options{ app_dir }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{"app_dir"}) 0 0 0
1178 # Give Chrome a second to start up, even if that means our App
1179 # starts slow
1180 0 sleep 1;
1181 };
1182  
1183 $self->target->connect(
1184 new_tab => !$options{ existing_tab } || $options{ new_tab },
1185 tab => $options{ tab },
1186 #reuse => $options{ reuse_transport },
1187 app => $options{ app_dir },
1188 separate_session => $options{ separate_session },
1189 start_url => $options{ start_url } ? "".$options{ start_url } : undef,
1190 0 ▶ )->catch( sub(@args) {
Subroutine __ANON__: not called CC=2 SCAR=12.2
1191 0 my $err = $args[0];
1192 0 ▶ if( ref $args[1] eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args[1] eq "HASH") 0 0 0
1193 0 ▶ use Data::Dumper; warn Dumper $args[1];
Subroutine BEGIN: called CC=1 SCAR=0.2
1194 0 $err .= $args[1]->{Reason};
1195 };
1196 0 Future->fail( $err );
1197 0 ▶ });
Branch: 1 branch
BranchTrueFalseTotal
$options{'start_url'} ? : 0 0 0
Condition0%0/3
!$options{'existing_tab'} || $options{'new_tab'}
l!l&&r!l&&!r
000
MC/DC0%0/2
!$options{'existing_tab'} || $options{'new_tab'}
!$options{'existing_tab'} $options{'new_tab'}
Truth table0%0/3
not(A) || B
A= !$options{'existing_tab'}B= $options{'new_tab'}
ABresult
1X1
011
000
1198 }
1199  
1200 # This (tries to) connects to the devtools in the browser
1201 0 ▶sub _connect( $self, %options ) {
Subroutine _connect: not called CC=4 SCAR=30.0
1202 0 my $err;
1203 my $setup = $self->_setup_driver_future( %options )
1204 0 ▶ ->catch( sub(@args) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1205 0 $err = $args[0];
1206 0 Future->fail( @args );
1207 0 });
1208  
1209 # if Chrome started, but so slow or unresponsive that we cannot connect
1210 # to it, kill it manually to avoid waiting for it indefinitely
1211 0 ▶ if ( $err ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 0 0 0
1212 0 ▶ if( $self->{ kill_pid } and $self->{ pid }->@*) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"kill_pid"} and @{$self->{"pid"}}) 0 0 0
Condition0%0/3
$self->{"kill_pid"} and @{$self->{"pid"}}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"kill_pid"} and @{$self->{"pid"}}
$self->{"kill_pid"} @{$self->{"pid"}}
Truth table0%0/3
A and B
A= $self->{"kill_pid"}B= @{$self->{"pid"}}
ABresult
0X0
100
111
1213 0 my $pids = $self->{ pid };
1214 0 $self->kill_child( 'SIGKILL', $pids, $self->{wait_file} );
1215 };
1216 0 croak $err;
1217 }
1218  
1219 # Create new world if needed
1220 # connect to current world/new world
1221  
1222 0 my $s = $self;
1223 0 weaken $s;
1224  
1225 0 ▶ my $res = $setup->then(sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1226 0 ▶ my $collect_JS_problems = sub( $msg ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1227 $s->_handleConsoleAPICall( $msg->{params} )
1228 0 };
1229 $s->{consoleAPIListener} =
1230 0 $s->add_listener( 'Runtime.consoleAPICalled', $collect_JS_problems );
1231 $s->{exceptionThrownListener} =
1232 0 $s->add_listener( 'Runtime.exceptionThrown', $collect_JS_problems );
1233 $s->{nodeGenerationChange} =
1234 0 ▶ $s->add_listener( 'DOM.attributeModified', sub { $s->new_generation() } );
Subroutine __ANON__: not called CC=1 SCAR=6.9
1235 0 $s->new_generation;
1236  
1237 my @setup = (
1238 $s->target->send_message('DOM.enable'),
1239 $s->target->send_message('Overlay.enable'),
1240 $s->target->send_message('Page.enable'), # capture DOMLoaded
1241 $s->target->send_message('Network.enable'), # capture network
1242 $s->target->send_message('Runtime.enable'), # capture console messages
1243 $s->target->send_message('Debugger.enable'), # capture "script compiled" messages
1244 $s->set_download_directory_future($s->{download_directory}),
1245  
1246 $s->_listen_for_popup_f(1),
1247  
1248 0 ▶ keys %{$options{ extra_headers }} ? $s->_set_extra_headers_future( %{$options{ extra_headers }} ) : (),
Branch: 1 branch
BranchTrueFalseTotal
keys %{$options{'extra_headers'};} ? : 0 0 0
1249  
1250 # do a dummy search so no nodeId 0 gets used (?!)
1251 # $s->_performSearch(query => '//'),
1252 );
1253  
1254 0 ▶ if( my $agent = delete $options{ user_agent }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $agent = delete $options{"user_agent"}) 0 0 0
1255 0 push @setup, $s->agent_future( $agent );
1256 };
1257 my $res = Future->wait_all(
1258 @setup,
1259 0 ▶ )->on_done(sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
1260  
1261 # ->get() doesn't have ->get_future() yet
1262 0 ▶ if( ! (exists $options{ tab } )) {
Branch: 2 branches
BranchTrueFalseTotal
if (not exists $options{'tab'}) { } 0 0 0
elsif ($options{'tab'} and $options{'tab'} eq 'current') { } 0 0 0
1263 0 $s->get($options{ start_url }); # Reset to clean state, also initialize our frame id
1264 ▶ } elsif( $options{ tab } and $options{ tab } eq 'current' ) {
Condition0%0/3
$options{"tab"} and $options{"tab"} eq "current"
!ll&&!rl&&r
000
MC/DC0%0/2
$options{"tab"} and $options{"tab"} eq "current"
$options{"tab"} $options{"tab"} eq "current"
Truth table0%0/3
A and B
A= $options{"tab"}B= $options{"tab"} eq "current"
ABresult
0X0
100
111
1265 # If we're reusing a tab, wait for it to have content?
1266 # Or at least give it a moment to stabilize if it was just activated
1267 }
1268  
1269 0 ▶ $s->{_fresh_document} = $s->add_listener('DOM.documentUpdated', sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1270 0 $s->{_currentNodeGeneration}++;
1271 0 $s->log('debug', "Need new node ids! Now: $s->{_currentNodeGeneration}");
1272 # Maybe simply ->clear_cached_document is enough?!
1273 0 $s->_clear_cached_document;
1274 0 });
1275 0 });
1276 0 return $res
1277 0 });
1278  
1279 0 return $res
1280 }
1281  
1282 0 ▶sub _handleConsoleAPICall( $self, $msg ) {
Subroutine _handleConsoleAPICall: not called CC=2 SCAR=17.9
1283 0 ▶ if( $self->{report_js_errors}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"report_js_errors"}) 0 0 0
1284 0 my $desc = $msg->{exceptionDetails}->{exception}->{description};
1285 0 my $loc = $msg->{exceptionDetails}->{stackTrace}->{callFrames}->[0]->{url};
1286 0 my $line = $msg->{exceptionDetails}->{stackTrace}->{callFrames}->[0]->{lineNumber};
1287 0 my $err = "$desc at $loc line $line";
1288 0 $self->log('error', $err);
1289 };
1290 0 push @{$self->{js_events}}, $msg;
1291 }
1292  
1293 0 ▶sub frameId( $self ) {
Subroutine frameId: not called CC=1 SCAR=6.9
Pod undocumented
1294 $self->{frameId}
1295 0 }
1296  
1297 0 ▶sub requestId( $self ) {
Subroutine requestId: not called CC=1 SCAR=6.9
Pod undocumented
1298 $self->{requestId}
1299 0 }
1300  
1301 =head2 C<< $mech->chrome_version >>
1302  
1303 print $mech->chrome_version;
1304  
1305 Synonym for C<< ->browser_version >>
1306  
1307 =cut
1308  
1309 =head2 C<< $mech->browser_version >>
1310  
1311 print $mech->browser_version;
1312  
1313 Returns the version of the browser executable being used. This information
1314 needs launching the browser and asking for the version via the network.
1315  
1316 =cut
1317  
1318 1 ▶sub browser_version_from_stdout( $class, $options={} ) {
Subroutine browser_version_from_stdout: called CC=6 SCAR=33.8
Pod undocumented
1319 # We can try to get at the version through the --version command line:
1320 my @cmd = $class->build_command_line({
1321 launch_arg => ['--version'],
1322 headless => 0,
1323 enable_automation => 0,
1324 port => undef,
1325 maybe launch_exe => $options->{launch_exe},
1326 1 });
1327 0 ▶ if ($^O =~ /darwin/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O =~ /darwin/u) 0 0 0
1328 0 s/ /\\ /g for @cmd;
1329 }
1330  
1331 0 my $v = readpipe(join " ", @cmd);
1332  
1333 # Chromium 58.0.3029.96 Built on Ubuntu , running on Ubuntu 14.04
1334 # Chromium 76.0.4809.100 built on Debian 10.0, running on Debian 10.0
1335 # Google Chrome 78.0.3904.97
1336 # Mozilla Firefox 87.0
1337 0 ▶ if( $v =~ m!^(.*?)\s+(\d+\.\d+\.\d+\.\d+)\b!) {
Branch: 2 branches
BranchTrueFalseTotal
if ($v =~ /^(.*?)\s+(\d+\.\d+\.\d+\.\d+)\b/u) { } 0 0 0
elsif ($v =~ m[^(Mozilla Firefox)[ /](\d+.\d+)\b]u) { } 0 0 0
1338 0 return "$1/$2"
1339 } elsif($v =~ m!^(Mozilla Firefox)[ /](\d+.\d+)\b!) {
1340 0 return "$1/$2.0.0"
1341 } else {
1342 0 return; # we didn't find anything
1343 }
1344 }
1345  
1346 0 ▶sub browser_version_from_executable_win32( $class, $options={} ) {
Subroutine browser_version_from_executable_win32: not called CC=6 SCAR=37.4
Pod undocumented
1347 0 require Win32::File::VersionInfo;
1348  
1349 0 ▶ my @names = ($options->{launch_exe} ? $options->{launch_exe}: ());
Branch: 1 branch
BranchTrueFalseTotal
$options->{'launch_exe'} ? : 0 0 0
1350 0 my ($program,$error) = $class->find_executable( @names );
1351 0 ▶ croak $error if $error;
Branch: 1 branch
BranchTrueFalseTotal
if $error 0 0 0
1352  
1353 0 my $info = Win32::File::VersionInfo::GetFileVersionInfo( $program );
1354  
1355 # Find whether we are Chrome* or MS Edge:
1356 0 (my $l) = sort (keys %{$info->{Lang}});
1357 0 my $name = $info->{Lang}->{ $l }->{"ProductName"};
1358 0 ▶ if( $name eq 'Microsoft Edge' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq 'Microsoft Edge') { } 0 0 0
1359 # Fudge the version to the equivalent Chrome API version
1360 0 my $v = $info->{ProductVersion};
1361 0 ▶ if( $v =~ /^11\./ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v =~ /^11\./u) { } 0 0 0
1362 0 $v = "72.0.0.0"; # random guess
1363 } else {
1364 0 $v = "78.0.0.0"; # even more random guess
1365 };
1366 0 return "Chrome/$v";
1367 } else {
1368 0 return "Chrome/$info->{ProductVersion}";
1369 };
1370 }
1371  
1372 1 ▶sub browser_version( $self, %options ) {
Subroutine browser_version: called CC=5 SCAR=25.2
Pod documented
1373 1 ▶ if( blessed $self and $self->target ) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($self) and $self->target) { } 0 1 1
elsif (not $^O =~ /mswin/iu) { } 1 0 1
Condition33%1/3
builtin::blessed($self) and $self->target
!ll&&!rl&&r
100
MC/DC0%0/2
builtin::blessed($self) and $self->target
builtin::blessed($self) $self->target
Truth table33%1/3
A and B
A= builtin::blessed($self)B= $self->target
ABresult
0X0
100
111
1374 0 return $self->chrome_version_info()->{product};
1375  
1376 } elsif( $^O !~ /mswin/i ) {
1377 1 my $version = $self->browser_version_from_stdout(\%options);
1378 0 ▶ if( $version ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($version) 0 0 0
1379 0 return $version;
1380 };
1381  
1382 } else {
1383 0 $self->browser_version_from_executable_win32( \%options )
1384 };
1385 }
1386  
1387 69 *chrome_version =
1388 *chrome_version = \&browser_version;
1389  
1390 =head2 C<< $mech->chrome_version_info >>
1391  
1392 print $mech->chrome_version_info->{product};
1393  
1394 Returns the version information of the Chrome executable and various other
1395 APIs of Chrome that the object is connected to.
1396  
1397 =cut
1398  
1399 0 ▶sub chrome_version_info( $self ) {
Subroutine chrome_version_info: not called CC=2 SCAR=17.9
Pod documented
1400 0 ▶ $self->{chrome_version} ||= do {
Condition0%0/3
$self->{"chrome_version"} ||= do { $self->target->getVersion->get }
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"chrome_version"} ||= do { $self->target->getVersion->get }
$self->{"chrome_version"} do { $self->target->getVersion->get }
Truth table0%0/3
A ||= B
A= $self->{"chrome_version"}B= do { $self->target->getVersion->get }
ABresult
1X1
011
000
1401 #$self->target->version_info->get;
1402 0 $self->target->getVersion->get;
1403 };
1404 }
1405  
1406 =head2 C<< $mech->driver >>
1407  
1408 B<deprecated> - use C<< ->target >> instead
1409  
1410 my $driver = $mech->driver
1411  
1412 Access the L<Chrome::DevToolsProtocol> instance connecting to Chrome.
1413  
1414 Deprecated, don't use this anymore. Most likely you want to use C<< ->target >>
1415 to talk to the Chrome tab or C<< ->transport >> to talk to the Chrome instance.
1416  
1417 =cut
1418  
1419 0 ▶sub driver {
Subroutine driver: not called CC=1 SCAR=6.9
Pod documented
1420 0 $_[0]->target
1421 };
1422  
1423 =head2 C<< $mech->target >>
1424  
1425 my $target = $mech->target
1426  
1427 Access the L<Chrome::DevToolsProtocol::Target> instance connecting to the
1428 Chrome tab we use.
1429  
1430 =cut
1431  
1432 1 ▶sub target {
Subroutine target: called CC=1 SCAR=0.0
Pod documented
1433 $_[0]->{target}
1434 1 };
1435  
1436 =head2 C<< $mech->transport >>
1437  
1438 my $transport = $mech->transport
1439  
1440 Access the L<Chrome::DevToolsProtocol::Transport> instance connecting to the
1441 Chrome instance.
1442  
1443 =cut
1444  
1445 0 ▶sub transport {
Subroutine transport: not called CC=1 SCAR=6.9
Pod documented
1446 0 $_[0]->driver->transport
1447 };
1448  
1449 =head2 C<< $mech->tab >>
1450  
1451 my $tab = $mech->tab
1452  
1453 Access the tab hash of the L<Chrome::DevToolsProtocol::Target> instance.
1454 This represents the tab we control.
1455  
1456 =cut
1457  
1458 0 ▶sub tab( $self ) {
Subroutine tab: not called CC=1 SCAR=6.9
Pod documented
1459 0 $self->target->tab
1460 }
1461  
1462 =head2 C<< $mech->new_tab >>
1463  
1464 =head2 C<< $mech->new_tab_future >>
1465  
1466 my $tab2 = $mech->new_tab_future(
1467 start_url => 'https://google.com',
1468 )->get;
1469  
1470 Creates a new tab (basically, a new WWW::Mechanize::Chrome object) connected
1471 to the same Chrome session.
1472  
1473 # Use a targetInfo structure from Chrome
1474 my $tab2 = $mech->new_tab_future(
1475 tab => {
1476 'targetId' => '1F42BDF32A30700805DDC21EDB5D8C4A',
1477 },
1478 )->get;
1479  
1480 It returns a L<Future> because most event loops do not like recursing within
1481 themselves, which happens if you want to access a fresh new tab within another
1482 callback.
1483  
1484 =cut
1485  
1486 0 ▶sub new_tab_future( $self, %options ) {
Subroutine new_tab_future: not called CC=2 SCAR=17.9
Pod documented
1487 0 ▶ my $new_tab = $options{ tab } ? undef : 1;
Branch: 1 branch
BranchTrueFalseTotal
$options{'tab'} ? : 0 0 0
1488 return $self->new_future(
1489 %options,
1490 maybe new_tab => $new_tab,
1491 headless => $self->{headless},
1492 0 driver => $self->driver,
1493 driver_transport => $self->transport,
1494 autoclose_tab => 1,
1495 );
1496 }
1497  
1498 0 ▶sub new_tab( $self, %options ) {
Subroutine new_tab: not called CC=1 SCAR=6.9
Pod documented
1499 0 $self->new_tab_future( %options )->get
1500 };
1501  
1502 =head1 EVENTS
1503  
1504 =head2 C<< popup >>
1505  
1506 my $opened;
1507 $mech->on( 'popup' => sub( $mech, $tab_f ) {
1508 # This is a bit heavyweight, but ...
1509 $tab_f->on_done(sub($tab) {
1510 say "New window/tab was popped up:";
1511 $tab->uri_future->then(sub($uri) {
1512 say $uri;
1513 });
1514 $opened = $tab;
1515 })->retain;
1516 });
1517  
1518 $mech->click({ selector => '#popup_window' });
1519 if( $opened ) {
1520 say $opened->title;
1521 } else {
1522 say "Did not find new tab?";
1523 };
1524  
1525 This event is sent whenever a new tab/window gets popped up or created. The
1526 callback is handed the current and a second WWW::Mechanize::Chrome instance.
1527 Note that depending on your event loop, you are quite restricted on what
1528 synchronous methods you can call from within the callback.
1529  
1530 =cut
1531  
1532 0 ▶sub _listen_for_popup_f( $self, $popup ) {
Subroutine _listen_for_popup_f: not called CC=2 SCAR=17.9
1533 0 my $res;
1534 0 ▶ if( $popup ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($popup) { } 0 0 0
1535 # Remember all known targets, because setDiscoverTargets will list all
1536 # existing targets too :-/
1537 0 my %known_targets;
1538 0 ▶ my $setup = $self->transport->getTargets()->then(sub( @targets ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1539 0 %known_targets = map { $_->{targetId} => 1 } @targets;
1540 0 Future->done(1);
1541 0 });
1542  
1543 0 weaken( my $s = $self );
1544 0 ▶ $self->{target_created} = $self->add_listener('Target.targetCreated' => sub($targetInfo) {
Subroutine __ANON__: not called CC=5 SCAR=34.0
1545  
1546 0 ▶ if( $s && $s->has_subscribers('popup') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s and $s->has_subscribers("popup")) 0 0 0
Condition0%0/3
$s and $s->has_subscribers("popup")
!ll&&!rl&&r
000
MC/DC0%0/2
$s and $s->has_subscribers("popup")
$s $s->has_subscribers("popup")
Truth table0%0/3
A and B
A= $sB= $s->has_subscribers("popup")
ABresult
0X0
100
111
1547 #use Data::Dumper; warn Dumper $targetInfo;
1548 0 my $id = $targetInfo->{params}->{targetInfo}->{targetId};
1549 0 ▶ if( $targetInfo->{params}->{targetInfo}->{type} eq 'page'
Branch: 1 branch
BranchTrueFalseTotal
if ($targetInfo->{'params'}{'targetInfo'}{'type'} eq 'page' and not $known_targets{$id}) { } 0 0 0
Condition0%0/3
$targetInfo->{"params"}{"targetInfo"}{"type"} eq "page" and not $known_targets{$id}
!ll&&!rl&&r
000
MC/DC0%0/2
$targetInfo->{"params"}{"targetInfo"}{"type"} eq "page" and not $known_targets{$id}
$targetInfo->{"params"}{"targetInfo"}{"type"} eq "page" not $known_targets{$id}
Truth table0%0/3
A and not(B)
A= $targetInfo->{"params"}{"targetInfo"}{"type"} eq "page"B= not $known_targets{$id}
ABresult
0X0
100
111
1550 && ! $known_targets{ $id }
1551 ) {
1552 0 my $tab = $s->new_tab_future( tab => $targetInfo->{params}->{targetInfo});
1553 0 $s->emit('popup', $tab);
1554 } else {
1555 # warn "...- already know it";
1556 };
1557 };
1558 0 });
1559  
1560 0 ▶ $res = $setup->then(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1561 0 $s->target->send_message('Target.setDiscoverTargets' => discover => JSON::true() )
1562 0 });
1563 } else {
1564 0 $res = $self->target->send_message('Target.setDiscoverTargets' => discover => JSON::false() );
1565 0 delete $self->{target_created};
1566 };
1567  
1568 0 return $res
1569 };
1570  
1571 0 ▶sub autodie {
Subroutine autodie: not called CC=2 SCAR=17.9
Pod documented
1572 0 my( $self, $val )= @_;
1573 0 ▶ $self->{autodie} = $val
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 2 0 0 0
1574 if @_ == 2;
1575 $_[0]->{autodie}
1576 0 }
1577  
1578 =head2 C<< $mech->allow( %options ) >>
1579  
1580 $mech->allow( javascript => 1 );
1581  
1582 Allow or disallow execution of Javascript
1583  
1584 =cut
1585  
1586 0 ▶sub allow {
Subroutine allow: not called CC=3 SCAR=24.8
Pod documented
1587 0 my($self,%options)= @_;
1588  
1589 0 my @await;
1590 0 ▶ if( exists $options{ javascript } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options{"javascript"}) 0 0 0
1591 0 ▶ my $disabled = !$options{ javascript } ? JSON::true : JSON::false;
Branch: 1 branch
BranchTrueFalseTotal
!$options{'javascript'} ? : 0 0 0
1592 0 push @await,
1593 $self->target->send_message('Emulation.setScriptExecutionDisabled', value => $disabled );
1594 };
1595  
1596 0 Future->wait_all( @await )->get;
1597 }
1598  
1599 =head2 C<< $mech->emulateNetworkConditions( %options ) >>
1600  
1601 # Go offline
1602 $mech->emulateNetworkConditions(
1603 offline => JSON::true,
1604 latency => 10, # ms ping
1605 downloadThroughput => 0, # bytes/s
1606 uploadThroughput => 0, # bytes/s
1607 connectionType => 'offline', # cellular2g, cellular3g, cellular4g, bluetooth, ethernet, wifi, wimax, other.
1608 );
1609  
1610 =cut
1611  
1612 0 ▶sub emulateNetworkConditions_future( $self, %options ) {
Subroutine emulateNetworkConditions_future: not called CC=5 SCAR=34.0
Pod undocumented
1613 $options{ offline } //= JSON::false,
1614 $options{ latency } //= -1,
1615 $options{ downloadThroughput } //= -1,
1616 0 ▶ $options{ uploadThroughput } //= -1,
Condition0%0/9
$options{"offline"} //= JSON::false()
l!l&&r!l&&!r
000
$options{"latency"} //= -1
l!l
00
$options{"downloadThroughput"} //= -1
l!l
00
$options{"uploadThroughput"} //= -1
l!l
00
MC/DC0%0/2
$options{"offline"} //= JSON::false()
$options{"offline"} JSON::false()
MC/DC0%0/1
$options{"latency"} //= -1
$options{"latency"}
MC/DC0%0/1
$options{"downloadThroughput"} //= -1
$options{"downloadThroughput"}
MC/DC0%0/1
$options{"uploadThroughput"} //= -1
$options{"uploadThroughput"}
Truth table0%0/3
A //= B
A= $options{"offline"}B= JSON::false()
ABresult
1X1
011
000
Truth table0%0/2
A
A= $options{"latency"}
Aresult
11
00
Truth table0%0/2
A
A= $options{"downloadThroughput"}
Aresult
11
00
Truth table0%0/2
A
A= $options{"uploadThroughput"}
Aresult
11
00
1617 $self->target->send_message('Network.emulateNetworkConditions', %options)
1618 }
1619  
1620 0 ▶sub emulateNetworkConditions( $self, %options ) {
Subroutine emulateNetworkConditions: not called CC=1 SCAR=6.9
Pod documented
1621 0 $self->emulateNetworkConditions_future( %options )->get
1622 }
1623  
1624 =head2 C<< $mech->setRequestInterception( @patterns ) >>
1625  
1626 $mech->setRequestInterception(
1627 { urlPattern => '*', resourceType => 'Document', interceptionStage => 'Request'},
1628 { urlPattern => '*', resourceType => 'Media', interceptionStage => 'Response'},
1629 );
1630  
1631 Sets the list of request patterns and resource types for which the interception
1632 callback will be invoked.
1633  
1634 =cut
1635  
1636 0 ▶sub setRequestInterception_future( $self, @patterns ) {
Subroutine setRequestInterception_future: not called CC=1 SCAR=6.9
Pod undocumented
1637 0 $self->target->send_message('Network.setRequestInterception', patterns => \@patterns)
1638 }
1639  
1640 0 ▶sub setRequestInterception( $self, @patterns ) {
Subroutine setRequestInterception: not called CC=1 SCAR=6.9
Pod documented
1641 0 $self->setRequestInterception_future( @patterns )->get
1642 }
1643  
1644 =head2 C<< $mech->continueInterceptedRequest( %options ) >>
1645  
1646 $mech->continueInterceptedRequest_future(
1647 interceptionId => ...
1648 );
1649  
1650 Continues an intercepted request
1651  
1652 =cut
1653  
1654 0 ▶sub continueInterceptedRequest_future( $self, %options ) {
Subroutine continueInterceptedRequest_future: not called CC=1 SCAR=6.9
Pod undocumented
1655 0 $self->target->send_message('Network.continueInterceptedRequest', %options)
1656 }
1657  
1658 0 ▶sub continueInterceptedRequest( $self, %options ) {
Subroutine continueInterceptedRequest: not called CC=1 SCAR=6.9
Pod documented
1659 0 $self->continueInterceptedRequest_future( %options )->get
1660 }
1661  
1662 =head2 C<< $mech->add_listener >>
1663  
1664 my $url_loaded = $mech->add_listener('Network.responseReceived', sub {
1665 my( $info ) = @_;
1666 warn "Loaded URL "
1667 . $info->{params}->{response}->{url}
1668 . ": "
1669 . $info->{params}->{response}->{status};
1670 warn "Resource timing: " . Dumper $info->{params}->{response}->{timing};
1671 });
1672  
1673 Returns a listener object. If that object is discarded, the listener callback
1674 will be removed.
1675  
1676 Calling this method in void context croaks.
1677  
1678 To see the browser console live from your Perl script, use the following:
1679  
1680 my $console = $mech->add_listener('Runtime.consoleAPICalled', sub {
1681 warn join ", ",
1682 map { $_->{value} // $_->{description} }
1683 @{ $_[0]->{params}->{args} };
1684 });
1685  
1686 If you want to explicitly remove the listener, either set it to C<undef>:
1687  
1688 undef $console;
1689  
1690 Alternatively, call
1691  
1692 $console->unregister;
1693  
1694 or call
1695  
1696 $mech->remove_listener( $console );
1697  
1698 =cut
1699  
1700 0 ▶sub add_listener( $self, $event, $callback ) {
Subroutine add_listener: not called CC=2 SCAR=17.9
Pod documented
1701 0 ▶ if( ! defined wantarray ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined wantarray) 0 0 0
1702 0 croak "->add_listener called in void context."
1703 . "Please store the result somewhere";
1704 };
1705 0 return $self->target->add_listener( $event, $callback )
1706 }
1707  
1708 0 ▶sub remove_listener( $self, $listener ) {
Subroutine remove_listener: not called CC=1 SCAR=6.9
Pod undocumented
1709 0 $listener->unregister
1710 }
1711  
1712 =head2 C<< $mech->on_request_intercepted( $cb ) >>
1713  
1714 $mech->on_request_intercepted( sub {
1715 my( $mech, $info ) = @_;
1716 warn $info->{request}->{url};
1717 $mech->continueInterceptedRequest_future(
1718 interceptionId => $info->{interceptionId}
1719 )
1720 });
1721  
1722 A callback for intercepted requests that match the patterns set up
1723 via C<setRequestInterception>.
1724  
1725 If you return a future from this callback, it will not be discarded but kept in
1726 a safe place.
1727  
1728 =cut
1729  
1730 0 ▶sub on_request_intercepted( $self, $cb ) {
Subroutine on_request_intercepted: not called CC=2 SCAR=17.9
Pod documented
1731 0 ▶ if( $cb ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cb) { } 0 0 0
1732 0 my $s = $self;
1733 0 weaken $s;
1734 $self->{ on_request_intercept_listener } =
1735 0 ▶ $self->add_listener('Network.requestIntercepted', sub( $ev ) {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1736 0 ▶ if( $s->{ on_request_intercepted }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s->{"on_request_intercepted"}) 0 0 0
1737 $s->log('debug', sprintf 'Request intercepted %s: %s',
1738 $ev->{params}->{interceptionId},
1739 0 $ev->{params}->{request}->{url});
1740 0 $s->{ on_request_intercepted }->( $s, $ev->{params} );
1741 };
1742 0 });
1743 } else {
1744 0 delete $self->{ on_request_intercept_listener };
1745 };
1746 0 $self->{ on_request_intercepted } = $cb;
1747 }
1748  
1749 =head2 C<< $mech->searchInResponseBody( $id, %options ) >>
1750  
1751 my $request_id = ...;
1752 my @matches = $mech->searchInResponseBody(
1753 requestId => $request_id,
1754 query => 'rumpelstiltskin',
1755 caseSensitive => JSON::true,
1756 isRegex => JSON::false,
1757 );
1758 for( @matches ) {
1759 print $_->{lineNumber}, ":", $_->{lineContent}, "\n";
1760 };
1761  
1762 Returns the matches (if any) for a string or regular expression within
1763 a response.
1764  
1765 =cut
1766  
1767 0 ▶sub searchInResponseBody_future( $self, %options ) {
Subroutine searchInResponseBody_future: not called CC=1 SCAR=6.9
Pod undocumented
1768 $self->target->send_message('Network.searchInResponseBody', %options)
1769 0 ▶ ->then(sub( $res ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1770 0 return Future->done( @{ $res->{result}} )
1771 })
1772 0 }
1773  
1774 0 ▶sub searchInResponseBody( $self, @patterns ) {
Subroutine searchInResponseBody: not called CC=1 SCAR=6.9
Pod documented
1775 0 $self->searchInResponseBody_future( @patterns )->get
1776 }
1777  
1778 =head2 C<< $mech->on_dialog( $cb ) >>
1779  
1780 $mech->on_dialog( sub {
1781 my( $mech, $dialog ) = @_;
1782 warn $dialog->{message};
1783 $mech->handle_dialog( 1 ); # click "OK" / "yes" instead of "cancel"
1784 });
1785  
1786 A callback for Javascript dialogs (C<< alert() >>, C<< prompt() >>, ... )
1787  
1788 =cut
1789  
1790 0 ▶sub on_dialog( $self, $cb ) {
Subroutine on_dialog: not called CC=2 SCAR=17.9
Pod documented
1791 0 ▶ if( $cb ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cb) { } 0 0 0
1792 0 my $s = $self;
1793 0 weaken $s;
1794 $self->{ on_dialog_listener } =
1795 0 ▶ $self->add_listener('Page.javascriptDialogOpening', sub( $ev ) {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1796 0 ▶ if( $s->{ on_dialog }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s->{"on_dialog"}) 0 0 0
1797 0 $s->log('debug', sprintf 'Javascript %s: %s', $ev->{params}->{type}, $ev->{params}->{message});
1798 0 $s->{ on_dialog }->( $s, $ev->{params} );
1799 };
1800 0 });
1801 } else {
1802 0 delete $self->{ on_dialog_listener };
1803 };
1804 0 $self->{ on_dialog } = $cb;
1805 }
1806  
1807 =head2 C<< $mech->handle_dialog( $accept, $prompt = undef ) >>
1808  
1809 $mech->on_dialog( sub {
1810 my( $mech, $dialog ) = @_;
1811 warn "[Javascript $dialog->{type}]: $dialog->{message}";
1812 $mech->handle_dialog( 1 ); # click "OK" / "yes" instead of "cancel"
1813 });
1814  
1815 Closes the current Javascript dialog.
1816  
1817 =cut
1818  
1819 0 ▶sub handle_dialog( $self, $accept, $prompt = undef ) {
Subroutine handle_dialog: not called CC=4 SCAR=30.0
Pod documented
1820 0 ▶ my $v = $accept ? JSON::true : JSON::false;
Branch: 1 branch
BranchTrueFalseTotal
$accept ? : 0 0 0
1821 0 $self->log('debug', sprintf 'Dismissing Javascript dialog with %d', $accept);
1822 0 ▶ $self->target->send_message(
Branch: 1 branch
BranchTrueFalseTotal
defined $prompt ? : 0 0 0
1823 'Page.handleJavaScriptDialog',
1824 accept => $v,
1825 promptText => (defined $prompt ? $prompt : 'generic message'),
1826 )->retain;
1827 };
1828  
1829 =head2 C<< $mech->js_console_entries() >>
1830  
1831 print $_->{type}, " ", $_->{message}, "\n"
1832 for $mech->js_console_entries();
1833  
1834 An interface to the Javascript Error Console
1835  
1836 Returns the list of entries in the JEC
1837  
1838 =cut
1839  
1840 0 ▶sub js_console_entries( $self ) {
Subroutine js_console_entries: not called CC=1 SCAR=6.9
Pod documented
1841 0 @{$self->{js_events}}
1842 }
1843  
1844 =head2 C<< $mech->js_errors() >>
1845  
1846 print "JS error: ", $_->{message}, "\n"
1847 for $mech->js_errors();
1848  
1849 Returns the list of errors in the JEC
1850  
1851 =cut
1852  
1853 0 ▶sub js_errors {
Subroutine js_errors: not called CC=2 SCAR=17.9
Pod documented
1854 0 my ($self) = @_;
1855 0 ▶ grep { ($_->{type} || '') ne 'log' } $self->js_console_entries
Condition0%0/2
$_->{'type'} || ''
l!l
00
MC/DC0%0/1
$_->{'type'} || ''
$_->{'type'}
Truth table0%0/2
A
A= $_->{'type'}
Aresult
11
00
1856 }
1857  
1858 =head2 C<< $mech->clear_js_errors() >>
1859  
1860 $mech->clear_js_errors();
1861  
1862 Clears all Javascript messages from the console
1863  
1864 =cut
1865  
1866 0 ▶sub clear_js_errors {
Subroutine clear_js_errors: not called CC=1 SCAR=6.9
Pod documented
1867 0 my ($self) = @_;
1868 0 @{$self->{js_events}} = ();
1869 0 $self->target->send_message('Runtime.discardConsoleEntries')->get;
1870 };
1871  
1872 =head2 C<< $mech->eval_in_page( $str, %options ) >>
1873  
1874 =head2 C<< $mech->eval( $str, %options ) >>
1875  
1876 my ($value, $type) = $mech->eval( '2+2' );
1877  
1878 Evaluates the given Javascript fragment in the
1879 context of the web page.
1880 Returns a pair of value and Javascript type.
1881  
1882 This allows access to variables and functions declared
1883 "globally" on the web page.
1884  
1885 =over 4
1886  
1887 =item returnByValue
1888  
1889 If you want to create an object in Chrome and only want to keep a handle to that
1890 remote object, use C<JSON::false> for the C<returnByValue> option:
1891  
1892 my ($dummyObj,$type) = $mech->eval(
1893 'new Object',
1894 returnByValue => JSON::false
1895 );
1896  
1897 This is also helpful if the object in Chrome cannot be serialized as JSON.
1898 For example, C<window> is such an object. The return value is a hash, whose
1899 C<objectId> is the most interesting part.
1900  
1901 =back
1902  
1903 This method is special to WWW::Mechanize::Chrome.
1904  
1905 =cut
1906  
1907 0 ▶sub eval_in_page_future($self,$str, %options) {
Subroutine eval_in_page_future: not called CC=1 SCAR=6.9
Pod undocumented
1908 # Report errors from scope of caller
1909 # This feels weirdly backwards here, but oh well:
1910 local @Chrome::DevToolsProtocol::CARP_NOT
1911 0 = (@Chrome::DevToolsProtocol::CARP_NOT, (ref $self)); # we trust this
1912 local @CARP_NOT
1913 0 = (@CARP_NOT, 'Chrome::DevToolsProtocol', (ref $self)); # we trust this
1914 0 return $self->target->evaluate("$str", %options);
1915 }
1916  
1917 0 ▶sub eval_in_page( $self, $str, %options) {
Subroutine eval_in_page: not called CC=4 SCAR=30.0
Pod documented
1918 0 my $result = $self->eval_in_page_future("$str", %options)->get;
1919 0 ▶ if( $result->{error} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($result->{'error'}) { } 0 0 0
elsif ($result->{'exceptionDetails'}) { } 0 0 0
1920 $self->signal_condition(
1921 0 join "\n", grep { defined $_ }
1922 $result->{error}->{message},
1923 $result->{error}->{data},
1924 $result->{error}->{code}
1925 0 );
1926 } elsif( $result->{exceptionDetails} ) {
1927 $self->signal_condition(
1928 0 join "\n", grep { defined $_ }
1929 $result->{exceptionDetails}->{text},
1930 $result->{exceptionDetails}->{exception}->{description},
1931 0 );
1932 }
1933  
1934 0 ▶ if( exists $result->{result}->{value}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $result->{'result'}{'value'}) { } 0 0 0
1935 0 return $result->{result}->{value}, $result->{result}->{type};
1936 } else {
1937 0 return $result->{result}, $result->{result}->{type};
1938 }
1939 };
1940  
1941 {
1942 69 ▶ no warnings 'once';
Subroutine BEGIN: called CC=1 SCAR=0.0
1943 69 *eval = \&eval_in_page;
1944 69 *eval_future = \&eval_in_page_future;
1945 }
1946  
1947 =head2 C<< $mech->eval_in_chrome $code, @args >>
1948  
1949 $mech->eval_in_chrome(<<'JS', "Foobar/1.0");
1950 this.settings.userAgent= arguments[0]
1951 JS
1952  
1953 Evaluates Javascript code in the context of Chrome.
1954  
1955 This allows you to modify properties of Chrome.
1956  
1957 This is currently not implemented.
1958  
1959 =cut
1960  
1961 0 ▶sub eval_in_chrome {
Subroutine eval_in_chrome: not called CC=1 SCAR=6.9
Pod documented
1962 0 my ($self, $code, @args) = @_;
1963 0 croak "Can't call eval_in_chrome";
1964 };
1965  
1966 =head2 C<< $mech->callFunctionOn( $function, @arguments ) >>
1967  
1968 my ($value, $type) = $mech->callFunctionOn(
1969 'function(greeting) { window.alert(greeting)}',
1970 objectId => $someObjectId,
1971 arguments => [{ value => 'Hello World' }]
1972 );
1973  
1974 Runs the given function with the specified arguments. This is the only way to
1975 pass arguments to a function call without doing risky string interpolation.
1976 The Javascript C<this> object will be set to the object referenced from the
1977 C<objectId>.
1978  
1979 The C<arguments> option expects an arrayref of hashrefs. Each hash describes one
1980 function argument.
1981  
1982 The C<objectId> parameter is optional. Leaving out the C<objectId> parameter
1983 will create a dummy object on which the function then is called.
1984  
1985 This method is special to WWW::Mechanize::Chrome.
1986  
1987 =cut
1988  
1989 0 ▶sub callFunctionOn_future( $self, $str, %options ) {
Subroutine callFunctionOn_future: not called CC=2 SCAR=17.9
Pod undocumented
1990 # Report errors from scope of caller
1991 # This feels weirdly backwards here, but oh well:
1992 local @Chrome::DevToolsProtocol::CARP_NOT
1993 0 = (@Chrome::DevToolsProtocol::CARP_NOT, (ref $self)); # we trust this
1994 local @CARP_NOT
1995 0 = (@CARP_NOT, 'Chrome::DevToolsProtocol', (ref $self)); # we trust this
1996  
1997 0 my $objId;
1998 0 ▶ if( ! $options{ objectId }) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $options{'objectId'}) { } 0 0 0
1999 $objId = $self->target->evaluate('new Object',
2000 returnByValue => JSON::false
2001 0 ▶ )->then(sub($result) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2002 0 return Future->done( $result->{result}->{objectId});
2003 0 });
2004 } else {
2005 0 $objId = Future->done( $options{ objectId });
2006 };
2007  
2008 0 ▶ $objId->then( sub( $objectId ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2009 0 $options{ objectId } = $objectId;
2010 0 $self->target->callFunctionOn($str, %options)
2011 0 ▶ })->then( sub( $result ) {
Subroutine __ANON__: not called CC=4 SCAR=30.0
2012  
2013 0 ▶ if( $result->{error} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($result->{'error'}) { } 0 0 0
elsif ($result->{'exceptionDetails'}) { } 0 0 0
2014 $self->signal_condition(
2015 0 join "\n", grep { defined $_ }
2016 $result->{error}->{message},
2017 $result->{error}->{data},
2018 $result->{error}->{code}
2019 0 );
2020 } elsif( $result->{exceptionDetails} ) {
2021 $self->signal_condition(
2022 0 join "\n", grep { defined $_ }
2023 $result->{exceptionDetails}->{text},
2024 $result->{exceptionDetails}->{exception}->{description},
2025 0 );
2026 }
2027 0 ▶ if( exists $result->{result}->{value}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $result->{'result'}{'value'}) { } 0 0 0
2028 0 return Future->done( $result->{result}->{value}, $result->{result}->{type} );
2029 } else {
2030 0 return Future->done( $result->{result}, $result->{result}->{type} );
2031 }
2032 })
2033 0 };
2034  
2035 0 ▶sub callFunctionOn {
Subroutine callFunctionOn: not called CC=1 SCAR=6.9
Pod documented
2036 0 my ($self,$str, %options) = @_;
2037 # Report errors from scope of caller
2038 # This feels weirdly backwards here, but oh well:
2039 local @Chrome::DevToolsProtocol::CARP_NOT
2040 0 = (@Chrome::DevToolsProtocol::CARP_NOT, (ref $self)); # we trust this
2041 local @CARP_NOT
2042 0 = (@CARP_NOT, 'Chrome::DevToolsProtocol', (ref $self)); # we trust this
2043 0 $self->callFunctionOn_future($str, %options)->get;
2044 };
2045  
2046 {
2047 69 ▶ no warnings 'once';
Subroutine BEGIN: called CC=1 SCAR=0.0
2048 69 *eval = \&eval_in_page;
2049 }
2050  
2051 0 ▶sub agent_future( $self, $ua ) {
Subroutine agent_future: not called CC=1 SCAR=6.9
Pod undocumented
2052 0 $self->target->send_message('Network.setUserAgentOverride', userAgent => $ua )
2053 }
2054  
2055 0 ▶sub agent( $self, $ua ) {
Subroutine agent: not called CC=2 SCAR=17.9
Pod undocumented
2056 0 ▶ if( $ua ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ua) 0 0 0
2057 0 $self->agent_future( $ua )->get;
2058 };
2059  
2060 0 $self->chrome_version_info->{"User-Agent"}
2061 }
2062  
2063 =head2 C<< ->autoclose_tab >>
2064  
2065 Set the `autoclose_tab` option
2066  
2067 =cut
2068  
2069 0 ▶sub autoclose_tab( $self, $autoclose_tab ) {
Subroutine autoclose_tab: not called CC=1 SCAR=6.9
Pod documented
2070 0 $self->{autoclose_tab} = $autoclose_tab
2071 }
2072  
2073 =head2 C<< ->close >>
2074  
2075 $mech->close()
2076  
2077 Tear down all connections and shut down Chrome.
2078  
2079 =cut
2080  
2081 69 my @closing;
2082 1 ▶sub close {
Subroutine close: called CC=10 SCAR=37.6
Pod documented
2083 1 my $pids = delete $_[0]->{pid};
2084 #if( $_[0]->{autoclose} and $_[0]->tab and my $tab_id = $_[0]->tab->{id} ) {
2085 # $_[0]->target->close_tab({ id => $tab_id })->get();
2086 #};
2087 1 ▶ if( $_[0]->{autoclose_tab} and $_[0]->target and $_[0]->tab ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_[0]{"autoclose_tab"} and $_[0]->target and $_[0]->tab) 0 1 1
Condition33%2/6
$_[0]{"autoclose_tab"} and $_[0]->target and $_[0]->tab
!ll&&!rl&&r
100
$_[0]{"autoclose_tab"} and $_[0]->target
!ll&&!rl&&r
010
MC/DC0%0/3
$_[0]{"autoclose_tab"} and $_[0]->target and $_[0]->tab
$_[0]{"autoclose_tab"} $_[0]->target $_[0]->tab
Truth table25%1/4
A and B and C
A= $_[0]{"autoclose_tab"}B= $_[0]->targetC= $_[0]->tab
ABCresult
0XX0
10X0
1100
1111
2088 0 my $c = $_[0]->target->close;
2089 0 $c->set_label('close()');
2090 0 ▶ if( ${^GLOBAL_PHASE} eq 'DESTRUCT' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (${^GLOBAL_PHASE} eq 'DESTRUCT') { } 0 0 0
2091 0 $c->retain();
2092 } else {
2093 0 eval {
2094 0 ▶ local $SIG{ALRM} = sub { die "Timeout" };
Subroutine __ANON__: not called CC=1 SCAR=6.9
2095 0 alarm(1);
2096 0 $c->get;
2097 0 alarm(0);
2098 };
2099 0 ▶ if( $@ && $@ =~ /Timeout/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ and $@ =~ /Timeout/u) 0 0 0
Condition0%0/3
$@ and $@ =~ /Timeout/u
!ll&&!rl&&r
000
MC/DC0%0/2
$@ and $@ =~ /Timeout/u
$@ $@ =~ /Timeout/u
Truth table0%0/3
A and B
A= $@B= $@ =~ /Timeout/u
ABresult
0X0
100
111
2100 0 warn "Tab closure timed out";
2101 }
2102 }
2103 };
2104  
2105 #if( $pid and $_[0]->{cached_version} > 65) {
2106 # # Try a graceful shutdown
2107 # $_[0]->target->send_message('Browser.close' )->get
2108 #};
2109  
2110 1 local $@;
2111 1 eval {
2112 # Shut down our websocket connection
2113 1 ▶ if( $_[0]->{ driver }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_[0]{"driver"}) 0 1 1
2114 # This ruins too much of our infrastructure
2115 # We want to keep the connection open and maybe only call
2116 # ->close() from their DESTROY?!
2117 #$_[0]->{ driver }->close
2118 };
2119 };
2120 1 delete $_[0]->{ driver };
2121  
2122 1 ▶ if( $_[0]->{autoclose} and $_[0]->{kill_pid} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_[0]{"autoclose"} and $_[0]{"kill_pid"}) 0 1 1
Condition33%1/3
$_[0]{"autoclose"} and $_[0]{"kill_pid"}
!ll&&!rl&&r
010
MC/DC0%0/2
$_[0]{"autoclose"} and $_[0]{"kill_pid"}
$_[0]{"autoclose"} $_[0]{"kill_pid"}
Truth table33%1/3
A and B
A= $_[0]{"autoclose"}B= $_[0]{"kill_pid"}
ABresult
0X0
100
111
2123 0 $_[0]->kill_child( $_[0]->{cleanup_signal}, $pids, $_[0]->{wait_file} );
2124 }
2125 }
2126  
2127 0 ▶sub kill_child( $self, $signal, $pids, $wait_file ) {
Subroutine kill_child: not called CC=15 SCAR=54.8
Pod undocumented
2128 0 ▶ if( $pids and kill 0 => $pids->@*) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pids and kill 0, @$pids) 0 0 0
Condition0%0/3
$pids and kill 0, @$pids
!ll&&!rl&&r
000
MC/DC0%0/2
$pids and kill 0, @$pids
$pids kill 0, @$pids
Truth table0%0/3
A and B
A= $pidsB= kill 0, @$pids
ABresult
0X0
100
111
2129 0 local $SIG{CHLD} = 'IGNORE';
2130 0 undef $!;
2131 0 ▶ if( ! kill $signal => $pids->@* ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not kill($signal, @$pids)) { } 0 0 0
2132 # The child already has gone away?!
2133 0 warn "Couldn't kill browser child process $pids->@* with $self->{cleanup_signal}: $!";
2134 # Gobble up any exit status
2135 0 warn waitpid -1, WNOHANG;
2136 } else {
2137  
2138 0 ▶ if( $^O =~ /darwin/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O =~ /darwin/iu) { } 0 0 0
2139 # Busy-wait until the kid has gone away since on OSX this caused
2140 # infinite hangs at least on Travis CI !?
2141 0 my $timeout = time+2;
2142 0 ▶ while( time < $timeout ) {
Branch: 1 branch
BranchTrueFalseTotal
if (time < $timeout) 0 0 0
2143 0 my $res = waitpid $pids->[0], WNOHANG;
2144 0 ▶ if( $res != -1 and $res != $pids->[0] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res != -1 and $res != $pids->[0]) { } 0 0 0
Condition0%0/3
$res != -1 and $res != $pids->[0]
!ll&&!rl&&r
000
MC/DC0%0/2
$res != -1 and $res != $pids->[0]
$res != -1 $res != $pids->[0]
Truth table0%0/3
A and B
A= $res != -1B= $res != $pids->[0]
ABresult
0X0
100
111
2145 0 ▶ warn "Couldn't wait for child '$pids->@*' ($res)?"
Branch: 1 branch
BranchTrueFalseTotal
if $res != 0 0 0 0
2146 if $res != 0;
2147 0 sleep 0.1;
2148 } else {
2149 0 last;
2150 };
2151 };
2152 } else {
2153 # on Linux and Windows, plain waitpid Just Works
2154 0 waitpid $pids->[0], 0;
2155 # but still, check again that the child has really gone away:
2156 0 my $timeout = time+2;
2157 0 ▶ while( time < $timeout ) {
Branch: 1 branch
BranchTrueFalseTotal
if (time < $timeout) 0 0 0
2158 0 my $res = kill 0 => $pids->@*;
2159 0 ▶ if( $res ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res) { } 0 0 0
2160 0 sleep 0.1;
2161 } else {
2162 0 last;
2163 };
2164 };
2165  
2166 };
2167 };
2168  
2169 0 ▶ if( my $path = $wait_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $path = $wait_file) 0 0 0
2170 0 my $timeout = time + 10;
2171 0 ▶ while( time < $timeout ) {
Branch: 1 branch
BranchTrueFalseTotal
if (time < $timeout) 0 0 0
2172 0 ▶ last unless(-e $path);
Branch: 1 branch
BranchTrueFalseTotal
unless -e $path 0 0 0
2173 0 ▶ unlink($path) and last;
Branch: 1 branch
BranchTrueFalseTotal
unlink $path and last 0 0 0
2174 0 $self->sleep(0.1);
2175 }
2176 };
2177 };
2178 }
2179  
2180 1 ▶sub DESTROY {
Subroutine DESTROY: called CC=1 SCAR=0.0
2181 1 $_[0]->close();
2182 1 %{ $_[0] }= (); # clean out all other held references
2183 }
2184  
2185 =head2 C<< $mech->list_tabs >>
2186  
2187 my @open_tabs = $mech->list_tabs()->get;
2188 say $open_tabs[0]->{title};
2189  
2190 Returns the open tabs as a list of hashrefs.
2191  
2192 =cut
2193  
2194 0 ▶sub list_tabs( $self ) {
Subroutine list_tabs: not called CC=1 SCAR=6.9
Pod documented
2195 0 $self->transport->getTargets;
2196 }
2197  
2198 =head2 C<< $mech->highlight_node( @nodes ) >>
2199  
2200 my @links = $mech->selector('a');
2201 $mech->highlight_node(@links);
2202 print $mech->content_as_png();
2203  
2204 Convenience method that marks all nodes in the arguments
2205 with a red frame.
2206  
2207 This is convenient if you need visual verification that you've
2208 got the right nodes.
2209  
2210 =cut
2211  
2212 0 ▶sub highlight_nodes($self, @nodes) {
Subroutine highlight_nodes: not called CC=2 SCAR=17.9
Pod undocumented
2213 0 foreach my $node (@nodes) {
2214 0 $self->callFunctionOn(
2215 'function() {
2216 if( "none" == this.style.display ) {
2217 this.style.display= "block";
2218 };
2219 this.style.backgroundColor = "red";
2220 this.style.border = "solid black 1px"
2221 }',
2222 objectId => $node->objectId,
2223 arguments => []
2224 );
2225 }
2226 }
2227  
2228 =head1 NAVIGATION METHODS
2229  
2230 =head2 C<< $mech->get( $url, %options ) >>
2231  
2232 my $response = $mech->get( $url );
2233  
2234 Retrieves the URL C<URL>.
2235  
2236 It returns a L<HTTP::Response> object for interface compatibility
2237 with L<WWW::Mechanize>.
2238  
2239 Note that the returned L<HTTP::Response> object gets the response body
2240 filled in lazily, so you might have to wait a moment to get the response
2241 body from the result. This is a premature optimization and later releases of
2242 WWW::Mechanize::Chrome are planned to fetch the response body immediately when
2243 accessing the response body.
2244  
2245 Note that Chrome does not support download of files through the API.
2246  
2247 =head3 Options
2248  
2249 =over 4
2250  
2251 =item *
2252  
2253 C<intrapage> - Override the detection of whether to wait for a HTTP response
2254 or not. Setting this will never wait for an HTTP response.
2255  
2256 =back
2257  
2258 =cut
2259  
2260 0 ▶sub update_response($self, $response) {
Subroutine update_response: not called CC=1 SCAR=6.9
Pod undocumented
2261 0 $self->log('trace', 'Updated response object');
2262 0 $self->invalidate_cached_values;
2263 0 $self->{response} = $response;
2264 }
2265  
2266 =head2 C<< $mech->_collectEvents >>
2267  
2268 my $events = $mech->_collectEvents(
2269 sub { $_[0]->{method} eq 'Page.loadEventFired' }
2270 );
2271 my( $e,$r) = Future->wait_all( $events, $self->target->send_message(...));
2272  
2273 Internal method to create a Future that waits for an event that is sent by Chrome.
2274  
2275 The subroutine is the predicate to check to see if the current event
2276 is the event we have been waiting for.
2277  
2278 The result is a Future that will return all captured events.
2279  
2280 =cut
2281  
2282 0 ▶sub _collectEvents( $self, @info ) {
Subroutine _collectEvents: not called CC=2 SCAR=17.9
2283 # Read the stuff that the driver sends to us:
2284 0 my $predicate = pop @info;
2285 0 ▶ ref $predicate eq 'CODE'
Branch: 1 branch
BranchTrueFalseTotal
ref $predicate eq "CODE" or die "Need a predicate as the last parameter, not '${predicate}'!" 0 0 0
2286 or die "Need a predicate as the last parameter, not '$predicate'!";
2287  
2288 0 my @events = ();
2289 0 my $done = $self->target->future;
2290 0 my $s = $self;
2291 0 weaken $s;
2292 0 ▶ $self->target->on( 'message' => sub( $target, $message ) {
Subroutine __ANON__: not called CC=3 SCAR=24.8
2293 0 push @events, $message;
2294 0 ▶ if( $predicate->( $events[-1] )) {
Branch: 1 branch
BranchTrueFalseTotal
if (&$predicate($events[-1])) 0 0 0
2295 0 my $frameId = $events[-1]->{params}->{frameId};
2296 0 ▶ $s->log( 'debug', "Received final message, unwinding", sprintf "(%s)", $frameId || '-');
Condition0%0/2
$frameId || '-'
l!l
00
MC/DC0%0/1
$frameId || '-'
$frameId
Truth table0%0/2
A
A= $frameId
Aresult
11
00
2297 0 $s->log( 'trace', "Received final message, unwinding", $events[-1] );
2298 0 $target->unsubscribe('message', __SUB__);
2299 0 $done->done( @info, @events );
2300 };
2301 0 });
2302 0 $done
2303 }
2304  
2305 0 ▶sub _fetchFrameId( $self, $ev ) {
Subroutine _fetchFrameId: not called CC=5 SCAR=34.0
2306 0 ▶ if( $ev->{method} eq 'Page.frameStartedLoading'
Branch: 1 branch
BranchTrueFalseTotal
if ($ev->{"method"} eq "Page.frameStartedLoading" or $ev->{"method"} eq "Page.frameScheduledNavigation" or $ev->{"method"} eq "Network.requestWillBeSent") 0 0 0
Condition0%0/6
$ev->{"method"} eq "Page.frameStartedLoading" or $ev->{"method"} eq "Page.frameScheduledNavigation" or $ev->{"method"} eq "Network.requestWillBeSent"
l!l&&r!l&&!r
000
$ev->{"method"} eq "Page.frameStartedLoading" or $ev->{"method"} eq "Page.frameScheduledNavigation"
l!l&&r!l&&!r
000
MC/DC0%0/3
$ev->{"method"} eq "Page.frameStartedLoading" or $ev->{"method"} eq "Page.frameScheduledNavigation" or $ev->{"method"} eq "Network.requestWillBeSent"
$ev->{"method"} eq "Page.frameStartedLoading" $ev->{"method"} eq "Page.frameScheduledNavigation" $ev->{"method"} eq "Network.requestWillBeSent"
Truth table0%0/4
A or B or C
A= $ev->{"method"} eq "Page.frameStartedLoading"B= $ev->{"method"} eq "Page.frameScheduledNavigation"C= $ev->{"method"} eq "Network.requestWillBeSent"
ABCresult
1XX1
01X1
0011
0000
2307 || $ev->{method} eq 'Page.frameScheduledNavigation'
2308 || $ev->{method} eq 'Network.requestWillBeSent'
2309 ) {
2310 0 my $frameId = $ev->{params}->{frameId};
2311 0 ▶ $self->log('debug', sprintf "Found frame id as %s", $frameId || '-');
Condition0%0/2
$frameId || '-'
l!l
00
MC/DC0%0/1
$frameId || '-'
$frameId
Truth table0%0/2
A
A= $frameId
Aresult
11
00
2312 0 return ($frameId);
2313 }
2314 };
2315  
2316 0 ▶sub _fetchRequestId( $self, $ev ) {
Subroutine _fetchRequestId: not called CC=5 SCAR=34.0
2317 0 ▶ if( $ev->{method} eq 'Page.frameStartedLoading'
Branch: 1 branch
BranchTrueFalseTotal
if ($ev->{"method"} eq "Page.frameStartedLoading" or $ev->{"method"} eq "Page.frameScheduledNavigation" or $ev->{"method"} eq "Network.requestWillBeSent") 0 0 0
Condition0%0/6
$ev->{"method"} eq "Page.frameStartedLoading" or $ev->{"method"} eq "Page.frameScheduledNavigation" or $ev->{"method"} eq "Network.requestWillBeSent"
l!l&&r!l&&!r
000
$ev->{"method"} eq "Page.frameStartedLoading" or $ev->{"method"} eq "Page.frameScheduledNavigation"
l!l&&r!l&&!r
000
MC/DC0%0/3
$ev->{"method"} eq "Page.frameStartedLoading" or $ev->{"method"} eq "Page.frameScheduledNavigation" or $ev->{"method"} eq "Network.requestWillBeSent"
$ev->{"method"} eq "Page.frameStartedLoading" $ev->{"method"} eq "Page.frameScheduledNavigation" $ev->{"method"} eq "Network.requestWillBeSent"
Truth table0%0/4
A or B or C
A= $ev->{"method"} eq "Page.frameStartedLoading"B= $ev->{"method"} eq "Page.frameScheduledNavigation"C= $ev->{"method"} eq "Network.requestWillBeSent"
ABCresult
1XX1
01X1
0011
0000
2318 || $ev->{method} eq 'Page.frameScheduledNavigation'
2319 || $ev->{method} eq 'Network.requestWillBeSent'
2320 ) {
2321 0 my $requestId = $ev->{params}->{requestId};
2322 0 ▶ if( $requestId ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($requestId) { } 0 0 0
2323 0 $self->log('debug', sprintf "Found request id as %s", $requestId);
2324 0 return ($requestId);
2325 } else {
2326 return
2327 0 };
2328 }
2329 };
2330  
2331 0 ▶sub _waitForNavigationEnd( $self, %options ) {
Subroutine _waitForNavigationEnd: not called CC=5 SCAR=34.0
2332 # Capture all events as we seem to have initiated some network transfers
2333 # If we see a Page.frameScheduledNavigation then Chrome started navigating
2334 # to a new page in response to our click and we should wait until we
2335 # received all the navigation events.
2336  
2337 0 ▶ my $frameId = $options{ frameId } || $self->frameId;
Condition0%0/3
$options{'frameId'} || $self->frameId
l!l&&r!l&&!r
000
MC/DC0%0/2
$options{'frameId'} || $self->frameId
$options{'frameId'} $self->frameId
Truth table0%0/3
A || B
A= $options{'frameId'}B= $self->frameId
ABresult
1X1
011
000
2338 0 ▶ my $requestId = $options{ requestId } || $self->requestId;
Condition0%0/3
$options{'requestId'} || $self->requestId
l!l&&r!l&&!r
000
MC/DC0%0/2
$options{'requestId'} || $self->requestId
$options{'requestId'} $self->requestId
Truth table0%0/3
A || B
A= $options{'requestId'}B= $self->requestId
ABresult
1X1
011
000
2339  
2340 # Actually, we need to wait for DOM.documentUpdated!
2341  
2342 0 ▶ my $msg = sprintf "Capturing events until 'Page.frameStoppedLoading' or 'Page.frameClearedScheduledNavigation' for frame %s",
Condition0%0/2
$frameId || '-'
l!l
00
MC/DC0%0/1
$frameId || '-'
$frameId
Truth table0%0/2
A
A= $frameId
Aresult
11
00
2343 $frameId || '-';
2344 0 ▶ $msg .= " or 'Network.loadingFailed' or 'Network.loadingFinished' for request '$requestId'"
Branch: 1 branch
BranchTrueFalseTotal
if $requestId 0 0 0
2345 if $requestId;
2346  
2347 0 $self->log('debug', $msg);
2348  
2349 0 my $s = $self;
2350 0 weaken $s;
2351 0 ▶ my $events_f = $self->_collectEvents( sub( $ev ) {
Subroutine __ANON__: not called CC=26 SCAR=65.5
2352 0 ▶ if( ! $ev->{method}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ev->{"method"}) 0 0 0
2353 # We get empty responses when talking to indirect targets
2354 return
2355 0 };
2356  
2357 # Let's assume that the first frame id we see is "our" frame
2358 0 ▶ $frameId ||= $s->_fetchFrameId($ev);
Condition0%0/3
$frameId ||= $s->_fetchFrameId($ev)
l!l&&r!l&&!r
000
MC/DC0%0/2
$frameId ||= $s->_fetchFrameId($ev)
$frameId $s->_fetchFrameId($ev)
Truth table0%0/3
A ||= B
A= $frameIdB= $s->_fetchFrameId($ev)
ABresult
1X1
011
000
2359 0 ▶ $requestId ||= $s->_fetchRequestId($ev);
Condition0%0/3
$requestId ||= $s->_fetchRequestId($ev)
l!l&&r!l&&!r
000
MC/DC0%0/2
$requestId ||= $s->_fetchRequestId($ev)
$requestId $s->_fetchRequestId($ev)
Truth table0%0/3
A ||= B
A= $requestIdB= $s->_fetchRequestId($ev)
ABresult
1X1
011
000
2360  
2361 my $stopped = ( $ev->{method} eq 'Page.frameStoppedLoading'
2362 && $ev->{params}->{frameId} eq $frameId)
2363 ||
2364 ( $ev->{method} eq 'Network.loadingFinished'
2365 && (! $ev->{params}->{frameId} || $ev->{params}->{frameId} eq ($frameId || ''))
2366 0 ▶ && (! $ev->{params}->{requestId} || $ev->{params}->{requestId} eq ($requestId || ''))
Condition0%0/22
$ev->{'method'} eq 'Page.frameStoppedLoading' && $ev->{'params'}{'frameId'} eq $frameId || $ev->{'method'} eq 'Network.loadingFinished' && (!$ev->{'params'}{'frameId'} || $ev->{'params'}{'frameId'} eq ($frameId || '')) && (!$ev->{'params'}{'requestId'} || $ev->{'params'}{'requestId'} eq ($requestId || ''))
l!l&&r!l&&!r
000
$ev->{"method"} eq "Page.frameStoppedLoading" and $ev->{"params"}{"frameId"} eq $frameId
!ll&&!rl&&r
000
$ev->{"method"} eq "Network.loadingFinished" and !$ev->{"params"}{"frameId"} || $ev->{"params"}{"frameId"} eq ($frameId || "") and !$ev->{"params"}{"requestId"} || $ev->{"params"}{"requestId"} eq ($requestId || "")
!ll&&!rl&&r
000
$ev->{"method"} eq "Network.loadingFinished" and !$ev->{"params"}{"frameId"} || $ev->{"params"}{"frameId"} eq ($frameId || "")
!ll&&!rl&&r
000
not $ev->{"params"}{"frameId"} or $ev->{"params"}{"frameId"} eq ($frameId || "")
l!l&&r!l&&!r
000
$frameId || ''
l!l
00
not $ev->{"params"}{"requestId"} or $ev->{"params"}{"requestId"} eq ($requestId || "")
l!l&&r!l&&!r
000
$requestId || ''
l!l
00
MC/DC0%0/7
$ev->{'method'} eq 'Page.frameStoppedLoading' && $ev->{'params'}{'frameId'} eq $frameId || $ev->{'method'} eq 'Network.loadingFinished' && (!$ev->{'params'}{'frameId'} || $ev->{'params'}{'frameId'} eq ($frameId || '')) && (!$ev->{'params'}{'requestId'} || $ev->{'params'}{'requestId'} eq ($requestId || ''))
$ev->{"method"} eq "Page.frameStoppedLoading" $ev->{"params"}{"frameId"} eq $frameId $ev->{"method"} eq "Network.loadingFinished" not $ev->{"params"}{"frameId"} $ev->{"params"}{"frameId"} eq ($frameId || "") not $ev->{"params"}{"requestId"} $ev->{"params"}{"requestId"} eq ($requestId || "")
MC/DC0%0/1
$frameId || ''
$frameId
MC/DC0%0/1
$requestId || ''
$requestId
Truth table0%0/17
A and B || C and not(D) or E and not(F) or G
A= $ev->{"method"} eq "Page.frameStoppedLoading"B= $ev->{"params"}{"frameId"} eq $frameIdC= $ev->{"method"} eq "Network.loadingFinished"D= not $ev->{"params"}{"frameId"}E= $ev->{"params"}{"frameId"} eq ($frameId || "")F= not $ev->{"params"}{"requestId"}G= $ev->{"params"}{"requestId"} eq ($requestId || "")
ABCDEFGresult
11XXXXX1
0X11X1X1
0X11X011
0X1011X1
0X101011
1011X1X1
1011X011
101011X1
10101011
0X0XXXX0
0X100XX0
0X11X000
0X101000
100XXXX0
10100XX0
1011X000
10101000
Truth table0%0/2
A
A= $frameId
Aresult
11
00
Truth table0%0/2
A
A= $requestId
Aresult
11
00
2367 );
2368 # This means basically no navigation events will follow:
2369 my $internal_navigation = ( $ev->{method} eq 'Page.navigatedWithinDocument'
2370 && $requestId
2371 && (! exists $ev->{params}->{requestId}
2372 0 ▶ or ($ev->{params}->{requestId} eq $requestId)));
Condition0%0/9
$ev->{'method'} eq 'Page.navigatedWithinDocument' && $requestId && (!exists $ev->{'params'}{'requestId'} || $ev->{'params'}{'requestId'} eq $requestId)
!ll&&!rl&&r
000
$ev->{"method"} eq "Page.navigatedWithinDocument" and $requestId
!ll&&!rl&&r
000
not exists $ev->{"params"}{"requestId"} or $ev->{"params"}{"requestId"} eq $requestId
l!l&&r!l&&!r
000
MC/DC0%0/4
$ev->{'method'} eq 'Page.navigatedWithinDocument' && $requestId && (!exists $ev->{'params'}{'requestId'} || $ev->{'params'}{'requestId'} eq $requestId)
$ev->{"method"} eq "Page.navigatedWithinDocument" $requestId not exists $ev->{"params"}{"requestId"} $ev->{"params"}{"requestId"} eq $requestId
Truth table0%0/5
A and B && not(C) or D
A= $ev->{"method"} eq "Page.navigatedWithinDocument"B= $requestIdC= not exists $ev->{"params"}{"requestId"}D= $ev->{"params"}{"requestId"} eq $requestId
ABCDresult
0XXX0
10XX0
11000
111X1
11011
2373 $internal_navigation ||= ( $ev->{method} eq 'Page.frameClearedScheduledNavigation'
2374 0 ▶ && $ev->{params}->{frameId} eq $frameId);
Condition0%0/6
$internal_navigation ||= $ev->{"method"} eq "Page.frameClearedScheduledNavigation" && $ev->{"params"}{"frameId"} eq $frameId
l!l&&r!l&&!r
000
$ev->{'method'} eq 'Page.frameClearedScheduledNavigation' && $ev->{'params'}{'frameId'} eq $frameId
!ll&&!rl&&r
000
MC/DC0%0/3
$internal_navigation ||= $ev->{"method"} eq "Page.frameClearedScheduledNavigation" && $ev->{"params"}{"frameId"} eq $frameId
$internal_navigation $ev->{'method'} eq 'Page.frameClearedScheduledNavigation' $ev->{'params'}{'frameId'} eq $frameId
Truth table0%0/4
A ||= B && C
A= $internal_navigationB= $ev->{'method'} eq 'Page.frameClearedScheduledNavigation'C= $ev->{'params'}{'frameId'} eq $frameId
ABCresult
1XX1
0111
00X0
0100
2375  
2376 # This is far too early, but some requests only send this?!
2377 # Maybe this can be salvaged by setting a timeout when we see this?!
2378 my $domcontent = ( 0 # $options{ just_request }
2379 #&& $ev->{method} eq 'Page.domContentEventFired', # this should be the only one we need (!)
2380 # but we never learn which page (!). So this does not play well with iframes :(
2381 0 && $ev->{method} eq 'DOM.documentUpdated', # this should be the only one we need (!)
2382 # but we never learn which page (!). So this does not play well with iframes :(
2383 );
2384  
2385 my $failed = ( $ev->{method} eq 'Network.loadingFailed'
2386 && $requestId
2387 0 ▶ && $ev->{params}->{requestId} eq $requestId);
Condition0%0/6
$ev->{'method'} eq 'Network.loadingFailed' && $requestId && $ev->{'params'}{'requestId'} eq $requestId
!ll&&!rl&&r
000
$ev->{"method"} eq "Network.loadingFailed" and $requestId
!ll&&!rl&&r
000
MC/DC0%0/3
$ev->{'method'} eq 'Network.loadingFailed' && $requestId && $ev->{'params'}{'requestId'} eq $requestId
$ev->{"method"} eq "Network.loadingFailed" $requestId $ev->{'params'}{'requestId'} eq $requestId
Truth table0%0/4
A and B && C
A= $ev->{"method"} eq "Network.loadingFailed"B= $requestIdC= $ev->{'params'}{'requestId'} eq $requestId
ABCresult
0XX0
10X0
1100
1111
2388 my $download= ( $ev->{method} eq 'Network.responseReceived'
2389 && $requestId
2390 && $ev->{params}->{requestId} eq $requestId
2391 && exists $ev->{params}->{response}->{headers}->{"Content-Disposition"}
2392 0 ▶ && $ev->{params}->{response}->{headers}->{"Content-Disposition"} =~ m!^attachment\b!
Condition0%0/12
$ev->{'method'} eq 'Network.responseReceived' && $requestId && $ev->{'params'}{'requestId'} eq $requestId && exists $ev->{'params'}{'response'}{'headers'}{'Content-Disposition'} && $ev->{'params'}{'response'}{'headers'}{'Content-Disposition'} =~ /^attachment\b/u
!ll&&!rl&&r
000
$ev->{"method"} eq "Network.responseReceived" and $requestId and $ev->{"params"}{"requestId"} eq $requestId and exists $ev->{"params"}{"response"}{"headers"}{"Content-Disposition"}
!ll&&!rl&&r
000
$ev->{"method"} eq "Network.responseReceived" and $requestId and $ev->{"params"}{"requestId"} eq $requestId
!ll&&!rl&&r
000
$ev->{"method"} eq "Network.responseReceived" and $requestId
!ll&&!rl&&r
000
MC/DC0%0/5
$ev->{'method'} eq 'Network.responseReceived' && $requestId && $ev->{'params'}{'requestId'} eq $requestId && exists $ev->{'params'}{'response'}{'headers'}{'Content-Disposition'} && $ev->{'params'}{'response'}{'headers'}{'Content-Disposition'} =~ /^attachment\b/u
$ev->{"method"} eq "Network.responseReceived" $requestId $ev->{"params"}{"requestId"} eq $requestId exists $ev->{"params"}{"response"}{"headers"}{"Content-Disposition"} $ev->{'params'}{'response'}{'headers'}{'Content-Disposition'} =~ /^attachment\b/u
Truth table0%0/6
A and B and C and D && E
A= $ev->{"method"} eq "Network.responseReceived"B= $requestIdC= $ev->{"params"}{"requestId"} eq $requestIdD= exists $ev->{"params"}{"response"}{"headers"}{"Content-Disposition"}E= $ev->{'params'}{'response'}{'headers'}{'Content-Disposition'} =~ /^attachment\b/u
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
2393 );
2394 0 ▶ return $stopped || $internal_navigation || $failed || $download; # $domcontent;
Condition0%0/9
$stopped || $internal_navigation || $failed || $download
l!l&&r!l&&!r
000
$stopped or $internal_navigation or $failed
l!l&&r!l&&!r
000
$stopped or $internal_navigation
l!l&&r!l&&!r
000
MC/DC0%0/4
$stopped || $internal_navigation || $failed || $download
$stopped $internal_navigation $failed $download
Truth table0%0/5
A or B or C || D
A= $stoppedB= $internal_navigationC= $failedD= $download
ABCDresult
1XXX1
01XX1
001X1
00011
00000
2395 0 });
2396  
2397 0 $events_f;
2398 }
2399  
2400 0 ▶sub _mightNavigate( $self, $get_navigation_future, %options ) {
Subroutine _mightNavigate: not called CC=1 SCAR=6.9
2401 0 undef $self->{frameId};
2402 0 undef $self->{requestId};
2403 0 my $frameId = $options{ frameId };
2404 0 my $requestId = $options{ requestId };
2405  
2406 0 my $scheduled = $self->target->one_shot(
2407 'Page.frameScheduledNavigation',
2408 'Page.frameStartedLoading',
2409 'Network.requestWillBeSent', # trial
2410 #'Page.frameResized', # download
2411 'Inspector.detached', # Browser (window) was closed by user
2412 'Page.navigatedWithinDocument',
2413 );
2414 0 my $navigated;
2415 my $does_navigation;
2416 0 my $target_url = $options{ url };
2417  
2418 {
2419 0 my $s = $self;
2420 0 weaken $s;
2421 $does_navigation = $scheduled
2422 0 ▶ ->then(sub( $ev ) {
Subroutine __ANON__: not called CC=8 SCAR=42.8
2423 0 my $res;
2424 0 ▶ if( $ev->{method} eq 'Page.frameResized'
Branch: 3 branches
BranchTrueFalseTotal
if ($ev->{'method'} eq 'Page.frameResized' and 0 + keys(%{$$ev{'params'};}) == 0) { } 0 0 0
elsif ($ev->{'method'} eq 'Inspector.detached') { } 0 0 0
elsif ($ev->{'method'} eq 'Page.navigatedWithinDocument') { } 0 0 0
Condition0%0/3
$ev->{"method"} eq "Page.frameResized" and 0 + keys(%{$$ev{"params"};}) == 0
!ll&&!rl&&r
000
MC/DC0%0/2
$ev->{"method"} eq "Page.frameResized" and 0 + keys(%{$$ev{"params"};}) == 0
$ev->{"method"} eq "Page.frameResized" 0 + keys(%{$$ev{"params"};}) == 0
Truth table0%0/3
A and B
A= $ev->{"method"} eq "Page.frameResized"B= 0 + keys(%{$$ev{"params"};}) == 0
ABresult
0X0
100
111
2425 0 and 0+keys %{ $ev->{params} } == 0 ) {
2426 # This is dead code that is never reached (see above)
2427 # Chrome v64 doesn't indicate at all to the API that a
2428 # download started :-(
2429 # Also, we won't know that it finished, or what name the
2430 # file got
2431 # At least unless we try to parse that from the response body :(
2432 0 $s->log('trace', "Download started, returning synthesized event");
2433 0 $navigated++;
2434 0 $s->{ frameId } = $ev->{params}->{frameId};
2435 $res = Future->done(
2436 # Since Chrome v64,
2437 { method => 'MechanizeChrome.download', params => {
2438 frameId => $ev->{params}->{frameId},
2439 loaderId => $ev->{params}->{loaderId},
2440 0 response => {
2441 status => 200,
2442 statusText => 'faked response',
2443 headers => {
2444 'Content-Disposition' => 'attachment; filename=unknown',
2445 }
2446 }}
2447 })
2448  
2449 } elsif( $ev->{method} eq 'Inspector.detached' ) {
2450 0 $s->log('error', "Inspector was detached");
2451 0 $res = Future->fail("Inspector was detached");
2452  
2453 } elsif( $ev->{method} eq 'Page.navigatedWithinDocument' ) {
2454 0 $s->log('trace', "Intra-page navigation started, logging ($ev->{method})");
2455 0 ▶ $frameId ||= $s->_fetchFrameId( $ev );
Condition0%0/3
$frameId ||= $s->_fetchFrameId($ev)
l!l&&r!l&&!r
000
MC/DC0%0/2
$frameId ||= $s->_fetchFrameId($ev)
$frameId $s->_fetchFrameId($ev)
Truth table0%0/3
A ||= B
A= $frameIdB= $s->_fetchFrameId($ev)
ABresult
1X1
011
000
2456 $res = Future->done(
2457 # Since Chrome v64,
2458 { method => 'Page.intra-page-navigation', params => {
2459 frameId => $ev->{params}->{frameId},
2460 loaderId => $ev->{params}->{loaderId},
2461 0 response => {
2462 status => 200,
2463 statusText => 'faked response',
2464 }}
2465 })
2466  
2467 } else {
2468 0 $s->log('trace', "Navigation started, logging ($ev->{method})");
2469 0 $navigated++;
2470  
2471 0 ▶ $frameId ||= $s->_fetchFrameId( $ev );
Condition0%0/3
$frameId ||= $s->_fetchFrameId($ev)
l!l&&r!l&&!r
000
MC/DC0%0/2
$frameId ||= $s->_fetchFrameId($ev)
$frameId $s->_fetchFrameId($ev)
Truth table0%0/3
A ||= B
A= $frameIdB= $s->_fetchFrameId($ev)
ABresult
1X1
011
000
2472 0 ▶ $requestId ||= $s->_fetchRequestId( $ev );
Condition0%0/3
$requestId ||= $s->_fetchRequestId($ev)
l!l&&r!l&&!r
000
MC/DC0%0/2
$requestId ||= $s->_fetchRequestId($ev)
$requestId $s->_fetchRequestId($ev)
Truth table0%0/3
A ||= B
A= $requestIdB= $s->_fetchRequestId($ev)
ABresult
1X1
011
000
2473 0 $s->{ frameId } = $frameId;
2474 0 $s->{ requestId } = $requestId;
2475  
2476 0 $res = $s->_waitForNavigationEnd( %options )
2477 };
2478 0 return $res
2479 0 });
2480 };
2481  
2482 # Kick off the navigation ourselves
2483 0 my $s = $self;
2484 0 weaken $s;
2485  
2486 0 my $nav;
2487 $get_navigation_future->()
2488 0 ▶ ->then( sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2489 0 $nav = $_[0];
2490  
2491 # We have a race condition to find out whether Chrome navigates or not
2492 # so we wait a bit to see if it will navigate in response to our click
2493 0 $s->sleep_future(0.1); # X XX baad fix
2494 0 ▶ })->then( sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
2495 0 my $f;
2496 my @events;
2497 0 ▶ if( !$options{ intrapage } and $navigated ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $options{'intrapage'} and $navigated) { } 0 0 0
Condition0%0/3
not $options{"intrapage"} and $navigated
!ll&&!rl&&r
000
MC/DC0%0/2
not $options{"intrapage"} and $navigated
not $options{"intrapage"} $navigated
Truth table0%0/3
not(A) and B
A= not $options{"intrapage"}B= $navigated
ABresult
0X0
100
111
2498 0 ▶ $f = $does_navigation->then( sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2499 0 @events = @_;
2500 # Handle all the events, by turning them into a ->response again
2501 0 my $res = $self->httpMessageFromEvents( $self->frameId, \@events, $target_url );
2502 0 $self->update_response( $res );
2503 0 $scheduled->cancel;
2504 0 undef $scheduled;
2505  
2506 # Store our frame id so we know what events to listen for in the future!
2507 0 ▶ $self->{frameId} ||= $nav->{frameId};
Condition0%0/3
$self->{"frameId"} ||= $nav->{"frameId"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"frameId"} ||= $nav->{"frameId"}
$self->{"frameId"} $nav->{"frameId"}
Truth table0%0/3
A ||= B
A= $self->{"frameId"}B= $nav->{"frameId"}
ABresult
1X1
011
000
2508  
2509 0 Future->done( \@events )
2510 })
2511 0 } else {
2512 0 $self->log('trace', "No navigation occurred, not collecting events");
2513 0 $does_navigation->cancel;
2514 0 $f = Future->done(\@events);
2515 0 $scheduled->cancel;
2516 0 undef $scheduled;
2517 };
2518  
2519 0 return $f
2520 })
2521 0 }
2522  
2523 0 ▶sub get_future($self, $url, %options ) {
Subroutine get_future: not called CC=1 SCAR=6.9
Pod undocumented
2524  
2525 # $frameInfo might come _after_ we have already seen messages for it?!
2526 # So we need to capture all events even before we send our command to the
2527 # browser, as we might receive messages before we receive the answer to
2528 # our command:
2529 0 my $s = $self;
2530 0 weaken $s;
2531 0 ▶ my $events = $self->_mightNavigate( sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2532 0 $s->log('debug', "Navigating to [$url]");
2533 0 $s->target->send_message(
2534 'Page.navigate',
2535 url => "$url"
2536 )
2537 }, url => "$url", %options, navigates => 1 )
2538 0 ▶ ->then( sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2539 0 $s->invalidate_cached_values;
2540 0 Future->done( $s->response )
2541 })
2542 0 };
2543  
2544 0 ▶sub get($self, $url, %options ) {
Subroutine get: not called CC=1 SCAR=6.9
Pod documented
2545  
2546 0 $self->get_future($url, %options)->get;
2547 };
2548  
2549 =head2 C<< $mech->get_local( $filename , %options ) >>
2550  
2551 $mech->get_local('test.html');
2552  
2553 Shorthand method to construct the appropriate
2554 C<< file:// >> URI and load it into Chrome. Relative
2555 paths will be interpreted as relative to C<$0>
2556 or the C<basedir> option.
2557  
2558 This method accepts the same options as C<< ->get() >>.
2559  
2560 This method is special to WWW::Mechanize::Chrome but could
2561 also exist in WWW::Mechanize through a plugin.
2562  
2563 B<Warning>: Chrome does not handle local files well. Especially
2564 subframes do not get loaded properly.
2565  
2566 =cut
2567  
2568 0 ▶sub _local_url( $self, $htmlfile, %options ) {
Subroutine _local_url: not called CC=3 SCAR=24.8
2569 0 my $basedir;
2570 0 ▶ if( exists $options{ basedir }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options{'basedir'}) { } 0 0 0
2571 0 $basedir = $options{ basedir };
2572 } else {
2573 0 require Cwd;
2574 0 require File::Spec;
2575 0 $basedir = dirname($0);
2576 };
2577  
2578 0 my $fn = File::Spec->rel2abs( $htmlfile, $basedir );
2579 0 $fn =~ s!\\!/!g; # fakey "make file:// URL"
2580 0 my $url;
2581 0 ▶ if( $^O =~ /mswin/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O =~ /mswin/iu) { } 0 0 0
2582 0 $url= "file:///$fn";
2583 } else {
2584 0 $url= "file://$fn";
2585 };
2586 0 return $url
2587 }
2588  
2589 0 ▶sub get_local( $self, $htmlfile, %options ) {
Subroutine get_local: not called CC=1 SCAR=6.9
Pod documented
2590 0 my $url = $self->_local_url( $htmlfile, %options );
2591 0 my $res = $self->get($url, %options);
2592 ## Chrome is not helpful with its error messages for local URLs
2593 #if( 0+$res->headers->header_field_names and ([$res->headers->header_field_names]->[0] ne 'x-www-mechanize-Chrome-fake-success' or $self->uri ne 'about:blank')) {
2594 # # We need to fake the content headers from <meta> tags too...
2595 # # Maybe this even needs to go into ->get()
2596 # $res->code( 200 );
2597 #} else {
2598 # $res->code( 400 ); # Must have been "not found"
2599 #};
2600 0 $res
2601 }
2602  
2603 0 ▶sub httpRequestFromChromeRequest( $self, $event ) {
Subroutine httpRequestFromChromeRequest: not called CC=1 SCAR=6.9
Pod undocumented
2604 my $req = HTTP::Request->new(
2605 $event->{params}->{request}->{method},
2606 $event->{params}->{request}->{url},
2607 0 HTTP::Headers->new( %{ $event->{params}->{request}->{headers}} ),
2608 );
2609 };
2610  
2611 =head2 C<< $mech->getRequestPostData >>
2612  
2613 if( $info->{params}->{response}->{requestHeaders}->{":method"} eq 'POST' ) {
2614 $req->{postBody} = $m->getRequestPostData( $id );
2615 };
2616  
2617 Retrieves the data sent with a POST request
2618  
2619 =cut
2620  
2621 0 ▶sub getRequestPostData_future( $self, $requestId ) {
Subroutine getRequestPostData_future: not called CC=1 SCAR=6.9
Pod undocumented
2622 0 $self->log('debug', "Fetching request POST body for $requestId");
2623 0 weaken( my $s = $self );
2624 return
2625 $self->target->send_message('Network.getRequestPostData', requestId => $requestId)
2626 0 ▶ ->then(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2627 0 $s->log('trace', "Have POST body", @_);
2628 0 my ($body_obj) = @_;
2629  
2630 0 my $body = $body_obj->{postData};
2631 # WTF? The documentation says the body is base64 encoded, but
2632 # experimentation shows it isn't, at least for JSON content :-/
2633 #$body = decode_base64( $body );
2634 0 Future->done( $body )
2635 0 });
2636 }
2637  
2638 0 ▶sub getRequestPostData( $self, $requestId ) {
Subroutine getRequestPostData: not called CC=1 SCAR=6.9
Pod documented
2639 0 $self->getRequestPostData_future( $requestId )->get
2640 }
2641  
2642 0 ▶sub getResponseBody( $self, $requestId ) {
Subroutine getResponseBody: not called CC=1 SCAR=6.9
Pod undocumented
2643 0 $self->log('debug', "Fetching response body for $requestId");
2644 0 my $s = $self;
2645 0 weaken $s;
2646  
2647 0 $self->{__responseInFlight} = 1;
2648  
2649 return
2650 $self->target->send_message('Network.getResponseBody', requestId => $requestId)
2651 0 ▶ ->then(sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2652 0 $s->log('debug', "Have body", @_);
2653 0 my ($body_obj) = @_;
2654  
2655 0 $s->invalidate_cached_values;
2656  
2657 0 delete $s->{__responseInFlight};
2658  
2659 0 my $body = $body_obj->{body};
2660 $body = decode_base64( $body )
2661 0 ▶ if $body_obj->{base64Encoded};
Branch: 1 branch
BranchTrueFalseTotal
if $body_obj->{"base64Encoded"} 0 0 0
2662 0 Future->done( $body )
2663 0 });
2664 }
2665  
2666 0 ▶sub httpResponseFromChromeResponse( $self, $res ) {
Subroutine httpResponseFromChromeResponse: not called CC=3 SCAR=24.8
Pod undocumented
2667 my $response = HTTP::Response->new(
2668 $res->{params}->{response}->{status} || 200, # is 0 for files?!
2669 $res->{params}->{response}->{statusText},
2670 0 ▶ HTTP::Headers->new( %{ $res->{params}->{response}->{headers} }),
Condition0%0/2
$res->{'params'}{'response'}{'status'} || 200
l!l
00
MC/DC0%0/1
$res->{'params'}{'response'}{'status'} || 200
$res->{'params'}{'response'}{'status'}
Truth table0%0/2
A
A= $res->{'params'}{'response'}{'status'}
Aresult
11
00
2671 );
2672 0 $self->log('debug',sprintf "Status %0d - %s",$response->code, $response->status_line);
2673  
2674 # Also fetch the response body and include it in the response
2675 # as we can't do that lazily...
2676 # This is nasty, as we will fill in the response lazily and the user has
2677 # no way of knowing when we have filled in the response body
2678 # The proper way might be to return a proxy object...
2679 0 my $requestId = $res->{params}->{requestId};
2680  
2681 0 ▶ if( $requestId ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($requestId) 0 0 0
2682 0 my $full_response_future;
2683  
2684 0 my $s = $self;
2685 0 weaken $s;
2686 0 ▶ $full_response_future = $self->getResponseBody( $requestId )->then( sub( $body ) {
Subroutine __ANON__: not called CC=3 SCAR=24.8
2687 0 $s->log('debug', "Response body arrived");
2688  
2689 # We need to encode the body back to the appropriate bytes:
2690 0 my $ct = $response->content_type;
2691  
2692 0 ▶ $ct ||= 'text/plain';
Condition0%0/2
$ct ||= "text/plain"
l!l
00
MC/DC0%0/1
$ct ||= "text/plain"
$ct
Truth table0%0/2
A
A= $ct
Aresult
11
00
2693  
2694 0 ▶ if( $ct =~ m!^text/(\w+); charset=(.*?)! ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ct =~ m[^text/(\w+); charset=(.*?)]u) { } 0 0 0
2695 0 warn "Re-encoding back to $2";
2696 0 $body = encode( "$2", $body );
2697 } else {
2698 # assume Latin-1 (actually, strip the encoding information from the Perl string)
2699 0 $body = encode( 'Latin-1', $body );
2700 };
2701  
2702 0 $response->content( $body );
2703 #undef $full_response_future;
2704 0 Future->done($body)
2705 0 })->retain;
2706 #$response->content_ref( \$body );
2707 };
2708 0 $response
2709 };
2710  
2711 0 ▶sub httpResponseFromChromeNetworkFail( $self, $res ) {
Subroutine httpResponseFromChromeNetworkFail: not called CC=2 SCAR=17.9
Pod undocumented
2712 my $response = HTTP::Response->new(
2713 $res->{params}->{response}->{status} || 599, # No error code exists for files
2714 $res->{params}->{response}->{errorText},
2715 0 ▶ HTTP::Headers->new(),
Condition0%0/2
$res->{'params'}{'response'}{'status'} || 599
l!l
00
MC/DC0%0/1
$res->{'params'}{'response'}{'status'} || 599
$res->{'params'}{'response'}{'status'}
Truth table0%0/2
A
A= $res->{'params'}{'response'}{'status'}
Aresult
11
00
2716 );
2717 };
2718  
2719 0 ▶sub httpResponseFromChromeUrlUnreachable( $self, $res ) {
Subroutine httpResponseFromChromeUrlUnreachable: not called CC=1 SCAR=6.9
Pod undocumented
2720 my $response = HTTP::Response->new(
2721 599, # No error code exists for files
2722 "Unreachable URL: " . $res->{params}->{frame}->{unreachableUrl},
2723 0 HTTP::Headers->new(),
2724 );
2725 };
2726  
2727 0 ▶sub httpMessageFromEvents( $self, $frameId, $events, $url ) {
Subroutine httpMessageFromEvents: not called CC=43 SCAR=75.5
Pod undocumented
2728 0 my ($requestId,$loaderId);
2729  
2730 0 ▶ if( $url ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($url) 0 0 0
2731 # Find the request id of the request
2732 0 for( @$events ) {
2733 0 ▶ next unless $_->{method};
Branch: 1 branch
BranchTrueFalseTotal
unless $_->{"method"} 0 0 0
2734 0 ▶ if( defined $frameId
Branch: 1 branch
BranchTrueFalseTotal
if (defined $frameId and $_->{"method"} eq "Network.requestWillBeSent" and $_->{"params"}{"frameId"} eq $frameId) 0 0 0
Condition0%0/6
defined $frameId and $_->{"method"} eq "Network.requestWillBeSent" and $_->{"params"}{"frameId"} eq $frameId
!ll&&!rl&&r
000
defined $frameId and $_->{"method"} eq "Network.requestWillBeSent"
!ll&&!rl&&r
000
MC/DC0%0/3
defined $frameId and $_->{"method"} eq "Network.requestWillBeSent" and $_->{"params"}{"frameId"} eq $frameId
defined $frameId $_->{"method"} eq "Network.requestWillBeSent" $_->{"params"}{"frameId"} eq $frameId
Truth table0%0/4
A and B and C
A= defined $frameIdB= $_->{"method"} eq "Network.requestWillBeSent"C= $_->{"params"}{"frameId"} eq $frameId
ABCresult
0XX0
10X0
1100
1111
2735 and $_->{method} eq 'Network.requestWillBeSent'
2736 and $_->{params}->{frameId} eq $frameId ) {
2737 0 ▶ if( $url and $_->{params}->{request}->{url} eq $url ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($url and $_->{'params'}{'request'}{'url'} eq $url) { } 0 0 0
Condition0%0/3
$url and $_->{"params"}{"request"}{"url"} eq $url
!ll&&!rl&&r
000
MC/DC0%0/2
$url and $_->{"params"}{"request"}{"url"} eq $url
$url $_->{"params"}{"request"}{"url"} eq $url
Truth table0%0/3
A and B
A= $urlB= $_->{"params"}{"request"}{"url"} eq $url
ABresult
0X0
100
111
2738 0 $requestId = $_->{params}->{requestId};
2739 } else {
2740 0 ▶ $requestId ||= $_->{params}->{requestId};
Condition0%0/3
$requestId ||= $_->{"params"}{"requestId"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$requestId ||= $_->{"params"}{"requestId"}
$requestId $_->{"params"}{"requestId"}
Truth table0%0/3
A ||= B
A= $requestIdB= $_->{"params"}{"requestId"}
ABresult
1X1
011
000
2741 };
2742 }
2743 };
2744 };
2745  
2746 # Just silence some undef warnings
2747 0 ▶ if( ! defined $requestId) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $requestId) 0 0 0
2748 0 $requestId = ''
2749 };
2750 0 ▶ if( ! defined $frameId) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $frameId) 0 0 0
2751 0 $frameId = ''
2752 };
2753  
2754 my @events = grep {
2755 my $this_frame = (exists $_->{params}->{frameId} && $_->{params}->{frameId})
2756 0 ▶ || (exists $_->{params}->{frame}->{id} && $_->{params}->{frame}->{id});
Condition0%0/9
exists $_->{'params'}{'frameId'} && $_->{'params'}{'frameId'} || exists $_->{'params'}{'frame'}{'id'} && $_->{'params'}{'frame'}{'id'}
l!l&&r!l&&!r
000
exists $_->{"params"}{"frameId"} and $_->{"params"}{"frameId"}
!ll&&!rl&&r
000
exists $_->{"params"}{"frame"}{"id"} and $_->{"params"}{"frame"}{"id"}
!ll&&!rl&&r
000
MC/DC0%0/4
exists $_->{'params'}{'frameId'} && $_->{'params'}{'frameId'} || exists $_->{'params'}{'frame'}{'id'} && $_->{'params'}{'frame'}{'id'}
exists $_->{"params"}{"frameId"} $_->{"params"}{"frameId"} exists $_->{"params"}{"frame"}{"id"} $_->{"params"}{"frame"}{"id"}
Truth table0%0/7
A and B || C and D
A= exists $_->{"params"}{"frameId"}B= $_->{"params"}{"frameId"}C= exists $_->{"params"}{"frame"}{"id"}D= $_->{"params"}{"frame"}{"id"}
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
2757 0 ▶ if( exists $_->{params}->{requestId}
Branch: 2 branches
BranchTrueFalseTotal
if (exists $_->{'params'}{'requestId'} and $_->{'params'}{'requestId'} eq $requestId) { } 0 0 0
elsif (not exists $_->{'params'}{'requestId'} and $this_frame eq $frameId) { } 0 0 0
Condition0%0/3
exists $_->{"params"}{"requestId"} and $_->{"params"}{"requestId"} eq $requestId
!ll&&!rl&&r
000
MC/DC0%0/2
exists $_->{"params"}{"requestId"} and $_->{"params"}{"requestId"} eq $requestId
exists $_->{"params"}{"requestId"} $_->{"params"}{"requestId"} eq $requestId
Truth table0%0/3
A and B
A= exists $_->{"params"}{"requestId"}B= $_->{"params"}{"requestId"} eq $requestId
ABresult
0X0
100
111
2758 and $_->{params}->{requestId} eq $requestId
2759 ) {
2760 0 "Matches our request id"
2761 ▶ } elsif( ! exists $_->{params}->{requestId}
Condition0%0/3
not exists $_->{"params"}{"requestId"} and $this_frame eq $frameId
!ll&&!rl&&r
000
MC/DC0%0/2
not exists $_->{"params"}{"requestId"} and $this_frame eq $frameId
not exists $_->{"params"}{"requestId"} $this_frame eq $frameId
Truth table0%0/3
not(A) and B
A= not exists $_->{"params"}{"requestId"}B= $this_frame eq $frameId
ABresult
0X0
100
111
2762 and $this_frame eq $frameId
2763 ) {
2764 0 "Matches our frame id and has no associated request"
2765 } else {
2766 0 ""
2767 }
2768  
2769 } map {
2770 # Extract the loaderId and requestId, if we haven't found it yet
2771 0 ▶ my $fi = $frameId || '';
Condition0%0/2
$frameId || ''
l!l
00
MC/DC0%0/1
$frameId || ''
$frameId
Truth table0%0/2
A
A= $frameId
Aresult
11
00
2772 0 ▶ my $rfi = $_->{params}->{frameId} || '';
Condition0%0/2
$_->{'params'}{'frameId'} || ''
l!l
00
MC/DC0%0/1
$_->{'params'}{'frameId'} || ''
$_->{'params'}{'frameId'}
Truth table0%0/2
A
A= $_->{'params'}{'frameId'}
Aresult
11
00
2773 0 ▶ if( $_->{method} eq 'Network.requestWillBeSent' and $rfi eq $fi ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_->{"method"} eq "Network.requestWillBeSent" and $rfi eq $fi) 0 0 0
Condition0%0/3
$_->{"method"} eq "Network.requestWillBeSent" and $rfi eq $fi
!ll&&!rl&&r
000
MC/DC0%0/2
$_->{"method"} eq "Network.requestWillBeSent" and $rfi eq $fi
$_->{"method"} eq "Network.requestWillBeSent" $rfi eq $fi
Truth table0%0/3
A and B
A= $_->{"method"} eq "Network.requestWillBeSent"B= $rfi eq $fi
ABresult
0X0
100
111
2774 0 ▶ $requestId ||= $_->{params}->{requestId};
Condition0%0/3
$requestId ||= $_->{"params"}{"requestId"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$requestId ||= $_->{"params"}{"requestId"}
$requestId $_->{"params"}{"requestId"}
Truth table0%0/3
A ||= B
A= $requestIdB= $_->{"params"}{"requestId"}
ABresult
1X1
011
000
2775 0 ▶ $loaderId ||= $_->{params}->{loaderId};
Condition0%0/3
$loaderId ||= $_->{"params"}{"loaderId"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$loaderId ||= $_->{"params"}{"loaderId"}
$loaderId $_->{"params"}{"loaderId"}
Truth table0%0/3
A ||= B
A= $loaderIdB= $_->{"params"}{"loaderId"}
ABresult
1X1
011
000
2776 0 ▶ $requestId ||= $_->{params}->{requestId};
Condition0%0/3
$requestId ||= $_->{"params"}{"requestId"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$requestId ||= $_->{"params"}{"requestId"}
$requestId $_->{"params"}{"requestId"}
Truth table0%0/3
A ||= B
A= $requestIdB= $_->{"params"}{"requestId"}
ABresult
1X1
011
000
2777 };
2778 0 $_
2779 } @$events;
2780  
2781 0 my %events;
2782 0 for (@events) {
2783 #warn join " - ", $_->{method}, $_->{params}->{loaderId}, $_->{params}->{frameId};
2784 0 ▶ $events{ $_->{method} } ||= $_;
Condition0%0/3
$events{$_->{"method"}} ||= $_
l!l&&r!l&&!r
000
MC/DC0%0/2
$events{$_->{"method"}} ||= $_
$events{$_->{"method"}} $_
Truth table0%0/3
A ||= B
A= $events{$_->{"method"}}B= $_
ABresult
1X1
011
000
2785 };
2786  
2787 # Create HTTP::Request object from 'Network.requestWillBeSent'
2788 0 my $request;
2789 my $response;
2790  
2791 my $about_blank_loaded = $events{ "Page.frameNavigated" }
2792 0 ▶ && $events{ "Page.frameNavigated" }->{params}->{frame}->{url} eq 'about:blank';
Condition0%0/3
$events{'Page.frameNavigated'} && $events{'Page.frameNavigated'}{'params'}{'frame'}{'url'} eq 'about:blank'
!ll&&!rl&&r
000
MC/DC0%0/2
$events{'Page.frameNavigated'} && $events{'Page.frameNavigated'}{'params'}{'frame'}{'url'} eq 'about:blank'
$events{'Page.frameNavigated'} $events{'Page.frameNavigated'}{'params'}{'frame'}{'url'} eq 'about:blank'
Truth table0%0/3
A && B
A= $events{'Page.frameNavigated'}B= $events{'Page.frameNavigated'}{'params'}{'frame'}{'url'} eq 'about:blank'
ABresult
0X0
100
111
2793 0 ▶ if( $about_blank_loaded ) {
Branch: 9 branches
BranchTrueFalseTotal
if ($about_blank_loaded) { } 0 0 0
elsif (my $res = $events{'Network.responseReceived'}) { } 0 0 0
elsif ($res = $events{'Page.navigatedWithinDocument'}) { } 0 0 0
elsif ($res = $events{'Network.loadingFailed'}) { } 0 0 0
elsif ($res = $events{'Page.frameNavigated'} and $res->{'params'}{'frame'}{'unreachableUrl'}) { } 0 0 0
elsif ($res = $events{'Page.frameNavigated'} and $res->{'params'}{'frame'}{'url'} =~ m[^file://]u) { } 0 0 0
elsif ($res = $events{'Page.frameClearedScheduledNavigation'} and $res->{'params'}{'frameId'} eq $frameId) { } 0 0 0
elsif ($res = $events{'Page.frameStoppedLoading'} and $res->{'params'}{'frameId'} eq $frameId) { } 0 0 0
elsif ($res = $events{'MechanizeChrome.download'}) { } 0 0 0
2794 #warn "About:blank";
2795 0 $response = HTTP::Response->new(
2796 200,
2797 'OK',
2798 );
2799 } elsif ( my $res = $events{ 'Network.responseReceived' }) {
2800 #warn "Network.responseReceived";
2801 0 $response = $self->httpResponseFromChromeResponse( $res );
2802 0 $response->request( $request );
2803  
2804 } elsif ( $res = $events{ 'Page.navigatedWithinDocument' }) {
2805 # A fake response, just in case anybody checks
2806 0 $response = HTTP::Response->new(
2807 200, # is 0 for files?!
2808 "OK",
2809 HTTP::Headers->new(),
2810 );
2811 0 $response->request( $request );
2812  
2813 } elsif( $res = $events{ 'Network.loadingFailed' }) {
2814 #warn "Network.loadingFailed";
2815 0 $response = $self->httpResponseFromChromeNetworkFail( $res );
2816 0 $response->request( $request );
2817  
2818 ▶ } elsif ( $res = $events{ 'Page.frameNavigated' }
Condition0%0/3
$res = $events{"Page.frameNavigated"} and $res->{"params"}{"frame"}{"unreachableUrl"}
!ll&&!rl&&r
000
MC/DC0%0/2
$res = $events{"Page.frameNavigated"} and $res->{"params"}{"frame"}{"unreachableUrl"}
$res = $events{"Page.frameNavigated"} $res->{"params"}{"frame"}{"unreachableUrl"}
Truth table0%0/3
A and B
A= $res = $events{"Page.frameNavigated"}B= $res->{"params"}{"frame"}{"unreachableUrl"}
ABresult
0X0
100
111
2819 and $res->{params}->{frame}->{unreachableUrl}) {
2820 #warn "Network.frameNavigated (unreachable)";
2821 0 $response = $self->httpResponseFromChromeUrlUnreachable( $res );
2822 0 $response->request( $request );
2823  
2824 ▶ } elsif ( $res = $events{ 'Page.frameNavigated' }
Condition0%0/3
$res = $events{"Page.frameNavigated"} and $res->{"params"}{"frame"}{"url"} =~ m[^file://]u
!ll&&!rl&&r
000
MC/DC0%0/2
$res = $events{"Page.frameNavigated"} and $res->{"params"}{"frame"}{"url"} =~ m[^file://]u
$res = $events{"Page.frameNavigated"} $res->{"params"}{"frame"}{"url"} =~ m[^file://]u
Truth table0%0/3
A and B
A= $res = $events{"Page.frameNavigated"}B= $res->{"params"}{"frame"}{"url"} =~ m[^file://]u
ABresult
0X0
100
111
2825 and $res->{params}->{frame}->{url} =~ m!^file://!) {
2826 #warn "Network.frameNavigated (file)";
2827 # Chrome v67+ doesn't send network events for file:// navigation
2828 0 $response = HTTP::Response->new(
2829 200, # is 0 for files?!
2830 "OK",
2831 HTTP::Headers->new(),
2832 );
2833 0 $response->request( $request );
2834  
2835 # Popup window, handled in a new instance, if captured
2836 ▶ } elsif ( $res = $events{ 'Page.frameClearedScheduledNavigation' }
Condition0%0/3
$res = $events{"Page.frameClearedScheduledNavigation"} and $res->{"params"}{"frameId"} eq $frameId
!ll&&!rl&&r
000
MC/DC0%0/2
$res = $events{"Page.frameClearedScheduledNavigation"} and $res->{"params"}{"frameId"} eq $frameId
$res = $events{"Page.frameClearedScheduledNavigation"} $res->{"params"}{"frameId"} eq $frameId
Truth table0%0/3
A and B
A= $res = $events{"Page.frameClearedScheduledNavigation"}B= $res->{"params"}{"frameId"} eq $frameId
ABresult
0X0
100
111
2837 and $res->{params}->{frameId} eq $frameId) {
2838 #warn "Network.frameNavigated (file)";
2839 0 $response = HTTP::Response->new(
2840 200, # is 0 for files?!
2841 "OK",
2842 HTTP::Headers->new(),
2843 );
2844 0 $response->request( $request );
2845  
2846  
2847 ▶ } elsif ( $res = $events{ 'Page.frameStoppedLoading' }
Condition0%0/3
$res = $events{"Page.frameStoppedLoading"} and $res->{"params"}{"frameId"} eq $frameId
!ll&&!rl&&r
000
MC/DC0%0/2
$res = $events{"Page.frameStoppedLoading"} and $res->{"params"}{"frameId"} eq $frameId
$res = $events{"Page.frameStoppedLoading"} $res->{"params"}{"frameId"} eq $frameId
Truth table0%0/3
A and B
A= $res = $events{"Page.frameStoppedLoading"}B= $res->{"params"}{"frameId"} eq $frameId
ABresult
0X0
100
111
2848 and $res->{params}->{frameId} eq $frameId) {
2849 #warn "Network.frameStoppedLoading";
2850 # Chrome v67+ doesn't send network events for file:// navigation
2851 # so we need to fake it completely
2852 0 $response = HTTP::Response->new(
2853 200, # is 0 for files?!
2854 "OK",
2855 HTTP::Headers->new(),
2856 );
2857 0 $response->request( $request );
2858  
2859 } elsif( $res = $events{ "MechanizeChrome.download" } ) {
2860 #warn "MechanizeChrome.download";
2861 $response = HTTP::Response->new(
2862 $res->{params}->{response}->{status} || 200, # is 0 for files?!
2863 $res->{params}->{response}->{statusText},
2864 0 ▶ HTTP::Headers->new( %{ $res->{params}->{response}->{headers} }),
Condition0%0/2
$res->{'params'}{'response'}{'status'} || 200
l!l
00
MC/DC0%0/1
$res->{'params'}{'response'}{'status'} || 200
$res->{'params'}{'response'}{'status'}
Truth table0%0/2
A
A= $res->{'params'}{'response'}{'status'}
Aresult
11
00
2865 )
2866  
2867 } else {
2868 0 require Data::Dumper;
2869 0 $response = HTTP::Response->new(
2870 599, # internal error
2871 'Cannot synthesize response',
2872 HTTP::Headers->new(),
2873 join "\n",
2874 Data::Dumper::Dumper( $events ),
2875 join " ", "Chrome behaviour problem: Didn't see a",
2876 "'Network.responseReceived' event for frameId $frameId,",
2877 "requestId $requestId, cannot synthesize response.",
2878 "I saw " . join ",", sort keys %events
2879 );
2880 };
2881 0 $response
2882 }
2883  
2884 =head2 C<< $mech->post( $url, %options ) >>
2885  
2886 B<not implemented>
2887  
2888 $mech->post( 'http://example.com',
2889 params => { param => "Hello World" },
2890 headers => {
2891 "Content-Type" => 'application/x-www-form-urlencoded',
2892 },
2893 charset => 'utf-8',
2894 );
2895  
2896 Sends a POST request to C<$url>.
2897  
2898 A C<Content-Length> header will be automatically calculated if
2899 it is not given.
2900  
2901 The following options are recognized:
2902  
2903 =over 4
2904  
2905 =item *
2906  
2907 C<headers> - a hash of HTTP headers to send. If not given,
2908 the content type will be generated automatically.
2909  
2910 =item *
2911  
2912 C<data> - the raw data to send, if you've encoded it already.
2913  
2914 =back
2915  
2916 =cut
2917  
2918 0 ▶sub post {
Subroutine post: not called CC=2 SCAR=17.9
Pod documented
2919 0 my ($self, $url, %options) = @_;
2920 #my $b = $self->tab->{linkedBrowser};
2921 0 $self->invalidate_cached_values;
2922  
2923 #my $flags = 0;
2924 #if ($options{no_cache}) {
2925 # $flags = $self->repl->constant('nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE');
2926 #};
2927  
2928 # If we don't have data, encode the parameters:
2929 0 ▶ if( !$options{ data }) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options{"data"}) 0 0 0
2930 0 my $req= HTTP::Request::Common::POST( $url, $options{params} );
2931 #warn $req->content;
2932 0 carp "Faking content from parameters is not yet supported.";
2933 #$options{ data } = $req->content;
2934 };
2935  
2936 #$options{ charset } ||= 'utf-8';
2937 #$options{ headers } ||= {};
2938 #$options{ headers }->{"Content-Type"} ||= "application/x-www-form-urlencoded";
2939 #if( $options{ charset }) {
2940 # $options{ headers }->{"Content-Type"} .= "; charset=$options{ charset }";
2941 #};
2942  
2943 # Javascript POST implementation taken from
2944 # http://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit
2945 0 $self->eval(<<'JS', $url, $options{ params }, 'POST');
2946 function (path, params, method) {
2947 method = method || "post"; // Set method to post by default if not specified.
2948  
2949 // The rest of this code assumes you are not using a library.
2950 // It can be made less wordy if you use one.
2951 var form = document.createElement("form");
2952 form.setAttribute("method", method);
2953 form.setAttribute("action", path);
2954  
2955 for(var key in params) {
2956 if(params.hasOwnProperty(key)) {
2957 var hiddenField = document.createElement("input");
2958 hiddenField.setAttribute("type", "hidden");
2959 hiddenField.setAttribute("name", key);
2960 hiddenField.setAttribute("value", params[key]);
2961  
2962 form.appendChild(hiddenField);
2963 }
2964 }
2965  
2966 document.body.appendChild(form);
2967 form.submit();
2968 }
2969 JS
2970 # Now, how to trick Selenium into fetching the response?
2971 }
2972  
2973 =head2 C<< $mech->reload( %options ) >>
2974  
2975 $mech->reload( ignoreCache => 1 )
2976  
2977 Acts like the reload button in a browser: repeats the current request.
2978 The history (as per the "back" method) is not altered.
2979  
2980 Returns the HTTP::Response object from the reload, or undef if there's no
2981 current request.
2982  
2983 =cut
2984  
2985 0 ▶sub reload( $self, %options ) {
Subroutine reload: not called CC=3 SCAR=24.8
Pod documented
2986 0 ▶ if( exists $options{ ignoreCache } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options{"ignoreCache"}) 0 0 0
2987 0 ▶ $options{ ignoreCache } = $options{ ignoreCache } ? JSON::true : JSON::false;
Branch: 1 branch
BranchTrueFalseTotal
$options{'ignoreCache'} ? : 0 0 0
2988 };
2989 0 ▶ $self->_mightNavigate( sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2990 0 $self->target->send_message('Page.reload', %options )
2991 0 }, navigates => 1, %options)
2992 ->get;
2993 }
2994  
2995 =head2 C<< $mech->set_download_directory( $dir ) >>
2996  
2997 my $downloads = tempdir();
2998 $mech->set_download_directory( $downloads );
2999  
3000 Enables automatic file downloads and sets the directory where the files
3001 will be downloaded to. Setting this to undef will disable downloads again.
3002  
3003 The directory in C<$dir> must be an absolute path, since Chrome does not know
3004 about the current directory of your Perl script.
3005  
3006 =cut
3007  
3008 0 ▶sub set_download_directory_future( $self, $dir="" ) {
Subroutine set_download_directory_future: not called CC=3 SCAR=24.8
Pod undocumented
3009 0 $self->{download_directory} = $dir;
3010 0 my $res;
3011 0 ▶ if( "" eq $dir ) {
Branch: 1 branch
BranchTrueFalseTotal
if ('' eq $dir) { } 0 0 0
3012 0 $res = $self->target->send_message('Page.setDownloadBehavior',
3013 behavior => 'deny',
3014 );
3015  
3016 } else {
3017 0 $res = $self->target->send_message('Page.setDownloadBehavior',
3018 behavior => 'allow',
3019 downloadPath => $dir
3020 )
3021 };
3022 0 return $res
3023 };
3024  
3025 0 ▶sub set_download_directory( $self, $dir="" ) {
Subroutine set_download_directory: not called CC=2 SCAR=17.9
Pod documented
3026 0 $self->set_download_directory_future($dir)->get
3027 };
3028  
3029 =head2 C<< $mech->cookie_jar >>
3030  
3031 my $cookies = $mech->cookie_jar
3032  
3033 Returns all the Chrome cookies in a L<HTTP::Cookies::ChromeDevTools> instance.
3034 Setting a cookie in there will also set the cookie in Chrome. Note that
3035 the C<< ->cookie_jar >> does not automatically refresh when a new page is
3036 loaded. To manually refresh the state of the cookie jar, use:
3037  
3038 $mech->get('https://example.com/some_page');
3039 $mech->cookie_jar->load;
3040  
3041 =cut
3042  
3043 0 ▶sub cookie_jar( $self ) {
Subroutine cookie_jar: not called CC=2 SCAR=17.9
Pod documented
3044 0 ▶ $self->{cookie_jar} ||= do {
Condition0%0/3
$self->{"cookie_jar"} ||= do { my $c = "HTTP::Cookies::ChromeDevTools"->new("driver", $self->driver); $c->load; $c }
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"cookie_jar"} ||= do { my $c = "HTTP::Cookies::ChromeDevTools"->new("driver", $self->driver); $c->load; $c }
$self->{"cookie_jar"} do { my $c = "HTTP::Cookies::ChromeDevTools"->new("driver", $self->driver); $c->load; $c }
Truth table0%0/3
A ||= B
A= $self->{"cookie_jar"}B= do { my $c = "HTTP::Cookies::ChromeDevTools"->new("driver", $self->driver); $c->load; $c }
ABresult
1X1
011
000
3045 0 my $c = HTTP::Cookies::ChromeDevTools->new( driver => $self->driver );
3046 0 $c->load;
3047 0 $c
3048 };
3049 };
3050  
3051 =head2 C<< $mech->add_header( $name => $value, ... ) >>
3052  
3053 $mech->add_header(
3054 'X-WWW-Mechanize-Chrome' => "I'm using it",
3055 Encoding => 'text/klingon',
3056 );
3057  
3058 This method sets up custom headers that will be sent with B<every> HTTP(S)
3059 request that Chrome makes. If you are sending host-sensitive headers, these
3060 will also be sent again if the host issues a redirect. B<Avoid> setting
3061 an C<Authorization> header here, for example, if you are not certain that
3062 the receiving host will not redirect Chrome.
3063  
3064 Note that currently, we only support one value per header.
3065  
3066 Chrome since version 63+ does not allow setting and sending the C<Referer>
3067 header anymore. The bug report is
3068 at L<https://bugs.chromium.org/p/chromium/issues/detail?id=849972>.
3069  
3070 =cut
3071  
3072 0 ▶sub _set_extra_headers_future( $self, %headers ) {
Subroutine _set_extra_headers_future: not called CC=2 SCAR=17.9
3073 0 $self->log('debug',"Setting additional headers", \%headers);
3074 # force-stringify all header values
3075 0 for (values %headers) { $_ = "$_" };
3076 0 $self->target->send_message('Network.setExtraHTTPHeaders',
3077 headers => \%headers
3078 );
3079 };
3080  
3081 0 ▶sub _set_extra_headers( $self, %headers ) {
Subroutine _set_extra_headers: not called CC=1 SCAR=6.9
3082 0 $self->_set_extra_headers_future(
3083 %headers
3084 )->get;
3085 };
3086  
3087 0 ▶sub add_header( $self, %headers ) {
Subroutine add_header: not called CC=1 SCAR=6.9
Pod documented
3088 $self->{ extra_headers } = {
3089 0 %{ $self->{ extra_headers } },
3090 %headers,
3091 };
3092 0 $self->_set_extra_headers( %{ $self->{ extra_headers } } );
3093 };
3094  
3095 =head2 C<< $mech->delete_header( $name , $name2... ) >>
3096  
3097 $mech->delete_header( 'User-Agent' );
3098  
3099 Removes HTTP headers from the agent's list of special headers. Note
3100 that Chrome may still send a header with its default value.
3101  
3102 =cut
3103  
3104 0 ▶sub delete_header( $self, @headers ) {
Subroutine delete_header: not called CC=1 SCAR=6.9
Pod documented
3105 0 delete @{ $self->{ extra_headers } }{ @headers };
3106 0 $self->_set_extra_headers( %{ $self->{ extra_headers } } );
3107 };
3108  
3109 =head2 C<< $mech->reset_headers >>
3110  
3111 $mech->reset_headers();
3112  
3113 Removes all custom headers and makes Chrome send its defaults again.
3114  
3115 =cut
3116  
3117 0 ▶sub reset_headers( $self ) {
Subroutine reset_headers: not called CC=1 SCAR=6.9
Pod documented
3118 0 $self->{ extra_headers } = {};
3119 0 $self->_set_extra_headers();
3120 };
3121  
3122 =head2 C<< $mech->block_urls() >>
3123  
3124 $mech->block_urls( '//facebook.com/js/conversions/tracking.js' );
3125  
3126 Sets the list of blocked URLs. These URLs will not be retrieved by Chrome
3127 when loading a page. This is useful to eliminate tracking images or to test
3128 resilience in face of bad network conditions.
3129  
3130 =cut
3131  
3132 0 ▶sub block_urls( $self, @urls ) {
Subroutine block_urls: not called CC=1 SCAR=6.9
Pod documented
3133 0 $self->target->send_message( 'Network.setBlockedURLs',
3134 urls => \@urls
3135 )->get;
3136 }
3137  
3138 =head2 C<< $mech->res() >> / C<< $mech->response(%options) >>
3139  
3140 my $response = $mech->response(headers => 0);
3141  
3142 Returns the current response as a L<HTTP::Response> object.
3143  
3144 =cut
3145  
3146 0 ▶sub response( $self ) {
Subroutine response: not called CC=1 SCAR=6.9
Pod documented
3147 $self->{response}
3148 0 };
3149  
3150 {
3151 69 ▶ no warnings 'once';
Subroutine BEGIN: called CC=1 SCAR=0.0
3152 69 *res = \&response;
3153 }
3154  
3155 # Call croak or log it, depending on the C< autodie > setting
3156 0 ▶sub signal_condition {
Subroutine signal_condition: not called CC=2 SCAR=17.9
Pod undocumented
3157 0 my ($self,$msg) = @_;
3158 0 ▶ if ($self->{autodie}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'autodie'}) { } 0 0 0
3159 0 croak $msg
3160 } else {
3161 0 $self->log( 'warn', $msg );
3162 }
3163 };
3164  
3165 # Call croak on the C< autodie > setting if we have a non-200 status
3166 0 ▶sub signal_http_status {
Subroutine signal_http_status: not called CC=6 SCAR=37.4
Pod undocumented
3167 0 my ($self) = @_;
3168 0 ▶ if ($self->{autodie}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'autodie'}) { } 0 0 0
3169 0 ▶ if ($self->status and $self->status !~ /^2/ and $self->status != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->status and not $self->status =~ /^2/u and $self->status != 0) 0 0 0
Condition0%0/6
$self->status and not $self->status =~ /^2/u and $self->status != 0
!ll&&!rl&&r
000
$self->status and not $self->status =~ /^2/u
!ll&&!rl&&r
000
MC/DC0%0/3
$self->status and not $self->status =~ /^2/u and $self->status != 0
$self->status not $self->status =~ /^2/u $self->status != 0
Truth table0%0/4
A and not(B) and C
A= $self->statusB= not $self->status =~ /^2/uC= $self->status != 0
ABCresult
0XX0
10X0
1100
1111
3170 # there was an error
3171 0 ▶ croak ($self->response()->message || sprintf "Got status code %d", $self->status );
Condition0%0/3
$self->response->message || sprintf('Got status code %d', $self->status)
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->response->message || sprintf('Got status code %d', $self->status)
$self->response->message sprintf('Got status code %d', $self->status)
Truth table0%0/3
A || B
A= $self->response->messageB= sprintf('Got status code %d', $self->status)
ABresult
1X1
011
000
3172 };
3173 } else {
3174 # silent
3175 }
3176 };
3177  
3178 =head2 C<< $mech->success() >>
3179  
3180 $mech->get('https://google.com');
3181 print "Yay"
3182 if $mech->success();
3183  
3184 Returns a boolean telling whether the last request was successful.
3185 If there hasn't been an operation yet, returns false.
3186  
3187 This is a convenience function that wraps C<< $mech->res->is_success >>.
3188  
3189 =cut
3190  
3191 0 ▶sub success {
Subroutine success: not called CC=2 SCAR=17.9
Pod documented
3192 0 my $res = $_[0]->response();
3193 0 ▶ $res and $res->is_success
Branch: 1 branch
BranchTrueFalseTotal
$res and $res->is_success 0 0 0
3194 }
3195  
3196 =head2 C<< $mech->status() >>
3197  
3198 $mech->get('https://google.com');
3199 print $mech->status();
3200 # 200
3201  
3202 Returns the HTTP status code of the response.
3203 This is a 3-digit number like 200 for OK, 404 for not found, and so on.
3204  
3205 =cut
3206  
3207 0 ▶sub status {
Subroutine status: not called CC=1 SCAR=6.9
Pod documented
3208 0 my ($self) = @_;
3209 0 return $self->response()->code
3210 };
3211  
3212 =head2 C<< $mech->back() >>
3213  
3214 $mech->back();
3215  
3216 Goes one page back in the page history.
3217  
3218 Returns the (new) response.
3219  
3220 =cut
3221  
3222 0 ▶sub back( $self, %options ) {
Subroutine back: not called CC=1 SCAR=6.9
Pod documented
3223 0 ▶ $self->_mightNavigate( sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3224 0 ▶ $self->target->send_message('Page.getNavigationHistory')->then(sub($history) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3225 0 my $entry = $history->{entries}->[ $history->{currentIndex}-1 ];
3226 $self->target->send_message('Page.navigateToHistoryEntry', entryId => $entry->{id})
3227 0 });
3228 0 }, navigates => 1, %options)
3229 ->get;
3230 };
3231  
3232 =head2 C<< $mech->forward() >>
3233  
3234 $mech->forward();
3235  
3236 Goes one page forward in the page history.
3237  
3238 Returns the (new) response.
3239  
3240 =cut
3241  
3242 0 ▶sub forward( $self, %options ) {
Subroutine forward: not called CC=1 SCAR=6.9
Pod documented
3243 0 ▶ $self->_mightNavigate( sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3244 0 ▶ $self->target->send_message('Page.getNavigationHistory')->then(sub($history) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3245 0 my $entry = $history->{entries}->[ $history->{currentIndex}+1 ];
3246 $self->target->send_message('Page.navigateToHistoryEntry', entryId => $entry->{id})
3247 0 });
3248 0 }, navigates => 1, %options)
3249 ->get;
3250 }
3251  
3252 =head2 C<< $mech->stop() >>
3253  
3254 $mech->stop();
3255  
3256 Stops all loading in Chrome, as if you pressed C<ESC>.
3257  
3258 This function is mostly of use in callbacks or in a timer callback from your
3259 event loop.
3260  
3261 =cut
3262  
3263 0 ▶sub stop( $self ) {
Subroutine stop: not called CC=1 SCAR=6.9
Pod documented
3264 0 $self->target->send_message('Page.stopLoading')->get;
3265 }
3266  
3267 =head2 C<< $mech->uri() >>
3268  
3269 =head2 C<< $mech->uri_future() >>
3270  
3271 print "We are at " . $mech->uri;
3272 print "We are at " . $mech->uri_future->get;
3273  
3274 Returns the current document URI.
3275  
3276 =cut
3277  
3278 0 ▶sub uri_future( $self ) {
Subroutine uri_future: not called CC=1 SCAR=6.9
Pod documented
3279 0 ▶ $self->_cached_document->then(sub ($d) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3280 0 return Future->done( URI->new( $d->{root}->{documentURL} ))
3281 0 });
3282 }
3283  
3284 0 ▶sub uri( $self ) {
Subroutine uri: not called CC=1 SCAR=6.9
Pod documented
3285 0 $self->uri_future->get
3286 }
3287  
3288  
3289 =head2 C<< $mech->infinite_scroll( [$wait_time_in_seconds] ) >>
3290  
3291 $new_content_found = $mech->infinite_scroll(3);
3292  
3293 Loads content into pages that have "infinite scroll" capabilities by scrolling
3294 to the bottom of the web page and waiting up to the number of seconds, as set by
3295 the optional C<$wait_time_in_seconds> argument, for the browser to load more
3296 content. The default is to wait up to 20 seconds. For reasonably fast sites,
3297 the wait time can be set much lower.
3298  
3299 The method returns a boolean C<true> if new content is loaded, C<false>
3300 otherwise. You can scroll to the end (if there is one) of an infinitely
3301 scrolling page like so:
3302  
3303 while( $mech->infinite_scroll ) {
3304 # Tests for exiting the loop earlier
3305 last if $count++ >= 10;
3306 }
3307  
3308 =cut
3309  
3310 0 ▶sub infinite_scroll {
Subroutine infinite_scroll: not called CC=4 SCAR=30.0
Pod documented
3311 0 my $self = shift;
3312 0 ▶ my $wait_time = shift || 20;
Condition0%0/2
shift() || 20
l!l
00
MC/DC0%0/1
shift() || 20
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
3313  
3314 0 my $current_height = $self->_get_body_height;
3315 0 $self->log('debug', "Current page body height: $current_height");
3316  
3317 0 $self->_scroll_to_bottom;
3318  
3319 0 my $new_height = $self->_get_body_height;
3320 0 $self->log('debug', "New page body height: $new_height");
3321  
3322 0 my $start_time = time();
3323 0 ▶ while (!($new_height > $current_height)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($new_height > $current_height) 0 0 0
3324  
3325 # wait for new elements to load until $wait_time is reached
3326 0 ▶ if (time() - $start_time > $wait_time) {
Branch: 1 branch
BranchTrueFalseTotal
if (time - $start_time > $wait_time) 0 0 0
3327 0 return 0;
3328 }
3329  
3330 # wait 1/10th sec for new elements to load
3331 0 $self->sleep(0.1);
3332 0 $new_height = $self->_get_body_height;
3333 }
3334 0 return 1;
3335 }
3336  
3337 0 ▶sub _get_body_height {
Subroutine _get_body_height: not called CC=1 SCAR=6.9
3338 0 my $self = shift;
3339  
3340 0 my ($height) = $self->eval( 'document.body.scrollHeight' );
3341 0 return $height;
3342 }
3343  
3344 0 ▶sub _scroll_to_bottom {
Subroutine _scroll_to_bottom: not called CC=1 SCAR=6.9
3345 0 my $self = shift;
3346  
3347 # scroll to bottom and wait for some content to load
3348 0 $self->eval( 'window.scroll(0,document.body.scrollHeight + 200)' );
3349 0 $self->sleep(0.1);
3350 }
3351  
3352 =head1 CONTENT METHODS
3353  
3354 =head2 C<< $mech->document_future() >>
3355  
3356 =head2 C<< $mech->document() >>
3357  
3358 print $self->document->{nodeId};
3359  
3360 Returns the C<document> node.
3361  
3362 This is WWW::Mechanize::Chrome specific.
3363  
3364 =cut
3365  
3366 0 ▶sub _cached_document($self) {
Subroutine _cached_document: not called CC=2 SCAR=13.0
3367 0 ▶ if( $self->{_document}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_document'}) { } 0 0 0
3368 #warn "Cached document";
3369 return Future->done( $self->{_document} )
3370  
3371 0 } else {
3372 #warn "Requesting fresh document";
3373 0 weaken( my $s = $self );
3374 0 ▶ return $self->document_future->then(sub ($d) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3375 #warn "Have fresh document";
3376 0 $s->{_document} = $d;
3377 Future->done( $s->{_document} )
3378 0 ▶ })->catch(sub(@error) {
Subroutine __ANON__: not called CC=1 SCAR=0.6
3379 69 ▶ use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
3380 0 warn "Error while retrieving document:".Dumper \@error;
3381 0 });
3382 }
3383 }
3384  
3385 0 ▶sub _clear_cached_document {
Subroutine _clear_cached_document: not called CC=1 SCAR=6.9
3386 0 delete $_[0]->{_document};
3387 };
3388  
3389 # Move to DOMSnapshot.captureSnapshot / DOMSnapshot.DocumentSnapshot instead
3390 0 ▶sub document_future( $self ) {
Subroutine document_future: not called CC=1 SCAR=6.9
Pod documented
3391 0 return $self->target->send_message('DOM.getDocument', depth => -1, pierce => JSON::false );
3392 }
3393  
3394 0 ▶sub document( $self ) {
Subroutine document: not called CC=1 SCAR=6.9
Pod documented
3395 0 $self->_cached_document->get
3396 }
3397  
3398 0 ▶sub decoded_content($self) {
Subroutine decoded_content: not called CC=3 SCAR=24.8
Pod undocumented
3399 0 my $res;
3400 0 ▶ my $ct = $self->ct || 'text/html';
Condition0%0/2
$self->ct || 'text/html'
l!l
00
MC/DC0%0/1
$self->ct || 'text/html'
$self->ct
Truth table0%0/2
A
A= $self->ct
Aresult
11
00
3401 0 ▶ if( $ct eq 'text/html' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ct eq 'text/html') { } 0 0 0
3402 0 ▶ $res = $self->_cached_document->then(sub( $root ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3403 # Join _all_ child nodes together to also fetch DOCTYPE nodes
3404 # and the stuff that comes after them
3405  
3406 my @content = map {
3407 0 my $nodeId = $_->{nodeId};
3408 0 $self->log('trace', "Fetching HTML for node " . $nodeId );
3409 0 $self->target->send_message('DOM.getOuterHTML', nodeId => 0+$nodeId )
3410 0 } @{ $root->{root}->{children} };
3411  
3412 return Future->wait_all( @content )
3413 0 ▶ ->then( sub( @outerHTML_f ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3414 0 Future->done( join "", map { $_->get->{outerHTML} } @outerHTML_f );
3415 0 });
3416 0 });
3417 } else {
3418 # Return the raw body
3419 #use Data::Dumper;
3420 #warn Dumper $self->response;
3421 #warn $self->response->content;
3422  
3423 # The content is already decoded (?!)
3424 # I'm not sure how well this plays with encodings, and
3425 # binary content
3426 0 $res = Future->done($self->response->content);
3427 };
3428 0 return $res->get
3429 };
3430  
3431 =head2 C<< $mech->content( %options ) >>
3432  
3433 print $mech->content;
3434 print $mech->content( format => 'html' ); # default
3435 print $mech->content( format => 'text' ); # identical to ->text
3436 print $mech->content( format => 'mhtml' ); # identical to ->captureSnapshot
3437  
3438 This always returns the content as a Unicode string. It tries
3439 to decode the raw content according to its input encoding.
3440 This currently only works for HTML pages, not for images etc.
3441  
3442 Recognized options:
3443  
3444 =over 4
3445  
3446 =item *
3447  
3448 C<format> - the stuff to return
3449  
3450 The allowed values are C<html> and C<text>. The default is C<html>.
3451  
3452 =back
3453  
3454 =cut
3455  
3456 0 ▶sub content( $self, %options ) {
Subroutine content: not called CC=5 SCAR=34.0
Pod documented
3457 0 ▶ $options{ format } ||= 'html';
Condition0%0/2
$options{"format"} ||= "html"
l!l
00
MC/DC0%0/1
$options{"format"} ||= "html"
$options{"format"}
Truth table0%0/2
A
A= $options{"format"}
Aresult
11
00
3458 0 my $format = delete $options{ format };
3459  
3460 0 my $content;
3461 0 ▶ if( 'html' eq $format ) {
Branch: 3 branches
BranchTrueFalseTotal
if ('html' eq $format) { } 0 0 0
elsif ($format eq 'text') { } 0 0 0
elsif ($format eq 'mhtml') { } 0 0 0
3462 0 $content= $self->decoded_content()
3463 } elsif ( $format eq 'text' ) {
3464 0 $content= $self->text;
3465 } elsif ( $format eq 'mhtml' ) {
3466 0 $content= $self->captureSnapshot()->{data};
3467 } else {
3468 0 die qq{Unknown "format" parameter "$format"};
3469 };
3470 };
3471  
3472 =head2 C<< $mech->text() >>
3473  
3474 print $mech->text();
3475  
3476 Returns the text of the current HTML content. If the content isn't
3477 HTML, $mech will die.
3478  
3479 =cut
3480  
3481 0 ▶sub text {
Subroutine text: not called CC=1 SCAR=6.9
Pod documented
3482 0 my $self = shift;
3483  
3484 # Waugh - this is highly inefficient but conveniently short to write
3485 # Maybe this should skip SCRIPT nodes...
3486 0 join '', map { $_->get_attribute('innerText', live => 1) } $self->xpath('//body', single => 1 );
3487 }
3488  
3489 =head2 C<< $mech->captureSnapshot_future() >>
3490  
3491 =head2 C<< $mech->captureSnapshot() >>
3492  
3493 print $mech->captureSnapshot( format => 'mhtml' )->{data};
3494  
3495 Returns the current page as MHTML.
3496  
3497 This is WWW::Mechanize::Chrome specific.
3498  
3499 =cut
3500  
3501 0 ▶sub captureSnapshot_future( $self, %options ) {
Subroutine captureSnapshot_future: not called CC=1 SCAR=6.9
Pod documented
3502 0 $self->target->send_message( 'Page.captureSnapshot', %options )
3503 }
3504  
3505 0 ▶sub captureSnapshot( $self, %options ) {
Subroutine captureSnapshot: not called CC=1 SCAR=6.9
Pod documented
3506 0 $self->captureSnapshot_future(%options)->get
3507 }
3508  
3509 =head2 C<< $mech->content_encoding() >>
3510  
3511 print "The content is encoded as ", $mech->content_encoding;
3512  
3513 Returns the encoding that the content is in. This can be used
3514 to convert the content from UTF-8 back to its native encoding.
3515  
3516 =cut
3517  
3518 0 ▶sub content_encoding {
Subroutine content_encoding: not called CC=3 SCAR=24.8
Pod documented
3519 0 my ($self) = @_;
3520 # Let's trust the <meta http-equiv first, and the header second:
3521 # Also, a pox on Chrome for not having lower-case or upper-case
3522 0 ▶ if(( my $meta )= $self->xpath( q{//meta[translate(@http-equiv,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')="content-type"]}, first => 1 )) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($meta) = $self->xpath("//meta[translate(\@http-equiv,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')=\"content-type\"]", "first", 1)) 0 0 0
3523 0 (my $ct= $meta->{attributes}->{'content'}) =~ s/^.*;\s*charset=\s*//i;
3524 0 ▶ return $ct
Branch: 1 branch
BranchTrueFalseTotal
if $ct 0 0 0
3525 if( $ct );
3526 };
3527 0 $self->response->header('Content-Type');
3528 };
3529  
3530 =head2 C<< $mech->update_html( $html ) >>
3531  
3532 $mech->update_html($html);
3533  
3534 Writes C<$html> into the current document. This is mostly
3535 implemented as a convenience method for L<HTML::Display::MozRepl>.
3536  
3537 The value passed in as C<$html> will be stringified.
3538  
3539 =cut
3540  
3541 0 ▶sub update_html_future( $self, $content ) {
Subroutine update_html_future: not called CC=1 SCAR=2.8
Pod undocumented
3542 0 my $doc = $self->_cached_document;
3543 0 ▶ return $doc->then(sub( $root ) {
Subroutine __ANON__: not called CC=2 SCAR=11.6
3544 # Find "HTML" child node:
3545 0 my $nodeId = $root->{root}->{children}->[0]->{nodeId};
3546 0 my $id;
3547 0 ▶ if( ! $nodeId ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $nodeId) { } 0 0 0
3548 69 ▶ use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
3549 0 warn Dumper $root;
3550 0 warn "Need / fetching nodeId from backendNodeId";
3551  
3552 0 my @parentNodes; # we only expect one ...
3553 0 ▶ my $setChildNodes = $self->add_listener('DOM.setChildNodes', sub( $ev ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3554 #use Data::Dumper; warn "setChildNodes: "; warn Dumper $ev;
3555 0 push @parentNodes, @{ $ev->{params}->{nodes} };
3556 0 });
3557  
3558 $id = $self->target->send_message('DOM.resolveNode', backendNodeId => $root->{root}->{children}->[0]->{backendNodeId} )
3559 0 ▶ ->then( sub ( $nodeInfo ) {
Subroutine __ANON__: not called CC=1 SCAR=0.6
3560 69 ▶ use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
3561 0 warn Dumper $nodeInfo;
3562 $self->target->send_message('DOM.requestNode', objectId => $nodeInfo->{object}->{objectId})
3563 #return Future->done( $nodeInfo->{node}->{nodeId} )
3564 0 ▶ })->catch(sub( @error ) {
Subroutine __ANON__: not called CC=1 SCAR=1.2
3565 69 ▶ use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
3566 0 warn "Couldn't find node: @error";
3567 0 warn Dumper \@error;
3568 0 ▶ })->then(sub ( $node ) {
Subroutine __ANON__: not called CC=1 SCAR=1.2
3569  
3570 # Implicitly, @parentNodes has been filled ...
3571  
3572 69 ▶ use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
3573 0 warn Dumper $node;
3574 return Future->done( $node->{nodeId} )
3575 #return Future->done( $childNodes[0]->{nodeId} )
3576 0 });
3577  
3578 } else {
3579 0 $id = $self->target->future->done( $nodeId );
3580 };
3581  
3582 0 ▶ $id->then( sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3583 0 $self->log('trace', "Setting HTML for node " . $nodeId );
3584 $self->target->send_message('DOM.setOuterHTML', nodeId => 0+$nodeId, outerHTML => "$content" )
3585 0 ▶ ->then(sub {;
Subroutine __ANON__: not called CC=1 SCAR=6.9
3586 0 $self->invalidate_cached_values;
3587 0 Future->done()
3588 })
3589  
3590 # Also, we need to wait for a DOM.documentUpdated here before querying
3591 # again ... do we?!
3592 0 });
3593 0 });
3594 };
3595  
3596 0 ▶sub update_html( $self, $content ) {
Subroutine update_html: not called CC=1 SCAR=6.9
Pod documented
3597 0 $self->update_html_future($content)->get
3598 }
3599 =head2 C<< $mech->base() >>
3600  
3601 print $mech->base;
3602  
3603 Returns the URL base for the current page.
3604  
3605 The base is either specified through a C<base>
3606 tag or is the current URL.
3607  
3608 This method is specific to WWW::Mechanize::Chrome.
3609  
3610 =cut
3611  
3612 0 ▶sub base {
Subroutine base: not called CC=4 SCAR=30.0
Pod undocumented
3613 0 my ($self) = @_;
3614 0 (my $base) = $self->selector('base');
3615 $base = $base->get_attribute('href', live => 1)
3616 0 ▶ if $base && defined ($base->{nodeId});
Branch: 1 branch
BranchTrueFalseTotal
if $base and defined $base->{"nodeId"} 0 0 0
Condition0%0/3
$base and defined $base->{"nodeId"}
!ll&&!rl&&r
000
MC/DC0%0/2
$base and defined $base->{"nodeId"}
$base defined $base->{"nodeId"}
Truth table0%0/3
A and B
A= $baseB= defined $base->{"nodeId"}
ABresult
0X0
100
111
3617 0 ▶ $base ||= $self->uri;
Condition0%0/3
$base ||= $self->uri
l!l&&r!l&&!r
000
MC/DC0%0/2
$base ||= $self->uri
$base $self->uri
Truth table0%0/3
A ||= B
A= $baseB= $self->uri
ABresult
1X1
011
000
3618 };
3619  
3620 =head2 C<< $mech->content_type() >>
3621  
3622 =head2 C<< $mech->ct() >>
3623  
3624 print $mech->content_type;
3625  
3626 Returns the content type of the currently loaded document
3627  
3628 =cut
3629  
3630 0 ▶sub content_type {
Subroutine content_type: not called CC=5 SCAR=34.0
Pod documented
3631 0 my ($self) = @_;
3632 # Let's trust the <meta http-equiv first, and the header second:
3633 # Also, a pox on Chrome for not having lower-case or upper-case
3634 0 my $ct;
3635 0 ▶ if(my( $meta )= $self->xpath( q{//meta[translate(@http-equiv,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')="content-type"]}, first => 1 )) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($meta) = $self->xpath("//meta[translate(\@http-equiv,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')=\"content-type\"]", "first", 1)) 0 0 0
3636 0 $ct= $meta->{attributes}->{'content'};
3637 };
3638 0 ▶ if(!$ct and my $r= $self->response ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $ct and my $r = $self->response) 0 0 0
Condition0%0/3
not $ct and my $r = $self->response
!ll&&!rl&&r
000
MC/DC0%0/2
not $ct and my $r = $self->response
not $ct my $r = $self->response
Truth table0%0/3
not(A) and B
A= not $ctB= my $r = $self->response
ABresult
0X0
100
111
3639  
3640 0 my $h= $r->headers;
3641 0 $ct= $h->header('Content-Type');
3642 };
3643 0 ▶ $ct =~ s/;.*$// if defined $ct;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ct 0 0 0
3644 0 $ct
3645 };
3646  
3647 {
3648 69 ▶ no warnings 'once';
Subroutine BEGIN: called CC=1 SCAR=0.0
3649 69 *ct = \&content_type;
3650 }
3651  
3652 =head2 C<< $mech->is_html() >>
3653  
3654 print $mech->is_html();
3655  
3656 Returns true/false on whether our content is HTML, according to the
3657 HTTP headers.
3658  
3659 =cut
3660  
3661 0 ▶sub is_html {
Subroutine is_html: not called CC=2 SCAR=17.9
Pod documented
3662 0 my $self = shift;
3663 0 ▶ return defined $self->ct && ($self->ct eq 'text/html');
Condition0%0/3
defined $self->ct && $self->ct eq 'text/html'
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->ct && $self->ct eq 'text/html'
defined $self->ct $self->ct eq 'text/html'
Truth table0%0/3
A && B
A= defined $self->ctB= $self->ct eq 'text/html'
ABresult
0X0
100
111
3664 }
3665  
3666 =head2 C<< $mech->title() >>
3667  
3668 print "We are on page " . $mech->title;
3669  
3670 Returns the current document title.
3671  
3672 =cut
3673  
3674 0 ▶sub title( $self ) {
Subroutine title: not called CC=1 SCAR=6.9
Pod documented
3675 $self->target->info->{title}
3676 0 };
3677  
3678 =head1 EXTRACTION METHODS
3679  
3680 =head2 C<< $mech->links() >>
3681  
3682 print $_->text . " -> " . $_->url . "\n"
3683 for $mech->links;
3684  
3685 Returns all links in the document as L<WWW::Mechanize::Link> objects.
3686  
3687 Currently accepts no parameters. See C<< ->xpath >>
3688 or C<< ->selector >> when you want more control.
3689  
3690 =cut
3691  
3692 69 our %link_spec = (
3693 a => { url => 'href', },
3694 area => { url => 'href', },
3695 frame => { url => 'src', },
3696 iframe => { url => 'src', },
3697 link => { url => 'href', },
3698 meta => { url => 'content', xpath => (join '',
3699 q{translate(@http-equiv,'ABCDEFGHIJKLMNOPQRSTUVWXYZ',},
3700 q{'abcdefghijklmnopqrstuvwxyz')="refresh"}), },
3701 );
3702 # taken from WWW::Mechanize. This should possibly just be reused there
3703 0 ▶sub make_link {
Subroutine make_link: not called CC=7 SCAR=40.3
Pod undocumented
3704 0 my ($self,$node,$base) = @_;
3705  
3706 0 my $tag = lc $node->get_tag_name;
3707 0 my $url;
3708 0 ▶ if ($tag) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tag) 0 0 0
3709 0 ▶ if( ! exists $link_spec{ $tag }) {
Branch: 1 branch
BranchTrueFalseTotal
if (not exists $WWW::Mechanize::Chrome::link_spec{$tag}) { } 0 0 0
3710 0 carp "Unknown link-spec tag '$tag'";
3711 0 $url= '';
3712 } else {
3713 0 $url = $node->get_attribute( $link_spec{ $tag }->{url}, live => 1 );
3714 };
3715 };
3716  
3717 0 ▶ if ($tag eq 'meta') {
Branch: 1 branch
BranchTrueFalseTotal
if ($tag eq "meta") 0 0 0
3718 0 my $content = $url;
3719 0 ▶ if ( $content =~ /^\d+\s*;\s*url\s*=\s*(\S+)/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content =~ /^\d+\s*;\s*url\s*=\s*(\S+)/iu) { } 0 0 0
3720 0 $url = $1;
3721 0 ▶ $url =~ s/^"(.+)"$/$1/ or $url =~ s/^'(.+)'$/$1/;
Branch: 1 branch
BranchTrueFalseTotal
$url =~ s/^"(.+)"$/$1/u or $url =~ s/^'(.+)'$/$1/u 0 0 0
3722 }
3723 else {
3724 0 undef $url;
3725 }
3726 };
3727  
3728 0 ▶ if (defined $url) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $url) { } 0 0 0
3729 #my $text => $node->get_attribute('text'),
3730 0 my $text = $node->get_text;
3731 0 $text =~ s!\A\s+!!s;
3732 0 $text =~ s!\s+\z!!s;
3733 0 my $res = WWW::Mechanize::Link->new({
3734 tag => $tag,
3735 name => $node->get_attribute('name', live => 1),
3736 base => $base,
3737 url => $url,
3738 text => $text,
3739 attrs => {},
3740 });
3741 0 return $res
3742 } else {
3743 ()
3744 0 };
3745 }
3746  
3747 0 ▶sub links {
Subroutine links: not called CC=1 SCAR=6.9
Pod documented
3748 0 my ($self) = @_;
3749 0 my @links = $self->selector( join ",", sort keys %link_spec);
3750 0 my $base = $self->base;
3751 return map {
3752 0 $self->make_link($_,$base)
3753 } @links;
3754 };
3755  
3756 =head2 C<< $mech->selector( $css_selector, %options ) >>
3757  
3758 my @text = $mech->selector('p.content');
3759  
3760 Returns all nodes matching the given CSS selector. If
3761 C<$css_selector> is an array reference, it returns
3762 all nodes matched by any of the CSS selectors in the array.
3763  
3764 This takes the same options that C<< ->xpath >> does.
3765  
3766 This method is implemented via L<WWW::Mechanize::Plugin::Selector>.
3767  
3768 =cut
3769  
3770 0 ▶sub selector {
Subroutine selector: not called CC=5 SCAR=34.0
Pod documented
3771 0 my ($self,$query,%options) = @_;
3772 0 ▶ $options{ user_info } ||= "CSS selector '$query'";
Condition0%0/2
$options{"user_info"} ||= "CSS selector '${query}'"
l!l
00
MC/DC0%0/1
$options{"user_info"} ||= "CSS selector '${query}'"
$options{"user_info"}
Truth table0%0/2
A
A= $options{"user_info"}
Aresult
11
00
3773 0 ▶ if ('ARRAY' ne (ref $query || '')) {
Branch: 1 branch
BranchTrueFalseTotal
if ("ARRAY" ne (ref $query || "")) 0 0 0
Condition0%0/2
ref $query || ''
l!l
00
MC/DC0%0/1
ref $query || ''
ref $query
Truth table0%0/2
A
A= ref $query
Aresult
11
00
3774 0 $query = [$query];
3775 };
3776 0 ▶ my $root = $options{ node } ? './' : '';
Branch: 1 branch
BranchTrueFalseTotal
$options{'node'} ? : 0 0 0
3777 0 my @q = map { selector_to_xpath($_, root => $root) } @$query;
3778 0 $self->xpath(\@q, %options);
3779 };
3780  
3781 =head2 C<< $mech->find_link_dom( %options ) >>
3782  
3783 print $_->{innerHTML} . "\n"
3784 for $mech->find_link_dom( text_contains => 'CPAN' );
3785  
3786 A method to find links, like L<WWW::Mechanize>'s
3787 C<< ->find_links >> method. This method returns DOM objects from
3788 Chrome instead of WWW::Mechanize::Link objects.
3789  
3790 Note that Chrome
3791 might have reordered the links or frame links in the document
3792 so the absolute numbers passed via C<n>
3793 might not be the same between
3794 L<WWW::Mechanize> and L<WWW::Mechanize::Chrome>.
3795  
3796 The supported options are:
3797  
3798 =over 4
3799  
3800 =item *
3801  
3802 C<< text >> and C<< text_contains >> and C<< text_regex >>
3803  
3804 Match the text of the link as a complete string, substring or regular expression.
3805  
3806 Matching as a complete string or substring is a bit faster, as it is
3807 done in the XPath engine of Chrome.
3808  
3809 =item *
3810  
3811 C<< id >> and C<< id_contains >> and C<< id_regex >>
3812  
3813 Matches the C<id> attribute of the link completely or as part
3814  
3815 =item *
3816  
3817 C<< name >> and C<< name_contains >> and C<< name_regex >>
3818  
3819 Matches the C<name> attribute of the link
3820  
3821 =item *
3822  
3823 C<< url >> and C<< url_regex >>
3824  
3825 Matches the URL attribute of the link (C<href>, C<src> or C<content>).
3826  
3827 =item *
3828  
3829 C<< class >> - the C<class> attribute of the link
3830  
3831 =item *
3832  
3833 C<< n >> - the (1-based) index. Defaults to returning the first link.
3834  
3835 =item *
3836  
3837 C<< single >> - If true, ensure that only one element is found. Otherwise croak
3838 or carp, depending on the C<autodie> parameter.
3839  
3840 =item *
3841  
3842 C<< one >> - If true, ensure that at least one element is found. Otherwise croak
3843 or carp, depending on the C<autodie> parameter.
3844  
3845 The method C<croak>s if no link is found. If the C<single> option is true,
3846 it also C<croak>s when more than one link is found.
3847  
3848 =back
3849  
3850 =cut
3851  
3852 69 our %xpath_quote = (
3853 '"' => '\"',
3854 #"'" => "\\'",
3855 #'[' => '&#91;',
3856 #']' => '&#93;',
3857 #'[' => '[\[]',
3858 #'[' => '\[',
3859 #']' => '[\]]',
3860 );
3861  
3862 0 ▶sub quote_xpath {
Subroutine quote_xpath: not called CC=2 SCAR=17.9
Pod undocumented
3863 0 local $_ = $_[0];
3864 0 ▶ s/(['"\[\]])/$xpath_quote{$1} || $1/ge;
Condition0%0/3
$WWW::Mechanize::Chrome::xpath_quote{$1} || $1
l!l&&r!l&&!r
000
MC/DC0%0/2
$WWW::Mechanize::Chrome::xpath_quote{$1} || $1
$WWW::Mechanize::Chrome::xpath_quote{$1} $1
Truth table0%0/3
A || B
A= $WWW::Mechanize::Chrome::xpath_quote{$1}B= $1
ABresult
1X1
011
000
3865 0 $_
3866 };
3867  
3868 # Copied from WWW::Mechanize 1.97
3869 # Used by find_links to check for matches
3870 # The logic is such that ALL param criteria that are given must match
3871 0 ▶sub _match_any_link_params( $self, $link, $p ) {
Subroutine _match_any_link_params: not called CC=40 SCAR=74.0
3872 # No conditions, anything matches
3873 0 ▶ return 1 unless keys %$p;
Branch: 1 branch
BranchTrueFalseTotal
unless keys %$p 0 0 0
3874  
3875 0 ▶ return if defined $p->{url} && !($link->url eq $p->{url} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"url"} and not $link->url eq $p->{"url"} 0 0 0
Condition0%0/3
defined $p->{"url"} and not $link->url eq $p->{"url"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $p->{"url"} and not $link->url eq $p->{"url"}
defined $p->{"url"} not $link->url eq $p->{"url"}
Truth table0%0/3
A and not(B)
A= defined $p->{"url"}B= not $link->url eq $p->{"url"}
ABresult
0X0
100
111
3876 0 ▶ return if defined $p->{url_regex} && !($link->url =~ $p->{url_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"url_regex"} and not $link->url =~ /$p->{"url_regex"}/u 0 0 0
Condition0%0/3
defined $p->{"url_regex"} and not $link->url =~ /$p->{"url_regex"}/u
!ll&&!rl&&r
000
MC/DC0%0/2
defined $p->{"url_regex"} and not $link->url =~ /$p->{"url_regex"}/u
defined $p->{"url_regex"} not $link->url =~ /$p->{"url_regex"}/u
Truth table0%0/3
A and not(B)
A= defined $p->{"url_regex"}B= not $link->url =~ /$p->{"url_regex"}/u
ABresult
0X0
100
111
3877 0 ▶ return if defined $p->{url_abs} && !($link->url_abs eq $p->{url_abs} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"url_abs"} and not $link->url_abs eq $p->{"url_abs"} 0 0 0
Condition0%0/3
defined $p->{"url_abs"} and not $link->url_abs eq $p->{"url_abs"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $p->{"url_abs"} and not $link->url_abs eq $p->{"url_abs"}
defined $p->{"url_abs"} not $link->url_abs eq $p->{"url_abs"}
Truth table0%0/3
A and not(B)
A= defined $p->{"url_abs"}B= not $link->url_abs eq $p->{"url_abs"}
ABresult
0X0
100
111
3878 0 ▶ return if defined $p->{url_abs_regex} && !($link->url_abs =~ $p->{url_abs_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"url_abs_regex"} and not $link->url_abs =~ /$p->{"url_abs_regex"}/u 0 0 0
Condition0%0/3
defined $p->{"url_abs_regex"} and not $link->url_abs =~ /$p->{"url_abs_regex"}/u
!ll&&!rl&&r
000
MC/DC0%0/2
defined $p->{"url_abs_regex"} and not $link->url_abs =~ /$p->{"url_abs_regex"}/u
defined $p->{"url_abs_regex"} not $link->url_abs =~ /$p->{"url_abs_regex"}/u
Truth table0%0/3
A and not(B)
A= defined $p->{"url_abs_regex"}B= not $link->url_abs =~ /$p->{"url_abs_regex"}/u
ABresult
0X0
100
111
3879 0 ▶ return if defined $p->{text} && !(defined($link->text) && $link->text eq $p->{text} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"text"} and not defined $link->text && $link->text eq $p->{"text"} 0 0 0
Condition0%0/6
defined $p->{"text"} and not defined $link->text && $link->text eq $p->{"text"}
!ll&&!rl&&r
000
defined $link->text && $link->text eq $p->{'text'}
!ll&&!rl&&r
000
MC/DC0%0/3
defined $p->{"text"} and not defined $link->text && $link->text eq $p->{"text"}
defined $p->{"text"} defined $link->text $link->text eq $p->{'text'}
Truth table0%0/4
A and not(B && C)
A= defined $p->{"text"}B= defined $link->textC= $link->text eq $p->{'text'}
ABCresult
0XX0
1110
10X1
1101
3880 0 ▶ return if defined $p->{text_regex} && !(defined($link->text) && $link->text =~ $p->{text_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"text_regex"} and not defined $link->text && $link->text =~ /$p->{"text_regex"}/u 0 0 0
Condition0%0/6
defined $p->{"text_regex"} and not defined $link->text && $link->text =~ /$p->{"text_regex"}/u
!ll&&!rl&&r
000
defined $link->text && $link->text =~ /$p->{'text_regex'}/u
!ll&&!rl&&r
000
MC/DC0%0/3
defined $p->{"text_regex"} and not defined $link->text && $link->text =~ /$p->{"text_regex"}/u
defined $p->{"text_regex"} defined $link->text $link->text =~ /$p->{'text_regex'}/u
Truth table0%0/4
A and not(B && C)
A= defined $p->{"text_regex"}B= defined $link->textC= $link->text =~ /$p->{'text_regex'}/u
ABCresult
0XX0
1110
10X1
1101
3881 0 ▶ return if defined $p->{name} && !(defined($link->name) && $link->name eq $p->{name} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"name"} and not defined $link->name && $link->name eq $p->{"name"} 0 0 0
Condition0%0/6
defined $p->{"name"} and not defined $link->name && $link->name eq $p->{"name"}
!ll&&!rl&&r
000
defined $link->name && $link->name eq $p->{'name'}
!ll&&!rl&&r
000
MC/DC0%0/3
defined $p->{"name"} and not defined $link->name && $link->name eq $p->{"name"}
defined $p->{"name"} defined $link->name $link->name eq $p->{'name'}
Truth table0%0/4
A and not(B && C)
A= defined $p->{"name"}B= defined $link->nameC= $link->name eq $p->{'name'}
ABCresult
0XX0
1110
10X1
1101
3882 0 ▶ return if defined $p->{name_regex} && !(defined($link->name) && $link->name =~ $p->{name_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"name_regex"} and not defined $link->name && $link->name =~ /$p->{"name_regex"}/u 0 0 0
Condition0%0/6
defined $p->{"name_regex"} and not defined $link->name && $link->name =~ /$p->{"name_regex"}/u
!ll&&!rl&&r
000
defined $link->name && $link->name =~ /$p->{'name_regex'}/u
!ll&&!rl&&r
000
MC/DC0%0/3
defined $p->{"name_regex"} and not defined $link->name && $link->name =~ /$p->{"name_regex"}/u
defined $p->{"name_regex"} defined $link->name $link->name =~ /$p->{'name_regex'}/u
Truth table0%0/4
A and not(B && C)
A= defined $p->{"name_regex"}B= defined $link->nameC= $link->name =~ /$p->{'name_regex'}/u
ABCresult
0XX0
1110
10X1
1101
3883 0 ▶ return if defined $p->{tag} && !($link->tag && $link->tag eq $p->{tag} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"tag"} and not $link->tag && $link->tag eq $p->{"tag"} 0 0 0
Condition0%0/6
defined $p->{"tag"} and not $link->tag && $link->tag eq $p->{"tag"}
!ll&&!rl&&r
000
$link->tag && $link->tag eq $p->{'tag'}
!ll&&!rl&&r
000
MC/DC0%0/3
defined $p->{"tag"} and not $link->tag && $link->tag eq $p->{"tag"}
defined $p->{"tag"} $link->tag $link->tag eq $p->{'tag'}
Truth table0%0/4
A and not(B && C)
A= defined $p->{"tag"}B= $link->tagC= $link->tag eq $p->{'tag'}
ABCresult
0XX0
1110
10X1
1101
3884 0 ▶ return if defined $p->{tag_regex} && !($link->tag && $link->tag =~ $p->{tag_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"tag_regex"} and not $link->tag && $link->tag =~ /$p->{"tag_regex"}/u 0 0 0
Condition0%0/6
defined $p->{"tag_regex"} and not $link->tag && $link->tag =~ /$p->{"tag_regex"}/u
!ll&&!rl&&r
000
$link->tag && $link->tag =~ /$p->{'tag_regex'}/u
!ll&&!rl&&r
000
MC/DC0%0/3
defined $p->{"tag_regex"} and not $link->tag && $link->tag =~ /$p->{"tag_regex"}/u
defined $p->{"tag_regex"} $link->tag $link->tag =~ /$p->{'tag_regex'}/u
Truth table0%0/4
A and not(B && C)
A= defined $p->{"tag_regex"}B= $link->tagC= $link->tag =~ /$p->{'tag_regex'}/u
ABCresult
0XX0
1110
10X1
1101
3885  
3886 0 ▶ return if defined $p->{id} && !($link->attrs->{id} && $link->attrs->{id} eq $p->{id} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"id"} and not $link->attrs->{"id"} && $link->attrs->{"id"} eq $p->{"id"} 0 0 0
Condition0%0/6
defined $p->{"id"} and not $link->attrs->{"id"} && $link->attrs->{"id"} eq $p->{"id"}
!ll&&!rl&&r
000
$link->attrs->{'id'} && $link->attrs->{'id'} eq $p->{'id'}
!ll&&!rl&&r
000
MC/DC0%0/3
defined $p->{"id"} and not $link->attrs->{"id"} && $link->attrs->{"id"} eq $p->{"id"}
defined $p->{"id"} $link->attrs->{'id'} $link->attrs->{'id'} eq $p->{'id'}
Truth table0%0/4
A and not(B && C)
A= defined $p->{"id"}B= $link->attrs->{'id'}C= $link->attrs->{'id'} eq $p->{'id'}
ABCresult
0XX0
1110
10X1
1101
3887 0 ▶ return if defined $p->{id_regex} && !($link->attrs->{id} && $link->attrs->{id} =~ $p->{id_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"id_regex"} and not $link->attrs->{"id"} && $link->attrs->{"id"} =~ /$p->{"id_regex"}/u 0 0 0
Condition0%0/6
defined $p->{"id_regex"} and not $link->attrs->{"id"} && $link->attrs->{"id"} =~ /$p->{"id_regex"}/u
!ll&&!rl&&r
000
$link->attrs->{'id'} && $link->attrs->{'id'} =~ /$p->{'id_regex'}/u
!ll&&!rl&&r
000
MC/DC0%0/3
defined $p->{"id_regex"} and not $link->attrs->{"id"} && $link->attrs->{"id"} =~ /$p->{"id_regex"}/u
defined $p->{"id_regex"} $link->attrs->{'id'} $link->attrs->{'id'} =~ /$p->{'id_regex'}/u
Truth table0%0/4
A and not(B && C)
A= defined $p->{"id_regex"}B= $link->attrs->{'id'}C= $link->attrs->{'id'} =~ /$p->{'id_regex'}/u
ABCresult
0XX0
1110
10X1
1101
3888 0 ▶ return if defined $p->{class} && !($link->attrs->{class} && $link->attrs->{class} eq $p->{class} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"class"} and not $link->attrs->{"class"} && $link->attrs->{"class"} eq $p->{"class"} 0 0 0
Condition0%0/6
defined $p->{"class"} and not $link->attrs->{"class"} && $link->attrs->{"class"} eq $p->{"class"}
!ll&&!rl&&r
000
$link->attrs->{'class'} && $link->attrs->{'class'} eq $p->{'class'}
!ll&&!rl&&r
000
MC/DC0%0/3
defined $p->{"class"} and not $link->attrs->{"class"} && $link->attrs->{"class"} eq $p->{"class"}
defined $p->{"class"} $link->attrs->{'class'} $link->attrs->{'class'} eq $p->{'class'}
Truth table0%0/4
A and not(B && C)
A= defined $p->{"class"}B= $link->attrs->{'class'}C= $link->attrs->{'class'} eq $p->{'class'}
ABCresult
0XX0
1110
10X1
1101
3889 0 ▶ return if defined $p->{class_regex} && !($link->attrs->{class} && $link->attrs->{class} =~ $p->{class_regex} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"class_regex"} and not $link->attrs->{"class"} && $link->attrs->{"class"} =~ /$p->{"class_regex"}/u 0 0 0
Condition0%0/6
defined $p->{"class_regex"} and not $link->attrs->{"class"} && $link->attrs->{"class"} =~ /$p->{"class_regex"}/u
!ll&&!rl&&r
000
$link->attrs->{'class'} && $link->attrs->{'class'} =~ /$p->{'class_regex'}/u
!ll&&!rl&&r
000
MC/DC0%0/3
defined $p->{"class_regex"} and not $link->attrs->{"class"} && $link->attrs->{"class"} =~ /$p->{"class_regex"}/u
defined $p->{"class_regex"} $link->attrs->{'class'} $link->attrs->{'class'} =~ /$p->{'class_regex'}/u
Truth table0%0/4
A and not(B && C)
A= defined $p->{"class_regex"}B= $link->attrs->{'class'}C= $link->attrs->{'class'} =~ /$p->{'class_regex'}/u
ABCresult
0XX0
1110
10X1
1101
3890  
3891 # Success: everything that was defined passed.
3892 0 return 1;
3893 }
3894  
3895 0 ▶sub find_link_dom {
Subroutine find_link_dom: not called CC=24 SCAR=64.0
Pod documented
3896 0 my ($self,%opts) = @_;
3897 0 my %xpath_options;
3898  
3899 # Clean up some legacy stuff
3900 0 delete @opts{ qw(synchronize) };
3901  
3902 0 for (qw(node document frames xpath selector)) {
3903 # Copy over XPath options that were passed in
3904 0 ▶ if (exists $opts{ $_ }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{$_}) 0 0 0
3905 0 $xpath_options{ $_ } = delete $opts{ $_ };
3906 };
3907 };
3908  
3909 0 my $single = delete $opts{ single };
3910 0 ▶ my $one = delete $opts{ one } || $single;
Condition0%0/3
delete $opts{'one'} || $single
l!l&&r!l&&!r
000
MC/DC0%0/2
delete $opts{'one'} || $single
delete $opts{'one'} $single
Truth table0%0/3
A || B
A= delete $opts{'one'}B= $single
ABresult
1X1
011
000
3911 0 ▶ if ($single and exists $opts{ n }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($single and exists $opts{"n"}) 0 0 0
Condition0%0/3
$single and exists $opts{"n"}
!ll&&!rl&&r
000
MC/DC0%0/2
$single and exists $opts{"n"}
$single exists $opts{"n"}
Truth table0%0/3
A and B
A= $singleB= exists $opts{"n"}
ABresult
0X0
100
111
3912 0 croak "It doesn't make sense to use 'single' and 'n' option together"
3913 };
3914 0 ▶ my $n = (delete $opts{ n } || 1);
Condition0%0/2
delete $opts{'n'} || 1
l!l
00
MC/DC0%0/1
delete $opts{'n'} || 1
delete $opts{'n'}
Truth table0%0/2
A
A= delete $opts{'n'}
Aresult
11
00
3915 0 ▶ $n--
Branch: 1 branch
BranchTrueFalseTotal
if $n ne "all" 0 0 0
3916 if ($n ne 'all'); # 1-based indexing
3917 0 my @spec;
3918  
3919 # Decode text and text_contains into XPath
3920 0 for my $lvalue (qw( text id name class )) {
3921 0 my %lefthand = (
3922 text => 'text()',
3923 );
3924 0 my %match_op = (
3925 '' => q{%s="%s"},
3926 'contains' => q{contains(%s,"%s")},
3927 # Ideally we would also handle *_regex here, but Chrome XPath
3928 # does not support fn:matches() :-(
3929 #'regex' => q{matches(%s,"%s","%s")},
3930 );
3931 0 ▶ my $lhs = $lefthand{ $lvalue } || '@'.$lvalue;
Condition0%0/2
$lefthand{$lvalue} || '@' . $lvalue
l!l
00
MC/DC0%0/1
$lefthand{$lvalue} || '@' . $lvalue
$lefthand{$lvalue}
Truth table0%0/2
A
A= $lefthand{$lvalue}
Aresult
11
00
3932 0 for my $op (keys %match_op) {
3933 0 my $v = $match_op{ $op };
3934 0 ▶ $op = '_'.$op if length($op);
Branch: 1 branch
BranchTrueFalseTotal
if length $op 0 0 0
3935 0 my $key = "${lvalue}$op";
3936  
3937 0 ▶ if (exists $opts{ $key }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{$key}) 0 0 0
3938 0 my $p = delete $opts{ $key };
3939 0 push @spec, sprintf $v, $lhs, $p;
3940 };
3941 };
3942 };
3943  
3944 0 ▶ if (my $p = delete $opts{ url }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $p = delete $opts{"url"}) 0 0 0
3945 0 push @spec, sprintf '@href = "%s" or @src="%s"', quote_xpath( $p ), quote_xpath( $p );
3946 }
3947 0 my @tags = (sort keys %link_spec);
3948 0 ▶ if (my $p = delete $opts{ tag }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $p = delete $opts{"tag"}) 0 0 0
3949 0 @tags = $p;
3950 };
3951 0 ▶ if (my $p = delete $opts{ tag_regex }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $p = delete $opts{"tag_regex"}) 0 0 0
3952 0 @tags = grep /$p/, @tags;
3953 };
3954 my $q = join '|',
3955 map {
3956 0 ▶ my $xp= exists $link_spec{ $_ } ? $link_spec{$_}->{xpath} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $WWW::Mechanize::Chrome::link_spec{$_} ? : 0 0 0
3957 0 my @full = map {qq{($_)}} grep {defined} (@spec, $xp);
3958 0 ▶ if (@full) {
Branch: 1 branch
BranchTrueFalseTotal
if (@full) { } 0 0 0
3959 0 sprintf "//%s[%s]", $_, join " and ", @full;
3960 } else {
3961 0 sprintf "//%s", $_
3962 };
3963 } (@tags);
3964 #warn $q;
3965  
3966 0 my @res = $self->xpath($q, %xpath_options );
3967  
3968 0 ▶ if (keys %opts) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %opts) 0 0 0
3969 # post-filter the remaining links
3970 # for all the options we don't support with XPath
3971 0 my $base = $self->base;
3972  
3973 @res = grep {
3974 0 $self->_match_any_link_params($self->make_link($_,$base),\%opts);
3975 } @res;
3976 };
3977  
3978 0 ▶ if ($one) {
Branch: 1 branch
BranchTrueFalseTotal
if ($one) 0 0 0
3979 0 ▶ if (0 == @res) { $self->signal_condition( "No link found matching '$q'" )};
Branch: 1 branch
BranchTrueFalseTotal
if (0 == @res) 0 0 0
3980 0 ▶ if ($single) {
Branch: 1 branch
BranchTrueFalseTotal
if ($single) 0 0 0
3981 0 ▶ if (1 < @res) {
Branch: 1 branch
BranchTrueFalseTotal
if (1 < @res) 0 0 0
3982 0 $self->highlight_node(@res);
3983 0 $self->signal_condition(
3984 sprintf "%d elements found found matching '%s'", scalar @res, $q
3985 );
3986 };
3987 };
3988 };
3989  
3990 0 ▶ if ($n eq 'all') {
Branch: 1 branch
BranchTrueFalseTotal
if ($n eq "all") 0 0 0
3991 return @res
3992 0 };
3993 0 $res[$n]
3994 }
3995  
3996 =head2 C<< $mech->find_link( %options ) >>
3997  
3998 print $_->text . "\n"
3999 for $mech->find_link( text_contains => 'CPAN' );
4000  
4001 A method quite similar to L<WWW::Mechanize>'s method.
4002 The options are documented in C<< ->find_link_dom >>.
4003  
4004 Returns a L<WWW::Mechanize::Link> object.
4005  
4006 This defaults to not look through child frames.
4007  
4008 =cut
4009  
4010 0 ▶sub find_link {
Subroutine find_link: not called CC=4 SCAR=30.0
Pod documented
4011 0 my ($self,%opts) = @_;
4012 0 my $base = $self->base;
4013 croak "Option 'all' not available for ->find_link. Did you mean to call ->find_all_links()?"
4014 0 ▶ if 'all' eq ($opts{n} || '');
Branch: 1 branch
BranchTrueFalseTotal
if "all" eq ($opts{"n"} || "") 0 0 0
Condition0%0/2
$opts{'n'} || ''
l!l
00
MC/DC0%0/1
$opts{'n'} || ''
$opts{'n'}
Truth table0%0/2
A
A= $opts{'n'}
Aresult
11
00
4015 0 ▶ if (my $link = $self->find_link_dom(frames => 0, %opts)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $link = $self->find_link_dom('frames', 0, %opts)) { } 0 0 0
4016 0 return $self->make_link($link, $base)
4017 } else {
4018 return
4019 0 };
4020 };
4021  
4022 =head2 C<< $mech->find_all_links( %options ) >>
4023  
4024 print $_->text . "\n"
4025 for $mech->find_all_links( text_regex => qr/google/i );
4026  
4027 Finds all links in the document.
4028 The options are documented in C<< ->find_link_dom >>.
4029  
4030 Returns them as list or an array reference, depending
4031 on context.
4032  
4033 This defaults to not look through child frames.
4034  
4035 =cut
4036  
4037 0 ▶sub find_all_links {
Subroutine find_all_links: not called CC=2 SCAR=17.9
Pod documented
4038 0 my ($self, %opts) = @_;
4039 0 $opts{ n } = 'all';
4040 0 my $base = $self->base;
4041 my @matches = map {
4042 0 $self->make_link($_, $base);
4043 } $self->find_all_links_dom( frames => 0, %opts );
4044 0 ▶ return @matches if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 0 0 0
4045 0 return \@matches;
4046 };
4047  
4048 =head2 C<< $mech->find_all_links_dom %options >>
4049  
4050 print $_->{innerHTML} . "\n"
4051 for $mech->find_all_links_dom( text_regex => qr/google/i );
4052  
4053 Finds all matching linky DOM nodes in the document.
4054 The options are documented in C<< ->find_link_dom >>.
4055  
4056 Returns them as list or an array reference, depending
4057 on context.
4058  
4059 This defaults to not look through child frames.
4060  
4061 =cut
4062  
4063 0 ▶sub find_all_links_dom {
Subroutine find_all_links_dom: not called CC=2 SCAR=17.9
Pod documented
4064 0 my ($self,%opts) = @_;
4065 0 $opts{ n } = 'all';
4066 0 my @matches = $self->find_link_dom( frames => 0, %opts );
4067 0 ▶ return @matches if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 0 0 0
4068 0 return \@matches;
4069 };
4070  
4071 =head2 C<< $mech->follow_link( $link ) >>
4072  
4073 =head2 C<< $mech->follow_link( %options ) >>
4074  
4075 $mech->follow_link( xpath => '//a[text() = "Click here!"]' );
4076  
4077 Follows the given link. Takes the same parameters that C<find_link_dom>
4078 uses.
4079  
4080 Note that C<< ->follow_link >> will only try to follow link-like
4081 things like C<A> tags.
4082  
4083 =cut
4084  
4085 0 ▶sub follow_link {
Subroutine follow_link: not called CC=2 SCAR=17.9
Pod documented
4086 0 my ($self,$link,%opts);
4087 0 ▶ if (@_ == 2) { # assume only a link parameter
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 2) { } 0 0 0
4088 0 ($self,$link) = @_;
4089 0 $self->click($link);
4090 } else {
4091 0 ($self,%opts) = @_;
4092 0 _default_limiter( one => \%opts );
4093 0 $link = $self->find_link_dom(%opts);
4094 0 $self->click({ dom => $link, %opts });
4095 }
4096 }
4097  
4098 0 ▶sub activate_parent_container {
Subroutine activate_parent_container: not called CC=1 SCAR=6.9
Pod undocumented
4099 0 my( $self, $doc )= @_;
4100 0 $self->activate_container( $doc, 1 );
4101 };
4102  
4103 0 ▶sub activate_container {
Subroutine activate_container: not called CC=7 SCAR=40.3
Pod undocumented
4104 0 my( $self, $doc, $just_parent )= @_;
4105 0 my $driver= $self->driver;
4106  
4107 0 ▶ if( ! $doc->{__path}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($doc->{"__path"}) 0 0 0
4108 0 die "Invalid document without __path encountered. I'm sorry.";
4109 };
4110 # Activate the root window/frame
4111 #warn "Activating root frame:";
4112 #$driver->switch_to_frame();
4113 #warn "Activating root frame done.";
4114  
4115 0 for my $el ( @{ $doc->{__path} }) {
4116 #warn "Switching frames downwards ($el)";
4117 #warn "Tag: " . $el->get_tag_name;
4118 #warn Dumper $el;
4119 0 warn sprintf "Switching during path to %s %s", $el->get_tag_name, $el->get_attribute('src', live => 1);
4120 0 $driver->switch_to_frame( $el );
4121 };
4122  
4123 0 ▶ if( ! $just_parent ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($just_parent) 0 0 0
4124 0 warn sprintf "Activating container %s too", $doc->{id};
4125 # Now, unless it's the root frame, activate the container. The root frame
4126 # already is activated above.
4127 0 warn "Getting tag";
4128 0 my $tag= $doc->get_tag_name;
4129 #my $src= $doc->get_attribute('src');
4130 0 ▶ if( 'html' ne $tag and '' ne $tag) {
Branch: 1 branch
BranchTrueFalseTotal
if ("html" ne $tag and "" ne $tag) 0 0 0
Condition0%0/3
"html" ne $tag and "" ne $tag
!ll&&!rl&&r
000
MC/DC0%0/2
"html" ne $tag and "" ne $tag
"html" ne $tag "" ne $tag
Truth table0%0/3
A and B
A= "html" ne $tagB= "" ne $tag
ABresult
0X0
100
111
4131 #warn sprintf "Switching to final container %s %s", $tag, $src;
4132 0 $driver->switch_to_frame( $doc );
4133 };
4134 #warn sprintf "Switched to final/main container %s %s", $tag, $src;
4135 };
4136 #warn $self->target->get_current_url;
4137 #warn $self->target->get_title;
4138 #my $body= $doc->get_attribute('contentDocument');
4139 0 my $body= $driver->find_element('/*', 'xpath');
4140 0 ▶ if( $body ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body) 0 0 0
4141 0 warn "Now active container: " . $body->get_attribute('innerHTML', live => 1);
4142 #$body= $body->get_attribute('document');
4143 #warn $body->get_attribute('innerHTML');
4144 };
4145 };
4146  
4147 =head2 C<< $mech->xpath( $query, %options ) >>
4148  
4149 my $link = $mech->xpath('//a[id="clickme"]', one => 1);
4150 # croaks if there is no link or more than one link found
4151  
4152 my @para = $mech->xpath('//p');
4153 # Collects all paragraphs
4154  
4155 my @para_text = $mech->xpath('//p/text()', type => $mech->xpathResult('STRING_TYPE'));
4156 # Collects all paragraphs as text
4157  
4158 Runs an XPath query in Chrome against the current document.
4159  
4160 If you need more information about the returned results,
4161 use the C<< ->xpathEx() >> function.
4162  
4163 Note that Chrome sometimes returns a node with node id 0. This node then
4164 cannot be found again using the Chrome API. This is bad luck and results in
4165 a warning.
4166  
4167 The options allow the following keys:
4168  
4169 =over 4
4170  
4171 =item *
4172  
4173 C<< document >> - document in which the query is to be executed. Use this to
4174 search a node within a specific subframe of C<< $mech->document >>.
4175  
4176 =item *
4177  
4178 C<< frames >> - if true, search all documents in all frames and iframes.
4179 This may or may not conflict with C<node>. This will default to the
4180 C<frames> setting of the WWW::Mechanize::Chrome object.
4181  
4182 =item *
4183  
4184 C<< node >> - node relative to which the query is to be executed. Note
4185 that you will have to use a relative XPath expression as well. Use
4186  
4187 .//foo
4188  
4189 instead of
4190  
4191 //foo
4192  
4193 Querying relative to a node only works for restricting to children of the node,
4194 not for anything else. This is because we need to do the ancestor filtering
4195 ourselves instead of having a Chrome API for it.
4196  
4197 =item *
4198  
4199 C<< single >> - If true, ensure that only one element is found. Otherwise croak
4200 or carp, depending on the C<autodie> parameter.
4201  
4202 =item *
4203  
4204 C<< one >> - If true, ensure that at least one element is found. Otherwise croak
4205 or carp, depending on the C<autodie> parameter.
4206  
4207 =item *
4208  
4209 C<< maybe >> - If true, ensure that at most one element is found. Otherwise
4210 croak or carp, depending on the C<autodie> parameter.
4211  
4212 =item *
4213  
4214 C<< all >> - If true, return all elements found. This is the default.
4215 You can use this option if you want to use C<< ->xpath >> in scalar context
4216 to count the number of matched elements, as it will otherwise emit a warning
4217 for each usage in scalar context without any of the above restricting options.
4218  
4219 =item *
4220  
4221 C<< any >> - no error is raised, no matter if an item is found or not.
4222  
4223 =back
4224  
4225 Returns the matched results as L<WWW::Mechanize::Chrome::Node> objects.
4226  
4227 You can pass in a list of queries as an array reference for the first parameter.
4228 The result will then be the list of all elements matching any of the queries.
4229  
4230 This is a method that is not implemented in WWW::Mechanize.
4231  
4232 In the long run, this should go into a general plugin for
4233 L<WWW::Mechanize>.
4234  
4235 =cut
4236  
4237 # This unwraps a tree of child nodes into a flat hash indexed by nodeId
4238 0 ▶sub _unwrapChildNodeTree( $self, $nodes, $tree={} ) {
Subroutine _unwrapChildNodeTree: not called CC=4 SCAR=30.0
4239 0 for my $node (@$nodes) {
4240 0 $tree->{ $node->{nodeId} } = $node;
4241 0 ▶ if( $node->{children}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->{"children"}) 0 0 0
4242 0 $self->_unwrapChildNodeTree( $node->{children}, $tree );
4243 };
4244 }
4245 0 return $tree
4246 }
4247  
4248 0 ▶sub _performSearch( $self, %args ) {
Subroutine _performSearch: not called CC=2 SCAR=17.9
4249 0 my $subTreeId = $args{ subTreeId };
4250 0 my $query = $args{ query };
4251 0 weaken( my $s = $self );
4252  
4253 0 my $doc;
4254 # Retry a search up to three times if the page changes in the meantime
4255 my $nodeGeneration;
4256 0 ▶ $s->{_currentNodeGeneration} //= 0;
Condition0%0/2
$s->{"_currentNodeGeneration"} //= 0
l!l
00
MC/DC0%0/1
$s->{"_currentNodeGeneration"} //= 0
$s->{"_currentNodeGeneration"}
Truth table0%0/2
A
A= $s->{"_currentNodeGeneration"}
Aresult
11
00
4257 0 my $retries = 3;
4258 0 my $last_search;
4259 0 ▶ my $search = repeat {
Subroutine __ANON__: not called CC=1 SCAR=6.9
4260 0 $nodeGeneration = $self->{_currentNodeGeneration};
4261 # Lock the document, hoping that no intermittent update messes up our IDs
4262 # Just to make sure we avoid nodeId 0 ?!
4263 # https://github.com/cyrus-and/chrome-remote-interface/issues/165
4264 0 ▶ my $wait = $s->_cached_document->then(sub( $r ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
4265 0 $doc = $r->{root};
4266 0 Future->done
4267 0 });
4268  
4269 0 ▶ $wait = $wait->then( sub(@info) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
4270 0 my $res = $s->target->send_message( 'DOM.performSearch', query => $query );
4271 0 return $res
4272 0 });
4273 0 return $wait
4274  
4275 0 ▶ } while => sub($search) {
Subroutine __ANON__: not called CC=4 SCAR=30.0
4276 0 ▶ my $retry = ($nodeGeneration != $s->{_currentNodeGeneration} and $retries--);
Condition0%0/3
$nodeGeneration != $s->{'_currentNodeGeneration'} && $retries--
!ll&&!rl&&r
000
MC/DC0%0/2
$nodeGeneration != $s->{'_currentNodeGeneration'} && $retries--
$nodeGeneration != $s->{'_currentNodeGeneration'} $retries--
Truth table0%0/3
A && B
A= $nodeGeneration != $s->{'_currentNodeGeneration'}B= $retries--
ABresult
0X0
100
111
4277  
4278 0 ▶ if( $retry ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($retry) 0 0 0
4279 # close the previous search attempt
4280 0 ▶ my $se = $search->then(sub($results) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
4281 0 my $searchId = $results->{searchId};
4282 #warn "!!! Discarding search";
4283 0 $s->target->send_message( 'DOM.discardSearchResults',
4284 searchId => $searchId,
4285 );
4286 0 });
4287 #warn "Closed search: $se";
4288 0 $se->retain;
4289 }
4290  
4291 0 ▶ if( $retry ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($retry) 0 0 0
4292 0 $s->log('trace', "Retrying search ($retries attempts left)");
4293 }
4294 $retry
4295 0 };
4296  
4297 0 ▶ $search->then(sub($results) {
Subroutine __ANON__: not called CC=3 SCAR=24.8
4298 0 $s->log('debug', "XPath query '$query' (". $results->{resultCount} . " node(s))");
4299  
4300 0 ▶ if( $results->{resultCount} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($results->{'resultCount'}) { } 0 0 0
4301 0 my $searchResults;
4302 0 my $searchId = $results->{searchId};
4303 0 my @childNodes;
4304 0 ▶ my $setChildNodes = $self->add_listener('DOM.setChildNodes', sub( $ev ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
4305 #use Data::Dumper; warn "setChildNodes: "; warn Dumper $ev;
4306 0 push @childNodes, @{ $ev->{params}->{nodes} };
4307 0 });
4308  
4309 0 my $childNodes;
4310 0 ▶ if( defined $subTreeId ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $subTreeId) { } 0 0 0
4311 0 $childNodes =
4312 $self->target->send_message( 'DOM.requestChildNodes',
4313 nodeId => 0+$subTreeId,
4314 depth => -1, # we want/need the whole subtree
4315 )
4316 } else {
4317 0 $childNodes = Future->done;
4318 };
4319 my $search = $self->target->send_message( 'DOM.getSearchResults',
4320 searchId => $results->{searchId},
4321 fromIndex => 0,
4322 toIndex => 0+$results->{resultCount},
4323 0 );
4324 # We can't immediately discard our search results until we find out
4325 # what invalidates node ids.
4326 # So we currently accumulate memory until we disconnect. Oh well.
4327 # And node ids still get invalidated
4328 #)->followed_by( sub( $results ) {
4329 # $searchResults = $results->get;
4330 # $self->target->send_message( 'DOM.discardSearchResults',
4331 # searchId => $searchId,
4332 # );
4333 #}
4334  
4335 0 ▶ Future->wait_all( $childNodes, $search )->then(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
4336 # The result of $childNodes is indirect here, by pushing
4337 # the setChildNodes messages onto @childNodes
4338 0 my @discard = $childNodes->get();
4339  
4340 0 return $search;
4341  
4342 0 ▶ })->then( sub( $response ) {
Subroutine __ANON__: not called CC=5 SCAR=34.0
4343 # you might get a node with nodeId 0. This one
4344 # can't be retrieved. Bad luck.
4345 0 ▶ if($response->{nodeIds}->[0] == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->{"nodeIds"}[0] == 0) 0 0 0
4346 # Maybe we did receive exactly one childnode?!
4347 #if( @childNodes == 1 ) {
4348 # warn "Maybe we can hacky-salvage this?! Forcing nodeId to $childNodes[0]->{nodeId}";
4349 # # Nope - in the bad case, we always get the root node
4350 # # instead of something usable :-/
4351 # $response->{nodeIds}->[0] = $childNodes[0]->{nodeId};
4352 #} else {
4353  
4354 #warn "Bad luck: Node with nodeId 0 found. Info for this one cannot be retrieved";
4355 0 $self->signal_condition( "Bad luck: Node with nodeId 0 found. Info for this one cannot be retrieved" );
4356 #};
4357 };
4358  
4359 # Resolve the found nodes directly with the
4360 # found node ids instead of returning the numbers and fetching
4361 # them later
4362 # We could also prefill some data with the results from
4363 # $childNodes here, if we have that?!
4364 # We build and search the document here:
4365 0 my %node_ids;
4366 #use Data::Dumper;
4367 #warn Dumper $doc;
4368 0 my @scan = @{ $doc->{children}};
4369 0 ▶ while( my $node = shift @scan ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $node = shift @scan) 0 0 0
4370 0 $node_ids{ $node->{nodeId}} = $node;
4371  
4372 #warn join ",", sort keys %node_ids;
4373 0 ▶ if( $node->{children} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->{"children"}) 0 0 0
4374 unshift @scan,
4375 0 map { $_->{parentNodeId} = $node->{nodeId}; $_ }
4376 0 @{$node->{children}};
4377 };
4378 };
4379  
4380 #my @nodes = map {
4381 # WWW::Mechanize::Chrome::Node->fetchNode(
4382 # nodeId => 0+$_,
4383 # driver => $self->target,
4384 # );
4385 #} @{ $response->{nodeIds}};
4386 my @nodes = map {
4387 0 my $nid = $_;
4388 #my $request_f = $self->target->send_message('DOM.pushNodesByBackendIdsToFrontend',
4389 #backendNodeIds => [$node_ids{$_}->{backendNodeId}])
4390 #->then(sub( $info ) {
4391 # warn Dumper $info;
4392  
4393 # Convert the array of attributes to a hash of attributes ...
4394 0 ▶ if( ref $node_ids{$nid}->{attributes} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node_ids{$nid}{"attributes"} eq "ARRAY") 0 0 0
4395 $node_ids{$nid}->{attributes} = +{
4396 0 @{ $node_ids{$nid}->{attributes} }
4397 };
4398 };
4399 Future->done(
4400 WWW::Mechanize::Chrome::Node->new(
4401 0 +{ %{$node_ids{$nid} },
4402 driver => $self->target,
4403 }
4404 ))
4405 #});
4406 0 } @{ $response->{nodeIds}};
4407  
4408 0 Future->wait_all( @nodes )
4409 0 ▶ })->then( sub( @fetched_nodes ) {
Subroutine __ANON__: not called CC=12 SCAR=50.5
4410 # This should already happen through the DESTROY callback
4411 # but we'll be explicit here
4412 0 $setChildNodes->unregister;
4413 0 undef $setChildNodes;
4414  
4415 # Resolve the found nodes directly with the
4416 # found node ids instead of returning the numbers and fetching
4417 # them later
4418 0 my @foundNodes = map { $_->get() } @fetched_nodes;
4419 0 my $nodes = $self->_unwrapChildNodeTree( \@childNodes );
4420  
4421 0 for (@foundNodes) {
4422 0 my $id = $_->nodeId;
4423 0 ▶ if( ! defined $id ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $id) 0 0 0
4424 #use Data::Dumper;
4425 #warn "Found node without nodeId: " . Dumper $_;
4426 # Sometimes we get a spurious, empty node, so we ignore that
4427 # Maybe that is because the node we searched for went
4428 # away, but we'd need to associate the information
4429 # before we get the response, so ...
4430 0 next;
4431 };
4432 # Backfill here instead of overwriting!
4433 0 ▶ if( my $n = $nodes->{$id} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $n = $nodes->{$id}) 0 0 0
4434 0 for my $key (qw( backendNodeId parentId )) {
4435 0 $_->{ $key } = $n->{ $key };
4436 };
4437 0 ▶ if( ! $_->{backendNodeId} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($_->{"backendNodeId"}) 0 0 0
4438 0 die "No backend node id found via " . Dumper $n;
4439 };
4440 };
4441 0 $nodes->{ $id } = $_;
4442 };
4443  
4444 # Filter @found for those nodes that have $nodeId as
4445 # ancestor because we can't restrict the search in Chrome
4446 # directly...
4447 0 ▶ if( $subTreeId ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($subTreeId) { } 0 0 0
4448  
4449 0 $self->log('trace', "Filtering query results for ancestor backendNodeId $subTreeId");
4450  
4451 # Find all nodes contained in our subtree
4452 0 my @scan = @{ $doc->{children}};
4453 0 my $subTree;
4454 my $inSubTree;
4455 0 my %foundNodes = map { $_->nodeId => $_ } @foundNodes;
4456 0 @foundNodes = ();
4457  
4458 0 ▶ while( my $node = shift @scan ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $node = shift @scan) 0 0 0
4459 #warn join ",", sort keys %node_ids;
4460  
4461 0 ▶ if( $node->{backendNodeId} == $subTreeId ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->{"backendNodeId"} == $subTreeId) 0 0 0
4462 0 $subTree = $node;
4463 0 $inSubTree = 1;
4464 0 @scan = @{$subTree->{children}};
4465 0 next;
4466 };
4467  
4468 0 ▶ if( $inSubTree and exists $foundNodes{ $node->{nodeId}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inSubTree and exists $foundNodes{$node->{"nodeId"}}) 0 0 0
Condition0%0/3
$inSubTree and exists $foundNodes{$node->{"nodeId"}}
!ll&&!rl&&r
000
MC/DC0%0/2
$inSubTree and exists $foundNodes{$node->{"nodeId"}}
$inSubTree exists $foundNodes{$node->{"nodeId"}}
Truth table0%0/3
A and B
A= $inSubTreeB= exists $foundNodes{$node->{"nodeId"}}
ABresult
0X0
100
111
4469 0 push @foundNodes, $foundNodes{ $node->{nodeId}};
4470 };
4471  
4472 0 ▶ if( $node->{children} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->{"children"}) 0 0 0
4473 unshift @scan,
4474 0 map { $_->{parentNodeId} = $node->{nodeId}; $_ }
4475 0 @{$node->{children}};
4476 };
4477 };
4478  
4479 0 $self->log('debug', "filtered XPath query '$query' for ancestor $subTreeId (". (0+@foundNodes) . " node(s))");
4480 } else {
4481 #warn "*** Not filtering for any parent node";
4482 };
4483  
4484 # Downstream wants a double-nested Future, so do it here
4485 # until we fix downstream
4486 0 Future->wait_all( Future->done( @foundNodes ));
4487 0 });
4488 } else {
4489 0 return Future->done()
4490 };
4491 0 });
4492 }
4493  
4494 0 ▶sub xpath( $self, $query, %options) {
Subroutine xpath: not called CC=25 SCAR=64.8
Pod documented
4495 0 ▶ if ('ARRAY' ne (ref $query||'')) {
Branch: 1 branch
BranchTrueFalseTotal
if ("ARRAY" ne (ref $query || "")) 0 0 0
Condition0%0/2
ref $query || ''
l!l
00
MC/DC0%0/1
ref $query || ''
ref $query
Truth table0%0/2
A
A= ref $query
Aresult
11
00
4496 0 $query = [$query];
4497 };
4498 0 ▶ if( not exists $options{ frames }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options{"frames"}) 0 0 0
4499 0 $options{ frames }= $self->{frames};
4500 };
4501  
4502 0 my $single = $options{ single };
4503 0 my $first = $options{ one };
4504 0 my $maybe = $options{ maybe };
4505 0 my $any = $options{ any };
4506 0 ▶ my $index = $options{ index } || 0;
Condition0%0/2
$options{'index'} || 0
l!l
00
MC/DC0%0/1
$options{'index'} || 0
$options{'index'}
Truth table0%0/2
A
A= $options{'index'}
Aresult
11
00
4507 0 ▶ if( $index >= 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($index >= 1) 0 0 0
4508 0 $index--;
4509 };
4510 0 ▶ my $return_first_element = ($single or $first or $maybe or $any );
Condition0%0/9
$single || $first || $maybe || $any
l!l&&r!l&&!r
000
$single or $first or $maybe
l!l&&r!l&&!r
000
$single or $first
l!l&&r!l&&!r
000
MC/DC0%0/4
$single || $first || $maybe || $any
$single $first $maybe $any
Truth table0%0/5
A or B or C || D
A= $singleB= $firstC= $maybeD= $any
ABCDresult
1XXX1
01XX1
001X1
00011
00000
4511 0 ▶ $options{ user_info }||= join "|", @$query;
Condition0%0/3
$options{"user_info"} ||= join("|", @$query)
l!l&&r!l&&!r
000
MC/DC0%0/2
$options{"user_info"} ||= join("|", @$query)
$options{"user_info"} join("|", @$query)
Truth table0%0/3
A ||= B
A= $options{"user_info"}B= join("|", @$query)
ABresult
1X1
011
000
4512  
4513 # Construct some helper variables
4514 0 ▶ my $zero_allowed = not ($single or $first);
Condition0%0/3
$single || $first
l!l&&r!l&&!r
000
MC/DC0%0/2
$single || $first
$single $first
Truth table0%0/3
A || B
A= $singleB= $first
ABresult
1X1
011
000
4515 0 ▶ my $two_allowed = (not( $single or $maybe)) || defined $options{ index };
Condition0%0/6
!($single || $maybe) || defined $options{'index'}
l!l&&r!l&&!r
000
$single || $maybe
l!l&&r!l&&!r
000
MC/DC0%0/3
!($single || $maybe) || defined $options{'index'}
$single $maybe defined $options{'index'}
Truth table0%0/5
not(A || B) || C
A= $singleB= $maybeC= defined $options{'index'}
ABCresult
00X1
1X11
0111
1X00
0100
4516  
4517 # Sanity check for the common error of
4518 # my $item = $mech->xpath("//foo");
4519 0 ▶ if (! exists $options{ all } and not ($return_first_element)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options{"all"} or $return_first_element) 0 0 0
Condition0%0/3
exists $options{"all"} or $return_first_element
l!l&&r!l&&!r
000
MC/DC0%0/2
exists $options{"all"} or $return_first_element
exists $options{"all"} $return_first_element
Truth table0%0/3
A or B
A= exists $options{"all"}B= $return_first_element
ABresult
1X1
011
000
4520 0 ▶ $self->signal_condition(join "\n",
Branch: 1 branch
BranchTrueFalseTotal
if defined wantarray and not wantarray 0 0 0
Condition0%0/3
defined wantarray and not wantarray
!ll&&!rl&&r
000
MC/DC0%0/2
defined wantarray and not wantarray
defined wantarray not wantarray
Truth table0%0/3
A and not(B)
A= defined wantarrayB= not wantarray
ABresult
0X0
100
111
4521 "You asked for many elements but seem to only want a single item.",
4522 "Did you forget to pass the 'single' option with a true value?",
4523 "Pass 'all => 1' to suppress this message and receive the count of items.",
4524 ) if defined wantarray and !wantarray;
4525 };
4526  
4527 0 my @res;
4528  
4529 0 ▶ if( $options{ document }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{"document"}) 0 0 0
4530 0 warn sprintf "Document %s", $options{ document }->{id};
4531 };
4532  
4533 #my $doc= $options{ document } ? Future->done( $options{ document } ) : $self->document_future;
4534 0 my $doc = Future->done();
4535  
4536 0 weaken(my $s = $self);
4537  
4538 0 ▶ $doc->then( sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
4539 0 my $q = join "|", @$query;
4540  
4541 0 my @found;
4542 my $id;
4543 0 ▶ if ($options{ node }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{'node'}) { } 0 0 0
4544 0 $id = $options{ node }->backendNodeId;
4545 #warn "Performing search (below '$id')";
4546 } else {
4547 #warn "Performing search across complete DOM";
4548 };
4549 Future->wait_all(
4550 map {
4551 0 $s->_performSearch( query => $_, subTreeId => $id )
4552 } @$query
4553 );
4554 0 ▶ })->then( sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
4555 0 ▶ my @found = map { my @r = $_->get; @r ? map { $_->get } @r : () } @_;
Branch: 1 branch
BranchTrueFalseTotal
@r ? : 0 0 0
4556 #for( @found ) {
4557 # use Data::Dumper;
4558 # warn "Found " . Dumper $_;
4559 #};
4560 0 push @res, @found;
4561 0 Future->done( 1 );
4562 0 })->get;
4563  
4564 # Determine if we want only one element
4565 # or a list, like WWW::Mechanize::Chrome
4566  
4567 0 ▶ if (! $zero_allowed and @res == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $zero_allowed and @res == 0) 0 0 0
Condition0%0/3
not $zero_allowed and @res == 0
!ll&&!rl&&r
000
MC/DC0%0/2
not $zero_allowed and @res == 0
not $zero_allowed @res == 0
Truth table0%0/3
not(A) and B
A= not $zero_allowedB= @res == 0
ABresult
0X0
100
111
4568 0 $self->signal_condition( sprintf "No elements found for %s", $options{ user_info } );
4569 };
4570 0 ▶ if (! $two_allowed and @res > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $two_allowed and @res > 1) 0 0 0
Condition0%0/3
not $two_allowed and @res > 1
!ll&&!rl&&r
000
MC/DC0%0/2
not $two_allowed and @res > 1
not $two_allowed @res > 1
Truth table0%0/3
not(A) and B
A= not $two_allowedB= @res > 1
ABresult
0X0
100
111
4571 #$self->highlight_node(@res);
4572 0 ▶ warn $_->get_text() || '<no text>' for @res;
Condition0%0/2
$_->get_text || '<no text>'
l!l
00
MC/DC0%0/1
$_->get_text || '<no text>'
$_->get_text
Truth table0%0/2
A
A= $_->get_text
Aresult
11
00
4573 0 $self->signal_condition( sprintf "%d elements found for %s", (scalar @res), $options{ user_info } );
4574 };
4575  
4576 0 ▶ $return_first_element ? $res[$index] : @res
Branch: 1 branch
BranchTrueFalseTotal
$return_first_element ? : 0 0 0
4577 }
4578  
4579 =head2 C<< $mech->by_id( $id, %options ) >>
4580  
4581 my @text = $mech->by_id('_foo:bar');
4582  
4583 Returns all nodes matching the given ids. If
4584 C<$id> is an array reference, it returns
4585 all nodes matched by any of the ids in the array.
4586  
4587 This method is equivalent to calling C<< ->xpath >> :
4588  
4589 $self->xpath(qq{//*[\@id="$_"]}, %options)
4590  
4591 It is convenient when your element ids get mistaken for
4592 CSS selectors.
4593  
4594 =cut
4595  
4596 0 ▶sub by_id {
Subroutine by_id: not called CC=4 SCAR=30.0
Pod documented
4597 0 my ($self,$query,%options) = @_;
4598 0 ▶ if ('ARRAY' ne (ref $query||'')) {
Branch: 1 branch
BranchTrueFalseTotal
if ("ARRAY" ne (ref $query || "")) 0 0 0
Condition0%0/2
ref $query || ''
l!l
00
MC/DC0%0/1
ref $query || ''
ref $query
Truth table0%0/2
A
A= ref $query
Aresult
11
00
4599 0 $query = [$query];
4600 };
4601 $options{ user_info } ||= "id "
4602 0 ▶ . join(" or ", map {qq{'$_'}} @$query)
Condition0%0/2
$options{"user_info"} ||= 'id ' . join(" or ", map({"'${_}'";} @$query)) . ' found'
l!l
00
MC/DC0%0/1
$options{"user_info"} ||= 'id ' . join(" or ", map({"'${_}'";} @$query)) . ' found'
$options{"user_info"}
Truth table0%0/2
A
A= $options{"user_info"}
Aresult
11
00
4603 . " found";
4604 0 $query = [map { qq{.//*[\@id="$_"]} } @$query];
4605 0 $self->xpath($query, %options)
4606 }
4607  
4608 =head2 C<< $mech->click( $name [,$x ,$y] ) >>
4609  
4610 # If the element is within a <form> element
4611 $mech->click( 'go' );
4612  
4613 # If the element is anywhere on the page
4614 $mech->click({ xpath => '//button[@name="go"]' });
4615  
4616 Has the effect of clicking a button (or other element) on the current form. The
4617 first argument is the C<name> of the button to be clicked. The second and third
4618 arguments (optional) allow you to specify the (x,y) coordinates of the click.
4619  
4620 If there is only one button on the form, C<< $mech->click() >> with
4621 no arguments simply clicks that one button.
4622  
4623 If you pass in a hash reference instead of a name,
4624 the following keys are recognized:
4625  
4626 =over 4
4627  
4628 =item *
4629  
4630 C<text> - Find the element to click by its contained text
4631  
4632 =item *
4633  
4634 C<selector> - Find the element to click by the CSS selector
4635  
4636 =item *
4637  
4638 C<xpath> - Find the element to click by the XPath query
4639  
4640 =item *
4641  
4642 C<dom> - Click on the passed DOM element
4643  
4644 You can use this to click on arbitrary page elements. There is no convenient
4645 way to pass x/y co-ordinates when using the C<dom> option.
4646  
4647 =item *
4648  
4649 C<id> - Click on the element with the given id
4650  
4651 This is useful if your document ids contain characters that
4652 do look like CSS selectors. It is equivalent to
4653  
4654 xpath => qq{//*[\@id="$id"]}
4655  
4656 =item *
4657  
4658 C<intrapage> - Override the detection of whether to wait for a HTTP response
4659 or not. Setting this will never wait for an HTTP response.
4660  
4661 =back
4662  
4663 Returns a L<HTTP::Response> object.
4664  
4665 As a deviation from the WWW::Mechanize API, you can also pass a
4666 hash reference as the first parameter. In it, you can specify
4667 the parameters to search much like for the C<find_link> calls.
4668  
4669 =cut
4670  
4671 0 ▶sub click {
Subroutine click: not called CC=11 SCAR=48.8
Pod documented
4672 0 my ($self,$name,$x,$y) = @_;
4673 0 my %options;
4674 my @buttons;
4675  
4676 0 ▶ if (! defined $name) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $name) { } 0 0 0
elsif (ref $name and builtin::blessed($name) and $name->isa('WWW::Mechanize::Chrome::Node')) { } 0 0 0
elsif (ref $name eq 'HASH') { } 0 0 0
4677 0 croak("->click called with undef link");
4678 ▶ } elsif (ref $name and blessed $name and $name->isa('WWW::Mechanize::Chrome::Node') ) {
Condition0%0/6
ref $name and builtin::blessed($name) and $name->isa("WWW::Mechanize::Chrome::Node")
!ll&&!rl&&r
000
ref $name and builtin::blessed($name)
!ll&&!rl&&r
000
MC/DC0%0/3
ref $name and builtin::blessed($name) and $name->isa("WWW::Mechanize::Chrome::Node")
ref $name builtin::blessed($name) $name->isa("WWW::Mechanize::Chrome::Node")
Truth table0%0/4
A and B and C
A= ref $nameB= builtin::blessed($name)C= $name->isa("WWW::Mechanize::Chrome::Node")
ABCresult
0XX0
10X0
1100
1111
4679 0 $options{ dom } = $name;
4680 } elsif (ref $name eq 'HASH') { # options
4681 0 %options = %$name;
4682 } else {
4683 0 $options{ name } = $name;
4684 };
4685  
4686 0 ▶ if( exists $options{ text }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options{"text"}) 0 0 0
4687 0 $options{ xpath } = sprintf q{//*[text() = "%s"]}, quote_xpath( $options{ text });
4688 };
4689  
4690 0 ▶ if (exists $options{ name }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options{"name"}) 0 0 0
4691 0 ▶ $name = quotemeta($options{ name }|| '');
Condition0%0/2
$options{'name'} || ''
l!l
00
MC/DC0%0/1
$options{'name'} || ''
$options{'name'}
Truth table0%0/2
A
A= $options{'name'}
Aresult
11
00
4692 $options{ xpath } = [
4693 0 sprintf( q{//*[(translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")="button" and @name="%s") or (translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")="input" and (@type="button" or @type="submit" or @type="image") and @name="%s")]}, $name, $name),
4694 ];
4695 0 ▶ if ($options{ name } eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{"name"} eq "") 0 0 0
4696 0 push @{ $options{ xpath }},
4697 q{//*[(translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") = "button" or translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")="input") and @type="button" or @type="submit" or @type="image"]},
4698 ;
4699 };
4700 0 $options{ user_info } = "Button with name '$name'";
4701 };
4702  
4703 0 ▶ if ($options{ dom }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{'dom'}) { } 0 0 0
4704 0 @buttons = $options{ dom };
4705 } else {
4706 0 @buttons = $self->_option_query(%options);
4707 };
4708  
4709 # Get the node as an object so we can find its position and send the clicks:
4710 0 $self->log('trace', sprintf "Resolving nodeId %d to object for clicking", $buttons[0]->nodeId );
4711 0 my $id = $buttons[0]->objectId;
4712 #warn Dumper $self->target->send_message('Runtime.getProperties', objectId => $id)->get;
4713 #warn Dumper $self->target->send_message('Runtime.callFunctionOn', objectId => $id, functionDeclaration => 'function() { this.focus(); }', arguments => [])->get;
4714  
4715 0 ▶ $self->_mightNavigate( sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
4716 0 $self->target->send_message('Runtime.callFunctionOn', objectId => $id, functionDeclaration => 'function() { this.click(); }', arguments => [])
4717 0 }, %options)
4718 ->get;
4719  
4720 0 return $self->response;
4721 }
4722  
4723 # Internal method to run either an XPath, CSS or id query against the DOM
4724 # Returns the element(s) found
4725 69 my %rename = (
4726 xpath => 'xpath',
4727 selector => 'selector',
4728 id => 'by_id',
4729 by_id => 'by_id',
4730 );
4731  
4732 0 ▶sub _option_query {
Subroutine _option_query: not called CC=5 SCAR=34.0
4733 0 my ($self,%options) = @_;
4734 0 my ($method,$q);
4735 0 for my $meth (keys %rename) {
4736 0 ▶ if (exists $options{ $meth }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options{$meth}) 0 0 0
4737 0 $q = delete $options{ $meth };
4738 0 ▶ $method = $rename{ $meth } || $meth;
Condition0%0/3
$rename{$meth} || $meth
l!l&&r!l&&!r
000
MC/DC0%0/2
$rename{$meth} || $meth
$rename{$meth} $meth
Truth table0%0/3
A || B
A= $rename{$meth}B= $meth
ABresult
1X1
011
000
4739 }
4740 };
4741 0 _default_limiter( 'one' => \%options );
4742 0 ▶ croak "Need either a name, a selector or an xpath key!"
Branch: 1 branch
BranchTrueFalseTotal
unless $method 0 0 0
4743 if not $method;
4744 0 return $self->$method( $q, %options );
4745 };
4746  
4747 # Return the default limiter if no other limiting option is set:
4748 0 ▶sub _default_limiter {
Subroutine _default_limiter: not called CC=2 SCAR=17.9
4749 0 my ($default, $options) = @_;
4750 0 ▶ if (! grep { exists $options->{ $_ } } qw(single one maybe all any)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {exists $options->{$_};} "single", "one", "maybe", "all", "any") 0 0 0
4751 0 $options->{ $default } = 1;
4752 };
4753 return ()
4754 0 };
4755  
4756 =head2 C<< $mech->click_button( ... ) >>
4757  
4758 $mech->click_button( name => 'go' );
4759 $mech->click_button( input => $mybutton );
4760  
4761 Has the effect of clicking a button on the current form by specifying its
4762 name, value, or index. Its arguments are a list of key/value pairs. Only
4763 one of name, number, input or value must be specified in the keys.
4764  
4765 =over 4
4766  
4767 =item *
4768  
4769 C<name> - name of the button
4770  
4771 =item *
4772  
4773 C<value> - value of the button
4774  
4775 =item *
4776  
4777 C<input> - DOM node
4778  
4779 =item *
4780  
4781 C<id> - id of the button
4782  
4783 =item *
4784  
4785 C<number> - number of the button
4786  
4787 =back
4788  
4789 If you find yourself wanting to specify a button through its
4790 C<selector> or C<xpath>, consider using C<< ->click >> instead.
4791  
4792 =cut
4793  
4794 0 ▶sub click_button($self,%options) {
Subroutine click_button: not called CC=8 SCAR=42.8
Pod documented
4795 0 my $node;
4796 my $xpath;
4797 0 my $user_message;
4798 0 ▶ if (exists $options{ input }) {
Branch: 5 branches
BranchTrueFalseTotal
if (exists $options{'input'}) { } 0 0 0
elsif (exists $options{'name'}) { } 0 0 0
elsif (exists $options{'value'}) { } 0 0 0
elsif (exists $options{'id'}) { } 0 0 0
elsif (exists $options{'number'}) { } 0 0 0
4799 0 $node = delete $options{ input };
4800 } elsif (exists $options{ name }) {
4801 0 my $v = delete $options{ name };
4802 0 $xpath = sprintf( '//*[(translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") = "button" and @name="%s") or (translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")="input" and @type="button" or @type="submit" and @name="%s")]', $v, $v);
4803 0 $user_message = "Button name '$v' unknown";
4804 } elsif (exists $options{ value }) {
4805 0 my $v = delete $options{ value };
4806 0 $xpath = sprintf( '//*[(translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") = "button" and @value="%s") or (translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")="input" and (@type="button" or @type="submit") and @value="%s")]', $v, $v);
4807 0 $user_message = "Button value '$v' unknown";
4808 } elsif (exists $options{ id }) {
4809 0 my $v = delete $options{ id };
4810 0 $xpath = sprintf '//*[@id="%s"]', $v;
4811 0 $user_message = "Button id '$v' unknown";
4812 } elsif (exists $options{ number }) {
4813 0 my $v = delete $options{ number };
4814 0 $xpath = sprintf '//*[translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") = "button" or (translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") = "input" and @type="submit")][%s]', $v;
4815 0 $user_message = "Button number '$v' out of range";
4816 };
4817 0 ▶ $node ||= $self->xpath( $xpath,
Condition0%0/3
$node ||= $self->xpath($xpath, "node", $self->current_form, "single", 1, "user_message", $user_message)
l!l&&r!l&&!r
000
MC/DC0%0/2
$node ||= $self->xpath($xpath, "node", $self->current_form, "single", 1, "user_message", $user_message)
$node $self->xpath($xpath, "node", $self->current_form, "single", 1, "user_message", $user_message)
Truth table0%0/3
A ||= B
A= $nodeB= $self->xpath($xpath, "node", $self->current_form, "single", 1, "user_message", $user_message)
ABresult
1X1
011
000
4818 node => $self->current_form,
4819 single => 1,
4820 user_message => $user_message,
4821 );
4822 0 ▶ if ($node) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node) { } 0 0 0
4823 0 $self->click({ dom => $node, %options });
4824 } else {
4825  
4826 0 $self->signal_condition($user_message);
4827 };
4828  
4829 }
4830  
4831 =head1 FORM METHODS
4832  
4833 =head2 C<< $mech->current_form() >>
4834  
4835 print $mech->current_form->{name};
4836  
4837 Returns the current form.
4838  
4839 This method is incompatible with L<WWW::Mechanize>.
4840 It returns the DOM C<< <form> >> object and not
4841 a L<HTML::Form> instance.
4842  
4843 The current form will be reset by WWW::Mechanize::Chrome
4844 on calls to C<< ->get() >> and C<< ->get_local() >>,
4845 and on calls to C<< ->submit() >> and C<< ->submit_with_fields >>.
4846  
4847 =cut
4848  
4849 0 ▶sub current_form {
Subroutine current_form: not called CC=2 SCAR=17.9
Pod documented
4850 0 my( $self, %options )= @_;
4851 # Find the first <FORM> element from the currently active element
4852 0 ▶ $self->form_number(1) unless $self->{current_form};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"current_form"} 0 0 0
4853 0 $self->{current_form};
4854 }
4855  
4856 0 ▶sub clear_current_form {
Subroutine clear_current_form: not called CC=1 SCAR=6.9
Pod undocumented
4857 0 undef $_[0]->{current_form};
4858 };
4859  
4860 0 ▶sub invalidate_cached_values($self) {
Subroutine invalidate_cached_values: not called CC=1 SCAR=6.9
Pod undocumented
4861 0 $self->clear_current_form;
4862 0 $self->_clear_cached_document;
4863 }
4864  
4865 0 ▶sub active_form {
Subroutine active_form: not called CC=2 SCAR=17.9
Pod undocumented
4866 0 my( $self, %options )= @_;
4867 # Find the first <FORM> element from the currently active element
4868 0 my $focus= $self->target->get_active_element;
4869  
4870 0 ▶ if( !$focus ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($focus) 0 0 0
4871 0 warn "No active element, hence no active form";
4872 return
4873 0 };
4874  
4875 0 my $form= $self->xpath( './ancestor-or-self::FORM', node => $focus, maybe => 1 );
4876  
4877 }
4878  
4879 =head2 C<< $mech->dump_forms( [$fh] ) >>
4880  
4881 open my $fh, '>', 'form-log.txt'
4882 or die "Couldn't open logfile 'form-log.txt': $!";
4883 $mech->dump_forms( $fh );
4884  
4885 Prints a dump of the forms on the current page to
4886 the filehandle C<$fh>. If C<$fh> is not specified or is undef, it dumps
4887 to C<STDOUT>.
4888  
4889 =cut
4890  
4891 0 ▶sub dump_forms {
Subroutine dump_forms: not called CC=8 SCAR=42.8
Pod documented
4892 0 my $self = shift;
4893 0 ▶ my $fh = shift || \*STDOUT;
Condition0%0/2
shift() || \*STDOUT
l!l
00
MC/DC0%0/1
shift() || \*STDOUT
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
4894  
4895 0 for my $form ( $self->forms ) {
4896 0 ▶ print {$fh} "[FORM] ", $form->get_attribute('name', live => 1) || '<no name>', ' ', $form->get_attribute('action'), "\n";
Condition0%0/2
$form->get_attribute('name', 'live', 1) || '<no name>'
l!l
00
MC/DC0%0/1
$form->get_attribute('name', 'live', 1) || '<no name>'
$form->get_attribute('name', 'live', 1)
Truth table0%0/2
A
A= $form->get_attribute('name', 'live', 1)
Aresult
11
00
4897 #for my $f ($self->xpath( './/*', node => $form )) {
4898 #for my $f ($self->xpath( './/*[contains(" "+translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")+" "," input textarea button select "
4899 # )]', node => $form )) {
4900 0 for my $f ($self->xpath( './/*[contains(" input textarea button select ",concat(" ",translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")," "))]', node => $form )) {
4901 0 my $type;
4902 0 ▶ if($type= $f->get_attribute('type', live => 1) || '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type = $f->get_attribute("type", "live", 1) || "") 0 0 0
Condition0%0/2
$f->get_attribute('type', 'live', 1) || ''
l!l
00
MC/DC0%0/1
$f->get_attribute('type', 'live', 1) || ''
$f->get_attribute('type', 'live', 1)
Truth table0%0/2
A
A= $f->get_attribute('type', 'live', 1)
Aresult
11
00
4903 0 $type= " ($type)";
4904 };
4905  
4906 0 ▶ print {$fh} " [", $f->get_attribute('tagName', live => 1), $type, "] ", $f->get_attribute('name') || '<no name>', "\n";
Condition0%0/2
$f->get_attribute('name') || '<no name>'
l!l
00
MC/DC0%0/1
$f->get_attribute('name') || '<no name>'
$f->get_attribute('name')
Truth table0%0/2
A
A= $f->get_attribute('name')
Aresult
11
00
4907 };
4908 }
4909 0 return;
4910 }
4911  
4912 =head2 C<< $mech->form_name( $name [, %options] ) >>
4913  
4914 $mech->form_name( 'search' );
4915  
4916 Selects the current form by its name. The options
4917 are identical to those accepted by the L<< /$mech->xpath >> method.
4918  
4919 =cut
4920  
4921 0 ▶sub form_name {
Subroutine form_name: not called CC=1 SCAR=6.9
Pod documented
4922 0 my ($self,$name,%options) = @_;
4923 0 $name = quote_xpath( $name );
4924 0 _default_limiter( single => \%options );
4925 0 $self->{current_form} = $self->selector("form[name='$name']",
4926 user_info => "form name '$name'",
4927 %options
4928 );
4929 };
4930  
4931 =head2 C<< $mech->form_id( $id [, %options] ) >>
4932  
4933 $mech->form_id( 'login' );
4934  
4935 Selects the current form by its C<id> attribute.
4936 The options
4937 are identical to those accepted by the L<< /$mech->xpath >> method.
4938  
4939 This is equivalent to calling
4940  
4941 $mech->by_id($id,single => 1,%options)
4942  
4943 =cut
4944  
4945 0 ▶sub form_id {
Subroutine form_id: not called CC=1 SCAR=6.9
Pod documented
4946 0 my ($self,$name,%options) = @_;
4947  
4948 0 _default_limiter( single => \%options );
4949 0 $self->{current_form} = $self->by_id($name,
4950 user_info => "form with id '$name'",
4951 %options
4952 );
4953 };
4954  
4955 =head2 C<< $mech->form_number( $number [, %options] ) >>
4956  
4957 $mech->form_number( 2 );
4958  
4959 Selects the I<number>th form.
4960 The options
4961 are identical to those accepted by the L<< /$mech->xpath >> method.
4962  
4963 =cut
4964  
4965 0 ▶sub form_number {
Subroutine form_number: not called CC=1 SCAR=6.9
Pod documented
4966 0 my ($self,$number,%options) = @_;
4967  
4968 0 _default_limiter( single => \%options );
4969 0 $self->{current_form} = $self->xpath("(//form)[$number]",
4970 user_info => "form number $number",
4971 %options
4972 );
4973 0 $self->{current_form};
4974 };
4975  
4976 =head2 C<< $mech->form_with_fields( [$options], @fields ) >>
4977  
4978 $mech->form_with_fields(
4979 'user', 'password'
4980 );
4981  
4982 Find the form which has the listed fields.
4983  
4984 If the first argument is a hash reference, it's taken
4985 as options to C<< ->xpath >>.
4986  
4987 See also L<< /$mech->submit_form >>.
4988  
4989 =cut
4990  
4991 0 ▶sub form_with_fields {
Subroutine form_with_fields: not called CC=2 SCAR=17.9
Pod documented
4992 0 my ($self,@fields) = @_;
4993 0 my $options = {};
4994 0 ▶ if (ref $fields[0] eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $fields[0] eq "HASH") 0 0 0
4995 0 $options = shift @fields;
4996 };
4997 0 my @clauses = map { $self->element_query([qw[input select textarea]], { 'name' => $_ })} @fields;
4998  
4999 0 my $q = "//form[" . join( " and ", @clauses)."]";
5000 #warn $q;
5001 0 _default_limiter( single => $options );
5002 0 $self->{current_form} = $self->xpath($q,
5003 user_info => "form with fields [@fields]",
5004 %$options
5005 );
5006 #warn $form;
5007 0 $self->{current_form};
5008 };
5009  
5010 =head2 C<< $mech->forms( %options ) >>
5011  
5012 my @forms = $mech->forms();
5013  
5014 When called in a list context, returns a list
5015 of the forms found in the last fetched page.
5016 In a scalar context, returns a reference to
5017 an array with those forms.
5018  
5019 The options
5020 are identical to those accepted by the L<< /$mech->selector >> method.
5021  
5022 The returned elements are the DOM C<< <form> >> elements.
5023  
5024 =cut
5025  
5026 0 ▶sub forms {
Subroutine forms: not called CC=2 SCAR=17.9
Pod documented
5027 0 my ($self, %options) = @_;
5028 0 my @res = $self->selector('form', %options);
5029 return wantarray ? @res
5030 0 ▶ : \@res
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
5031 };
5032  
5033 =head2 C<< $mech->field( $selector, $value, [, $index, \@pre_events [,\@post_events]] ) >>
5034  
5035 $mech->field( user => 'joe' );
5036 $mech->field( not_empty => '', 0, [], [] ); # bypass JS validation
5037 $mech->field( date => '2020-04-01', 2 ); # set second field named "date"
5038  
5039 Sets the field with the name given in C<$selector> to the given value.
5040 Returns the value.
5041  
5042 The method understands very basic CSS selectors in the value for C<$selector>,
5043 like the L<HTML::Form> find_input() method.
5044  
5045 A selector prefixed with '#' must match the id attribute of the input.
5046 A selector prefixed with '.' matches the class attribute. A selector
5047 prefixed with '^' or with no prefix matches the name attribute.
5048  
5049 By passing the array reference C<@pre_events>, you can indicate which
5050 Javascript events you want to be triggered before setting the value.
5051 C<@post_events> contains the events you want to be triggered
5052 after setting the value.
5053  
5054 By default, the events set in the
5055 constructor for C<pre_events> and C<post_events>
5056 are triggered.
5057  
5058 =cut
5059  
5060 0 ▶sub field($self,$name,$value,$index=undef,$pre=undef,$post=undef) {
Subroutine field: not called CC=5 SCAR=34.0
Pod documented
5061 0 ▶ if( ref $index ) { # old API
Branch: 1 branch
BranchTrueFalseTotal
if (ref $index) 0 0 0
5062 0 carp "Old API style for ->field() is deprecated. Please fix the call to pass undef for the third parameter if using pre_events/post_events!";
5063 0 $post = $pre;
5064 0 $pre = $index;
5065 0 $index = undef;
5066 };
5067 0 $self->get_set_value(
5068 name => $name,
5069 value => $value,
5070 pre => $pre,
5071 post => $post,
5072 index => $index,
5073 node => $self->current_form,
5074 );
5075 }
5076  
5077 =head2 C<< $mech->sendkeys( %options ) >>
5078  
5079 $mech->sendkeys( string => "Hello World" );
5080  
5081 Sends a series of keystrokes. The keystrokes can be either a string or a
5082 reference to an array containing the detailed data as hashes.
5083  
5084 =over 4
5085  
5086 =item B<string> - the string to send as keystrokes
5087  
5088 =item B<keys> - reference of the array to send as keystrokes
5089  
5090 =item B<delay> - delay in ms to sleep between keys
5091  
5092 =back
5093  
5094 =cut
5095  
5096 0 ▶sub sendkeys_future( $self, %options ) {
Subroutine sendkeys_future: not called CC=4 SCAR=30.0
Pod undocumented
5097 $options{ keys } ||= [ map +{ type => 'char', text => $_ },
5098 split m//, $options{ string }
5099 0 ▶ ];
Condition0%0/2
$options{"keys"} ||= [map({"type", "char", "text", $_}, split(//u, $options{"string"}, 0))]
l!l
00
MC/DC0%0/1
$options{"keys"} ||= [map({"type", "char", "text", $_}, split(//u, $options{"string"}, 0))]
$options{"keys"}
Truth table0%0/2
A
A= $options{"keys"}
Aresult
11
00
5100  
5101 0 my $f = Future->done(1);
5102  
5103 0 for my $key (@{ $options{ keys }}) {
5104 0 ▶ $f = $f->then(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
5105 0 $self->target->send_message('Input.dispatchKeyEvent', %$key );
5106 0 });
5107 0 ▶ if( defined $options{ delay }) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options{"delay"}) 0 0 0
5108 0 ▶ $f->then(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
5109 0 $self->sleep( $options{ delay });
5110 0 });
5111 };
5112 };
5113  
5114 0 return $f
5115 };
5116  
5117 0 ▶sub sendkeys( $self, %options ) {
Subroutine sendkeys: not called CC=1 SCAR=6.9
Pod documented
5118 0 $self->sendkeys_future( %options )->get
5119 }
5120  
5121 =head2 C<< $mech->upload( $selector, $value ) >>
5122  
5123 $mech->upload( user_picture => 'C:/Users/Joe/face.png' );
5124  
5125 Sets the file upload field with the name given in C<$selector> to the given
5126 file. The filename must be an absolute path and filename in the local
5127 filesystem.
5128  
5129 The method understands very basic CSS selectors in the value for C<$selector>,
5130 like the C<< ->field >> method.
5131  
5132 =cut
5133  
5134 # Page.setInterceptFileChooserDialog
5135 # doesn't help anything, since we can only suppress that dialog but not
5136 # supply file names or anything. See the ->upload() method for how to actually
5137 # set filenames
5138  
5139 0 ▶sub upload($self,$name,$value) {
Subroutine upload: not called CC=3 SCAR=24.8
Pod documented
5140 0 my %options;
5141  
5142 0 my @fields = $self->_field_by_name(
5143 name => $name,
5144 user_info => "upload field with name '$name'",
5145 %options );
5146 0 ▶ $value = [$value]
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value 0 0 0
5147 if ! ref $value;
5148  
5149 # Stringify all files:
5150 0 @$value = map { "$_" } @$value;
5151  
5152 0 ▶ if( @fields ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@fields) 0 0 0
5153 0 $self->target->send_message('DOM.setFileInputFiles',
5154 nodeId => 0+$fields[0]->nodeId,
5155 files => $value,
5156 )->get;
5157 }
5158  
5159 }
5160  
5161  
5162 =head2 C<< $mech->value( $selector_or_element, [ $index | %options] ) >>
5163  
5164 print $mech->value( 'user' );
5165  
5166 Returns the value of the field given by C<$selector_or_name> or of the
5167 DOM element passed in.
5168  
5169 If you have multiple fields with the same name, you can use the index
5170 to specify the index directly:
5171  
5172 print $mech->value( 'date', 2 ); # get the second field named "date"
5173  
5174 The legacy form of
5175  
5176 $mech->value( name => value );
5177  
5178 is not supported anymore.
5179  
5180 For fields that can have multiple values, like a C<select> field,
5181 the method is context sensitive and returns the first selected
5182 value in scalar context and all values in list context.
5183  
5184 Note that this method does not support file uploads. See the C<< ->upload >>
5185 method for that.
5186  
5187 =cut
5188  
5189 0 ▶sub value {
Subroutine value: not called CC=4 SCAR=30.0
Pod documented
5190 0 ▶ if (@_ == 3) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 3) { } 0 0 0
5191 0 my ($self,$name,$index) = @_;
5192  
5193 0 ▶ if( defined $index and $index !~ /^\d+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $index and not $index =~ /^\d+$/u) 0 0 0
Condition0%0/3
defined $index and not $index =~ /^\d+$/u
!ll&&!rl&&r
000
MC/DC0%0/2
defined $index and not $index =~ /^\d+$/u
defined $index not $index =~ /^\d+$/u
Truth table0%0/3
A and not(B)
A= defined $indexB= not $index =~ /^\d+$/u
ABresult
0X0
100
111
5194 0 $self->signal_condition("Non-numeric index passed to ->value(). Did you mean to call ->field('$name' => '$index') ?");
5195 };
5196  
5197 0 return $self->get_set_value(
5198 node => $self->current_form,
5199 index => $index,
5200 name => $name,
5201 );
5202  
5203 } else {
5204 0 my ($self,$name,%options) = @_;
5205 0 return $self->get_set_value(
5206 node => $self->current_form,
5207 %options,
5208 name => $name,
5209 );
5210 };
5211 };
5212  
5213 =head2 C<< $mech->get_set_value( %options ) >>
5214  
5215 Allows fine-grained access to getting/setting a value
5216 with a different API. Supported keys are:
5217  
5218 name
5219 value
5220 pre
5221 post
5222  
5223 in addition to all keys that C<< $mech->xpath >> supports.
5224  
5225 =cut
5226  
5227 0 ▶sub _field_by_name {
Subroutine _field_by_name: not called CC=5 SCAR=34.0
5228 0 my ($self,%options) = @_;
5229 0 my @fields;
5230 0 my $name = delete $options{ name };
5231 0 my $attr = 'name';
5232 0 ▶ if ($name =~ s/^\^//) { # if it starts with ^, it's supposed to be a name
Branch: 3 branches
BranchTrueFalseTotal
if ($name =~ s/^\^//u) { } 0 0 0
elsif ($name =~ s/^#//u) { } 0 0 0
elsif ($name =~ s/^\.//u) { } 0 0 0
5233 0 $attr = 'name'
5234 } elsif ($name =~ s/^#//) {
5235 0 $attr = 'id'
5236 } elsif ($name =~ s/^\.//) {
5237 0 $attr = 'class'
5238 };
5239 0 ▶ if (blessed $name) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($name)) { } 0 0 0
5240 0 @fields = $name;
5241 } else {
5242 0 _default_limiter( single => \%options );
5243 0 my $query = $self->element_query([qw[input select textarea]], { $attr => $name });
5244 0 @fields = $self->xpath($query,%options);
5245 };
5246 @fields
5247 0 }
5248  
5249 =head2 C<< $mech->set_field( %options ) >>
5250  
5251 $mech->set_field(
5252 field => $field_node,
5253 value => 'foo',
5254 );
5255  
5256 Low level value setting method. Use this if you have an input element outside
5257 of a E<lt>formE<gt> tag.
5258  
5259 =cut
5260  
5261 0 ▶sub set_field($self, %options ) {
Subroutine set_field: not called CC=21 SCAR=61.4
Pod documented
5262 0 my $value = delete $options{ value };
5263 0 my $pre = delete $options{pre};
5264 0 ▶ $pre = [$pre]
Branch: 1 branch
BranchTrueFalseTotal
if defined $pre and not ref $pre 0 0 0
Condition0%0/3
defined $pre and not ref $pre
!ll&&!rl&&r
000
MC/DC0%0/2
defined $pre and not ref $pre
defined $pre not ref $pre
Truth table0%0/3
A and not(B)
A= defined $preB= not ref $pre
ABresult
0X0
100
111
5265 if (defined $pre and ! ref $pre);
5266 0 my $post = delete $options{post};
5267 0 ▶ $post = [$post]
Branch: 1 branch
BranchTrueFalseTotal
if defined $post and not ref $post 0 0 0
Condition0%0/3
defined $post and not ref $post
!ll&&!rl&&r
000
MC/DC0%0/2
defined $post and not ref $post
defined $post not ref $post
Truth table0%0/3
A and not(B)
A= defined $postB= not ref $post
ABresult
0X0
100
111
5268 if (defined $post and ! ref $post);
5269 0 ▶ $pre ||= ['focus']; # just to eliminate some checks downwards
Condition0%0/2
$pre ||= ["focus"]
l!l
00
MC/DC0%0/1
$pre ||= ["focus"]
$pre
Truth table0%0/2
A
A= $pre
Aresult
11
00
5270 0 ▶ $post ||= ['change']; # just to eliminate some checks downwards
Condition0%0/2
$post ||= ["change"]
l!l
00
MC/DC0%0/1
$post ||= ["change"]
$post
Truth table0%0/2
A
A= $post
Aresult
11
00
5271 my $obj = delete $options{ field }
5272 0 ▶ or croak "Need a field to set";
Branch: 1 branch
BranchTrueFalseTotal
my $obj = delete $options{"field"} or croak("Need a field to set") 0 0 0
5273 0 my $tag = $obj->get_tag_name();
5274  
5275 0 my %method = (
5276 input => 'value',
5277 textarea => 'content',
5278 select => 'selected',
5279 );
5280 0 my $method = $method{ lc $tag };
5281 0 ▶ if( lc $tag eq 'input' and $obj->get_attribute('type', live => 1) eq 'radio' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $tag eq "input" and $obj->get_attribute("type", "live", 1) eq "radio") 0 0 0
Condition0%0/3
lc $tag eq "input" and $obj->get_attribute("type", "live", 1) eq "radio"
!ll&&!rl&&r
000
MC/DC0%0/2
lc $tag eq "input" and $obj->get_attribute("type", "live", 1) eq "radio"
lc $tag eq "input" $obj->get_attribute("type", "live", 1) eq "radio"
Truth table0%0/3
A and B
A= lc $tag eq "input"B= $obj->get_attribute("type", "live", 1) eq "radio"
ABresult
0X0
100
111
5282 0 $method = 'checked';
5283 };
5284  
5285 0 my $id = $obj->objectId;
5286 0 ▶ if( ! $id ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($id) 0 0 0
5287 0 warn "No object id for nodeId " . $obj->nodeId;
5288 };
5289  
5290 # Send pre-change events:
5291 0 for my $ev (@$pre) {
5292 0 $self->target->send_message(
5293 'Runtime.callFunctionOn',
5294 objectId => $id,
5295 functionDeclaration => <<'JS',
5296 function(ev) {
5297 var event = new Event(ev, {
5298 view : window,
5299 bubbles: true,
5300 cancelable: true
5301 });
5302 this.dispatchEvent(event);
5303 }
5304 JS
5305 arguments => [{ value => $ev }],
5306 );
5307 };
5308  
5309 0 ▶ if( 'value' eq $method ) {
Branch: 4 branches
BranchTrueFalseTotal
if ('value' eq $method) { } 0 0 0
elsif ('selected' eq $method) { } 0 0 0
elsif ('checked' eq $method) { } 0 0 0
elsif ('content' eq $method) { } 0 0 0
5310 0 $self->target->send_message('DOM.setAttributeValue', nodeId => 0+$obj->nodeId, name => 'value', value => "$value" )->get;
5311  
5312 } elsif( 'selected' eq $method ) {
5313 # ignoring undef; but [] would reset to no option
5314 0 ▶ if (defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) 0 0 0
5315  
5316 0 ▶ $value = [ $value ] unless ref $value;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value 0 0 0
5317 0 $self->target->send_message(
5318 'Runtime.callFunctionOn',
5319 objectId => $id,
5320 functionDeclaration => <<'JS',
5321 function(newValue) {
5322 var i, j;
5323 if (this.multiple == true) {
5324 for (i=0; i<this.options.length; i++) {
5325 this.options[i].selected = false
5326 }
5327 }
5328 for (j=0; j<newValue.length; j++) {
5329 for (i=0; i<this.options.length; i++) {
5330 if (this.options[i].value == newValue[j]) {
5331 this.options[i].selected = true
5332 }
5333 }
5334 }
5335 }
5336 JS
5337 arguments => [{ value => $value }],
5338 )->get;
5339 }
5340 } elsif( 'checked' eq $method ) {
5341 0 ▶ if (defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) 0 0 0
5342 0 ▶ $value = [ $value ] unless ref $value;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value 0 0 0
5343 0 $obj->set_attribute('checked' => JSON::true);
5344 }
5345 } elsif( 'content' eq $method ) {
5346 0 $self->target->send_message('Runtime.callFunctionOn',
5347 objectId => $id,
5348 functionDeclaration => 'function(newValue) { this.innerHTML = newValue }',
5349 arguments => [{ value => $value }]
5350 )->get;
5351 } else {
5352 0 die "Don't know how to set the value for node '$tag', sorry";
5353 };
5354  
5355 # Send post-change events
5356 # Send pre-change events:
5357 0 for my $ev (@$post) {
5358 0 $self->target->send_message(
5359 'Runtime.callFunctionOn',
5360 objectId => $id,
5361 functionDeclaration => <<'JS',
5362 function(ev) {
5363 var event = new Event(ev, {
5364 view : window,
5365 bubbles: true,
5366 cancelable: true
5367 });
5368 this.dispatchEvent(event);
5369 }
5370 JS
5371 arguments => [{ value => $ev }],
5372 );
5373 };
5374 }
5375  
5376 0 ▶sub get_set_value($self,%options) {
Subroutine get_set_value: not called CC=20 SCAR=60.4
Pod documented
5377 0 my $set_value = exists $options{ value };
5378 0 my $value = delete $options{ value };
5379 0 my $pre = delete $options{pre};
5380 0 ▶ $pre = [$pre]
Branch: 1 branch
BranchTrueFalseTotal
if defined $pre and not ref $pre 0 0 0
Condition0%0/3
defined $pre and not ref $pre
!ll&&!rl&&r
000
MC/DC0%0/2
defined $pre and not ref $pre
defined $pre not ref $pre
Truth table0%0/3
A and not(B)
A= defined $preB= not ref $pre
ABresult
0X0
100
111
5381 if (defined $pre and ! ref $pre);
5382 0 my $post = delete $options{post};
5383 0 ▶ $post = [$post]
Branch: 1 branch
BranchTrueFalseTotal
if defined $post and not ref $post 0 0 0
Condition0%0/3
defined $post and not ref $post
!ll&&!rl&&r
000
MC/DC0%0/2
defined $post and not ref $post
defined $post not ref $post
Truth table0%0/3
A and not(B)
A= defined $postB= not ref $post
ABresult
0X0
100
111
5384 if (defined $post and ! ref $post);
5385 0 ▶ $pre ||= ['focus']; # just to eliminate some checks downwards
Condition0%0/2
$pre ||= ["focus"]
l!l
00
MC/DC0%0/1
$pre ||= ["focus"]
$pre
Truth table0%0/2
A
A= $pre
Aresult
11
00
5386 0 ▶ $post ||= ['change']; # just to eliminate some checks downwards
Condition0%0/2
$post ||= ["change"]
l!l
00
MC/DC0%0/1
$post ||= ["change"]
$post
Truth table0%0/2
A
A= $post
Aresult
11
00
5387 0 my $name = delete $options{ name };
5388 0 my $index = delete $options{ index };
5389  
5390 0 my $index_name = '';
5391 0 ▶ if( defined $index ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $index) 0 0 0
5392 0 ▶ if( $index == 1 or $index =~ /[^1]1$/ ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($index == 1 or $index =~ /[^1]1$/u) { } 0 0 0
elsif ($index == 2 or $index =~ /[^1]2$/u) { } 0 0 0
elsif ($index == 3 or $index =~ /[^1]3$/u) { } 0 0 0
Condition0%0/3
$index == 1 or $index =~ /[^1]1$/u
l!l&&r!l&&!r
000
MC/DC0%0/2
$index == 1 or $index =~ /[^1]1$/u
$index == 1 $index =~ /[^1]1$/u
Truth table0%0/3
A or B
A= $index == 1B= $index =~ /[^1]1$/u
ABresult
1X1
011
000
5393 0 $index_name = "${index}st ";
5394  
5395 ▶ } elsif( $index == 2 or $index =~ /[^1]2$/ ) {
Condition0%0/3
$index == 2 or $index =~ /[^1]2$/u
l!l&&r!l&&!r
000
MC/DC0%0/2
$index == 2 or $index =~ /[^1]2$/u
$index == 2 $index =~ /[^1]2$/u
Truth table0%0/3
A or B
A= $index == 2B= $index =~ /[^1]2$/u
ABresult
1X1
011
000
5396 0 $index_name = "${index}nd ";
5397  
5398 ▶ } elsif( $index == 3 or $index =~ /[^1]3$/ ) {
Condition0%0/3
$index == 3 or $index =~ /[^1]3$/u
l!l&&r!l&&!r
000
MC/DC0%0/2
$index == 3 or $index =~ /[^1]3$/u
$index == 3 $index =~ /[^1]3$/u
Truth table0%0/3
A or B
A= $index == 3B= $index =~ /[^1]3$/u
ABresult
1X1
011
000
5399 0 $index_name = "${index}rd ";
5400  
5401 } else {
5402 0 $index_name = "${index}th ";
5403 }
5404 };
5405 0 my @fields = $self->_field_by_name(
5406 name => $name,
5407 user_info => "${index_name}input with name '$name'",
5408 index => $index,
5409 %options );
5410  
5411 0 ▶ if (my $obj = $fields[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $obj = $fields[0]) { } 0 0 0
5412  
5413 0 ▶ if ($set_value) {
Branch: 1 branch
BranchTrueFalseTotal
if ($set_value) 0 0 0
5414 0 $self->set_field(
5415 field => $obj,
5416 value => $value,
5417 pre => $pre,
5418 post => $post,
5419 );
5420 };
5421  
5422 # Don't bother to fetch the field's value if it's not wanted
5423 0 ▶ return unless defined wantarray;
Branch: 1 branch
BranchTrueFalseTotal
unless defined wantarray 0 0 0
5424  
5425 # We could save some work here for the simple case of single-select
5426 # dropdowns by not enumerating all options
5427 0 my $tag = $obj->get_tag_name();
5428 0 ▶ if ('SELECT' eq uc $tag) {
Branch: 1 branch
BranchTrueFalseTotal
if ('SELECT' eq uc $tag) { } 0 0 0
5429 0 my $id = $obj->objectId;
5430 0 ▶ if( ! $id ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($id) 0 0 0
5431 0 warn "No object id for nodeId " . $obj->nodeId;
5432 };
5433 my $arr = $self->target->send_message(
5434 'Runtime.callFunctionOn',
5435 objectId => $id,
5436 functionDeclaration => <<'JS',
5437 function() {
5438 var i;
5439 var arr = [];
5440 for (i=0; i<this.options.length; i++) {
5441 if (this.options[i].selected == true) {
5442 arr.push(this.options[i].value);
5443 }
5444 }
5445 return arr;
5446 }
5447 JS
5448 arguments => [],
5449 0 returnByValue => JSON::true)->get->{result};
5450  
5451 0 my @values = @{$arr->{value}};
5452 0 ▶ if (wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 0 0
5453 return @values
5454 0 } else {
5455 0 return $values[0];
5456 }
5457 } else {
5458 0 return $obj->get_attribute('value', live => 1);
5459 };
5460 } else {
5461 return
5462 0 }
5463 }
5464  
5465 =head2 C<< $mech->select( $name, $value ) >>
5466  
5467 =head2 C<< $mech->select( $name, \@values ) >>
5468  
5469 $mech->select( 'items', 'banana' );
5470  
5471 Given the name of a C<select> field, set its value to the value
5472 specified. If the field is not C<< <select multiple> >> and the
5473 C<$value> is an array, only the B<first> value will be set.
5474 Passing C<$value> as a hash with
5475 an C<n> key selects an item by number (e.g.
5476 C<< {n => 3} >> or C<< {n => [2,4]} >>).
5477 The numbering starts at 1. This applies to the current form.
5478  
5479 If you have a field with C<< <select multiple> >> and you pass a single
5480 C<$value>, then C<$value> will be added to the list of fields selected,
5481 without clearing the others. However, if you pass an array reference,
5482 then all previously selected values will be cleared.
5483  
5484 Returns true on successfully setting the value. On failure, returns
5485 false and calls C<< $self>warn() >> with an error message.
5486  
5487 =cut
5488  
5489 0 ▶sub select($self, $name, $value) {
Subroutine select: not called CC=16 SCAR=56.1
Pod documented
5490 0 my $field;
5491 0 ▶ if( ! eval {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { ($field) = $self->_field_by_name("node", $self->current_form, "name", $name); 1 } }) 0 0 0
5492 0 ($field) = $self->_field_by_name(
5493 node => $self->current_form,
5494 name => $name,
5495 #%options,
5496 );
5497 0 1;
5498 }) {
5499 # the field was not found
5500 0 return;
5501 };
5502  
5503 0 my @options = $self->xpath( './/option', node => $field);
5504 0 my @by_index;
5505 my @by_value;
5506 0 my $single = $field->get_attribute('type', live => 1) eq "select-one";
5507 0 my $deselect;
5508  
5509 0 ▶ if ('HASH' eq ref $value||'') {
Branch: 2 branches
BranchTrueFalseTotal
if ('HASH' eq ref $value or '') { } 0 0 0
elsif ('ARRAY' eq ref $value or '') { } 0 0 0
Condition0%0/2
"HASH" eq ref $value or ""
l!l
00
MC/DC0%0/1
"HASH" eq ref $value or ""
"HASH" eq ref $value
Truth table0%0/2
A
A= "HASH" eq ref $value
Aresult
11
00
5510 0 for (keys %$value) {
5511 0 ▶ $self->warn(qq{Unknown select value parameter "$_"})
Branch: 1 branch
BranchTrueFalseTotal
unless $_ eq "n" 0 0 0
5512 unless $_ eq 'n';
5513 }
5514  
5515 0 $deselect = ref $value->{n};
5516 0 ▶ @by_index = ref $value->{n} ? @{ $value->{n} } : $value->{n};
Branch: 1 branch
BranchTrueFalseTotal
ref $value->{'n'} ? : 0 0 0
5517 ▶ } elsif ('ARRAY' eq ref $value||'') {
Condition0%0/2
"ARRAY" eq ref $value or ""
l!l
00
MC/DC0%0/1
"ARRAY" eq ref $value or ""
"ARRAY" eq ref $value
Truth table0%0/2
A
A= "ARRAY" eq ref $value
Aresult
11
00
5518 # clear all preselected values
5519 0 $deselect = 1;
5520 0 @by_value = @{ $value };
5521 } else {
5522 0 @by_value = $value;
5523 };
5524  
5525 0 ▶ if ($deselect) {
Branch: 1 branch
BranchTrueFalseTotal
if ($deselect) 0 0 0
5526 0 for my $o (@options) {
5527 0 $o->{selected} = 0;
5528 }
5529 };
5530  
5531 0 ▶ if ($single) {
Branch: 1 branch
BranchTrueFalseTotal
if ($single) 0 0 0
5532 # Only use the first element for single-element boxes
5533 0 ▶ $#by_index = 0+@by_index ? 0 : -1;
Branch: 1 branch
BranchTrueFalseTotal
0 + @by_index ? : 0 0 0
5534 0 ▶ $#by_value = 0+@by_value ? 0 : -1;
Branch: 1 branch
BranchTrueFalseTotal
0 + @by_value ? : 0 0 0
5535 };
5536  
5537 # Select the items, either by index or by value
5538 0 for my $idx (@by_index) {
5539 0 $options[$idx-1]->set_attribute('selected' => 1 );
5540 };
5541  
5542 0 for my $v (@by_value) {
5543 0 my $option = $self->xpath( sprintf( './/option[@value="%s"]', quote_xpath( $v )) , node => $field, single => 1 );
5544 0 $option->set_attribute( 'selected' => '1' );
5545 };
5546  
5547 0 return @by_index + @by_value > 0;
5548 }
5549  
5550 =head2 C<< $mech->tick( $name, $value [, $set ] ) >>
5551  
5552 $mech->tick("confirmation_box", 'yes');
5553  
5554 "Ticks" the first checkbox that has both the name and value associated with it
5555 on the current form. Dies if there is no named check box for that value.
5556 Passing in a false value as the third optional argument will cause the
5557 checkbox to be unticked.
5558  
5559 (Un)ticking the checkbox is done by sending a click event to it if needed.
5560 If C<$value> is C<undef>, the first checkbox matching C<$name> will
5561 be (un)ticked.
5562  
5563 If C<$name> is a reference to a hash, that hash will be used
5564 as the options to C<< ->find_link_dom >> to find the element.
5565  
5566 =cut
5567  
5568 0 ▶sub tick($self, $name, $value=undef, $set=1) {
Subroutine tick: not called CC=18 SCAR=58.3
Pod documented
5569 0 my %options;
5570 my @boxes;
5571  
5572 0 ▶ if (! defined $name) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $name) { } 0 0 0
elsif (ref $name and builtin::blessed($name)) { } 0 0 0
elsif (ref $name eq 'HASH') { } 0 0 0
5573 0 croak("->tick called with undef name");
5574 ▶ } elsif (ref $name and blessed($name)) {
Condition0%0/3
ref $name and builtin::blessed($name)
!ll&&!rl&&r
000
MC/DC0%0/2
ref $name and builtin::blessed($name)
ref $name builtin::blessed($name)
Truth table0%0/3
A and B
A= ref $nameB= builtin::blessed($name)
ABresult
0X0
100
111
5575 0 $options{ dom } = $name;
5576 } elsif (ref $name eq 'HASH') { # options
5577 0 %options = %$name;
5578 } else {
5579 0 $options{ name } = $name;
5580 };
5581  
5582 0 ▶ if (exists $options{ name }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options{"name"}) 0 0 0
5583 0 my $attr = 'name';
5584 0 ▶ if ($name =~ s/^\^//) { # if it starts with ^, it's supposed to be a name
Branch: 3 branches
BranchTrueFalseTotal
if ($name =~ s/^\^//u) { } 0 0 0
elsif ($name =~ s/^#//u) { } 0 0 0
elsif ($name =~ s/^\.//u) { } 0 0 0
5585 0 $attr = 'name'
5586 } elsif ($name =~ s/^#//) {
5587 0 $attr = 'id'
5588 } elsif ($name =~ s/^\.//) {
5589 0 $attr = 'class'
5590 };
5591 0 $name = quotemeta($name);
5592 0 ▶ $value = quotemeta($value) if $value;
Branch: 1 branch
BranchTrueFalseTotal
if $value 0 0 0
5593  
5594 0 _default_limiter( one => \%options );
5595 0 my $q = $self->element_query(
5596 ['input'],
5597 {
5598 $attr => $name,
5599 type => 'checkbox',
5600 maybe value => $value,
5601 }
5602 );
5603 0 $options{ xpath } = $q;
5604 #$options{ xpath } = [
5605 # defined $value
5606 # ? sprintf( q{//input[@type="checkbox" and @%s="%s" and @value="%s"]}, $attr, $name, $value)
5607 # : sprintf( q{//input[@type="checkbox" and @%s="%s"]}, $attr, $name)
5608 #];
5609 0 ▶ $options{ user_info } = defined $value
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 0 0 0
5610 ? "Checkbox with name '$name' and value '$value'"
5611 : "Checkbox with name '$name'";
5612 };
5613  
5614 0 ▶ if ($options{ dom }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{'dom'}) { } 0 0 0
5615 0 @boxes = $options{ dom };
5616 } else {
5617 0 @boxes = $self->_option_query(%options);
5618 };
5619  
5620 0 my $target = $boxes[0];
5621 0 ▶ my $is_set = ($target->get_attribute( 'checked', live => 1 ) || '') eq 'checked';
Condition0%0/2
$target->get_attribute('checked', 'live', 1) || ''
l!l
00
MC/DC0%0/1
$target->get_attribute('checked', 'live', 1) || ''
$target->get_attribute('checked', 'live', 1)
Truth table0%0/2
A
A= $target->get_attribute('checked', 'live', 1)
Aresult
11
00
5622 0 ▶ if ($set xor $is_set) {
Branch: 1 branch
BranchTrueFalseTotal
if ($set xor $is_set) 0 0 0
Condition0%0/4
$set xor $is_set
l&&rl&&!r!l&&r!l&&!r
0000
MC/DC0%0/2
$set xor $is_set
$set $is_set
Truth table0%0/4
A xor B
A= $setB= $is_set
ABresult
110
101
011
000
5623 0 ▶ if ($set) {
Branch: 1 branch
BranchTrueFalseTotal
if ($set) { } 0 0 0
5624 0 $target->set_attribute('checked', 'checked');
5625 } else {
5626 0 $target->set_attribute('checked', undef);
5627 };
5628 };
5629 };
5630  
5631 =head2 C<< $mech->untick( $name, $value ) >>
5632  
5633 $mech->untick('spam_confirm','yes',undef)
5634  
5635 Causes the checkbox to be unticked. Shorthand for
5636  
5637 $mech->tick($name,$value,undef)
5638  
5639 =cut
5640  
5641 0 ▶sub untick {
Subroutine untick: not called CC=1 SCAR=6.9
Pod documented
5642 0 my ($self, $name, $value) = @_;
5643 0 $self->tick( $name, $value, undef );
5644 };
5645  
5646 =head2 C<< $mech->submit( $form ) >>
5647  
5648 $mech->submit;
5649  
5650 Submits the form. Note that this does B<not> fire the C<onClick>
5651 event and thus also does not fire eventual Javascript handlers.
5652 Maybe you want to use C<< $mech->click >> instead.
5653  
5654 The default is to submit the current form as returned
5655 by C<< $mech->current_form >>.
5656  
5657 =cut
5658  
5659 0 ▶sub submit($self,$dom_form = $self->current_form) {
Subroutine submit: not called CC=3 SCAR=24.8
Pod documented
5660 0 ▶ if ($dom_form) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dom_form) { } 0 0 0
5661 # We should prepare for navigation here as well
5662 # The __proto__ invocation is so we can have a HTML form field entry
5663 # named "submit"
5664  
5665 0 ▶ $self->_mightNavigate( sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
5666 0 $self->target->send_message(
5667 'Runtime.callFunctionOn',
5668 objectId => $dom_form->objectId,
5669 functionDeclaration => 'function() { var action = this.action; var isCallable = action && typeof(action) === "function"; if( isCallable) { action() } else { this.__proto__.submit.apply(this) }}'
5670 );
5671 })
5672 0 ->get;
5673  
5674 0 $self->invalidate_cached_values;
5675 } else {
5676 0 croak "I don't know which form to submit, sorry.";
5677 }
5678 0 return $self->response;
5679 };
5680  
5681 =head2 C<< $mech->submit_form( %options ) >>
5682  
5683 $mech->submit_form(
5684 with_fields => {
5685 user => 'me',
5686 pass => 'secret',
5687 }
5688 );
5689  
5690 This method lets you select a form from the previously fetched page,
5691 fill in its fields, and submit it. It combines the form_number/form_name,
5692 C<< ->set_fields >> and C<< ->click methods >> into one higher level call. Its
5693 arguments are a list of key/value pairs, all of which are optional.
5694  
5695 =over 4
5696  
5697 =item *
5698  
5699 C<< form => $mech->current_form() >>
5700  
5701 Specifies the form to be filled and submitted. Defaults to the current form.
5702  
5703 =item *
5704  
5705 C<< fields => \%fields >>
5706  
5707 Specifies the fields to be filled in the current form
5708  
5709 =item *
5710  
5711 C<< with_fields => \%fields >>
5712  
5713 Probably all you need for the common case. It combines a smart form selector
5714 and data setting in one operation. It selects the first form that contains
5715 all fields mentioned in \%fields. This is nice because you don't need to
5716 know the name or number of the form to do this.
5717  
5718 (calls L<< /$mech->form_with_fields() >> and L<< /$mech->set_fields() >>).
5719  
5720 If you choose this, the form_number, form_name, form_id and fields options
5721 will be ignored.
5722  
5723 =back
5724  
5725 =cut
5726  
5727 0 ▶sub submit_form($self,%options) {;
Subroutine submit_form: not called CC=9 SCAR=45.0
Pod documented
5728  
5729 0 my $form = delete $options{ form };
5730 0 my $fields;
5731 0 ▶ if (! $form) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($form) 0 0 0
5732 0 ▶ if ($fields = delete $options{ with_fields }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fields = delete $options{'with_fields'}) { } 0 0 0
5733 0 my @names = keys %$fields;
5734 0 $form = $self->form_with_fields( \%options, @names );
5735 0 ▶ if (! $form) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($form) 0 0 0
5736 0 $self->signal_condition("Couldn't find a matching form for @names.");
5737 return
5738 0 };
5739 } else {
5740 0 ▶ $fields = delete $options{ fields } || {};
Condition0%0/2
delete $options{'fields'} || {}
l!l
00
MC/DC0%0/1
delete $options{'fields'} || {}
delete $options{'fields'}
Truth table0%0/2
A
A= delete $options{'fields'}
Aresult
11
00
5741 0 $form = $self->current_form;
5742 };
5743 };
5744  
5745 0 ▶ if (! $form) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($form) 0 0 0
5746 0 $self->signal_condition("No form found to submit.");
5747 return
5748 0 };
5749 #warn Dumper $fields;
5750 #$self->log('debug', sprintf 'Submitting form %s with fields %s', $form->{id}, Dumper $fields);
5751 0 $self->do_set_fields( form => $form, fields => $fields );
5752  
5753 0 my $response;
5754 0 ▶ if ( $options{button} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{'button'}) { } 0 0 0
5755 0 ▶ $response = $self->click( $options{button}, $options{x} || 0, $options{y} || 0 );
Condition0%0/4
$options{'x'} || 0
l!l
00
$options{'y'} || 0
l!l
00
MC/DC0%0/1
$options{'x'} || 0
$options{'x'}
MC/DC0%0/1
$options{'y'} || 0
$options{'y'}
Truth table0%0/2
A
A= $options{'x'}
Aresult
11
00
Truth table0%0/2
A
A= $options{'y'}
Aresult
11
00
5756 }
5757 else {
5758 0 $response = $self->submit();
5759 }
5760 0 return $response;
5761  
5762 }
5763  
5764 =head2 C<< $mech->set_fields( $name => $value, ... ) >>
5765  
5766 $mech->set_fields(
5767 user => 'me',
5768 pass => 'secret',
5769 );
5770  
5771 This method sets multiple fields of the current form. It takes a list of
5772 field name and value pairs. If there is more than one field with the same
5773 name, the first one found is set. If you want to select which of the
5774 duplicate field to set, use a value which is an anonymous array which
5775 has the field value and its number as the 2 elements.
5776  
5777 $mech->set_fields(
5778 user => 'me',
5779 pass => 'secret',
5780 pass => [ 'secret', 2 ], # repeated password field
5781 );
5782  
5783 =cut
5784  
5785 0 ▶sub set_fields($self, %fields) {;
Subroutine set_fields: not called CC=2 SCAR=17.9
Pod documented
5786 0 my $f = $self->current_form;
5787 0 ▶ if (! $f) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($f) 0 0 0
5788 0 croak "Can't set fields: No current form set.";
5789 };
5790 0 $self->do_set_fields(form => $f, fields => \%fields);
5791 };
5792  
5793 0 ▶sub do_set_fields($self, %options) {
Subroutine do_set_fields: not called CC=3 SCAR=24.8
Pod undocumented
5794 0 my $form = delete $options{ form };
5795 0 my $fields = delete $options{ fields };
5796  
5797 0 ▶ while (my($n,$v) = each %$fields) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$fields) 0 0 0
5798 0 my $index = undef;
5799 0 ▶ if (ref $v) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v) 0 0 0
5800 0 ($v,my $num) = @$v;
5801 0 $index = $num;
5802 };
5803  
5804 0 $self->get_set_value( node => $form, name => $n, value => $v, index => $index, %options );
5805 }
5806 };
5807  
5808 =head1 CONTENT MONITORING METHODS
5809  
5810 =head2 C<< $mech->is_visible( $element ) >>
5811  
5812 =head2 C<< $mech->is_visible( %options ) >>
5813  
5814 if ($mech->is_visible( selector => '#login' )) {
5815 print "You can log in now.";
5816 };
5817  
5818 Returns true if the element is visible, that is, it is
5819 a member of the DOM and neither it nor its ancestors have
5820 a CSS C<visibility> attribute of C<hidden> or
5821 a C<display> attribute of C<none>.
5822  
5823 You can either pass in a DOM element or a set of key/value
5824 pairs to search the document for the element you want.
5825  
5826 =over 4
5827  
5828 =item *
5829  
5830 C<xpath> - the XPath query
5831  
5832 =item *
5833  
5834 C<selector> - the CSS selector
5835  
5836 =item *
5837  
5838 C<dom> - a DOM node
5839  
5840 =back
5841  
5842 The remaining options are passed through to either the
5843 L<< /$mech->xpath|xpath >> or L<< /$mech->selector|selector >> method.
5844  
5845 =cut
5846  
5847 0 ▶sub is_visible {
Subroutine is_visible: not called CC=5 SCAR=34.0
Pod documented
5848 0 my( $self, @args ) = @_;
5849 0 my %options;
5850 0 ▶ if (2 == @_) {
Branch: 1 branch
BranchTrueFalseTotal
if (2 == @_) { } 0 0 0
5851 0 ($self,$options{dom}) = @_;
5852 } else {
5853 0 ($self,%options) = @_;
5854 };
5855 0 _default_limiter( 'maybe', \%options );
5856 0 ▶ if (! $options{dom}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options{"dom"}) 0 0 0
5857 0 $options{dom} = $self->_option_query(%options);
5858 };
5859 # No element means not visible
5860 return
5861 0 ▶ unless $options{ dom };
Branch: 1 branch
BranchTrueFalseTotal
unless $options{"dom"} 0 0 0
5862 #$options{ window } ||= $self->tab->{linkedBrowser}->{contentWindow};
5863  
5864 0 my $id = $options{ dom }->objectId;
5865 0 my ($val, $type) = $self->callFunctionOn(<<'JS', objectId => $id, arguments => []); #->get;
5866 function ()
5867 {
5868 var obj = this;
5869 while (obj) {
5870 // No object
5871 if (!obj) return false;
5872  
5873 try {
5874 if( obj["parentNode"] ) 1;
5875 } catch (e) {
5876 // Dead object
5877 return false
5878 };
5879 // Descends from document, so we're done
5880 if (obj.parentNode === obj.ownerDocument) {
5881 return true;
5882 };
5883 // Not in the DOM
5884 if (!obj.parentNode) {
5885 return false;
5886 };
5887 // Direct style check
5888 if (obj.style) {
5889 if (obj.style.display == 'none') return false;
5890 if (obj.style.visibility == 'hidden') return false;
5891 };
5892  
5893 if (window.getComputedStyle) {
5894 var style = window.getComputedStyle(obj, null);
5895 if (style.display == 'none') {
5896 return false; }
5897 if (style.visibility == 'hidden') {
5898 return false;
5899 };
5900 };
5901 obj = obj.parentNode;
5902 };
5903 // The object does not live in the DOM at all
5904 return false
5905 }
5906 JS
5907 0 ▶ $type eq 'boolean'
Branch: 1 branch
BranchTrueFalseTotal
$type eq "boolean" or die "Don't know how to handle Javascript type '${type}'" 0 0 0
5908 or die "Don't know how to handle Javascript type '$type'";
5909 0 return $val
5910 };
5911  
5912 =head2 C<< $mech->wait_until_invisible( $element ) >>
5913  
5914 =head2 C<< $mech->wait_until_invisible( %options ) >>
5915  
5916 $mech->wait_until_invisible( $please_wait );
5917  
5918 Waits until an element is not visible anymore.
5919  
5920 Takes the same options as L<< $mech->is_visible/->is_visible >>.
5921  
5922 In addition, the following options are accepted:
5923  
5924 =over 4
5925  
5926 =item *
5927  
5928 C<timeout> - the timeout after which the function will C<croak>. To catch
5929 the condition and handle it in your calling program, use an L<eval> block.
5930 A timeout of C<0> means to never time out.
5931  
5932 See also C<max_wait> if you want to wait a limited time for an element to
5933 appear.
5934  
5935 =item *
5936  
5937 C<max_wait> - the maximum time to wait until the function will return.
5938 A max_wait of C<0> means to never time out. If the element is still visible,
5939 the function will return a false value.
5940  
5941 =item *
5942  
5943 C<sleep> - the interval in seconds used to L<sleep>. Subsecond
5944 intervals are possible.
5945  
5946 =back
5947  
5948 Note that when passing in a selector, that selector is requeried
5949 on every poll instance. So the following query will work as expected:
5950  
5951 xpath => '//*[contains(text(),"stand by")]'
5952  
5953 This also means that if your selector query relies on finding
5954 a changing text, you need to pass the node explicitly instead of
5955 passing the selector.
5956  
5957 =cut
5958  
5959 0 ▶sub wait_until_invisible {
Subroutine wait_until_invisible: not called CC=16 SCAR=56.1
Pod documented
5960 0 my( $self, %options );
5961 0 ▶ if (2 == @_) {
Branch: 1 branch
BranchTrueFalseTotal
if (2 == @_) { } 0 0 0
5962 0 ($self,$options{dom}) = @_;
5963 } else {
5964 0 ($self,%options) = @_;
5965 };
5966 0 ▶ my $sleep = delete $options{ sleep } || 0.3;
Condition0%0/2
delete $options{'sleep'} || 0.3
l!l
00
MC/DC0%0/1
delete $options{'sleep'} || 0.3
delete $options{'sleep'}
Truth table0%0/2
A
A= delete $options{'sleep'}
Aresult
11
00
5967 0 ▶ my $timeout = delete $options{ timeout } || 0;
Condition0%0/2
delete $options{'timeout'} || 0
l!l
00
MC/DC0%0/1
delete $options{'timeout'} || 0
delete $options{'timeout'}
Truth table0%0/2
A
A= delete $options{'timeout'}
Aresult
11
00
5968 0 ▶ my $wait = delete $options{ max_wait } || 0;
Condition0%0/2
delete $options{'max_wait'} || 0
l!l
00
MC/DC0%0/1
delete $options{'max_wait'} || 0
delete $options{'max_wait'}
Truth table0%0/2
A
A= delete $options{'max_wait'}
Aresult
11
00
5969 0 ▶ $timeout ||= $wait;
Condition0%0/3
$timeout ||= $wait
l!l&&r!l&&!r
000
MC/DC0%0/2
$timeout ||= $wait
$timeout $wait
Truth table0%0/3
A ||= B
A= $timeoutB= $wait
ABresult
1X1
011
000
5970  
5971 0 _default_limiter( 'maybe', \%options );
5972  
5973 0 my $timeout_after;
5974 0 ▶ if ($timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if ($timeout) 0 0 0
5975 0 $timeout_after = time + $timeout;
5976 };
5977 0 my $v;
5978 my $node;
5979 0 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
$v and !$timeout || time < $timeout_after and do { do { $node = $options{"dom"}; unless ($node) { $node = $self->_option_query(%options); } ; return unless $node; $self->sleep($sleep); $v = eval { do { $self->is_visible($node) } } } } 0 0 0
Condition0%0/6
$v and !$timeout || time < $timeout_after
!ll&&!rl&&r
000
not $timeout or time < $timeout_after
l!l&&r!l&&!r
000
MC/DC0%0/3
$v and !$timeout || time < $timeout_after
$v not $timeout time < $timeout_after
Truth table0%0/4
A and not(B) or C
A= $vB= not $timeoutC= time < $timeout_after
ABCresult
0XX0
1000
11X1
1011
5980 0 $node = $options{ dom };
5981 0 ▶ if (! $node) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($node) 0 0 0
5982 0 $node = $self->_option_query(%options);
5983 };
5984 return
5985 0 ▶ unless $node;
Branch: 1 branch
BranchTrueFalseTotal
unless $node 0 0 0
5986 0 $self->sleep( $sleep );
5987  
5988 # If $node goes away due to a page reload, ->is_visible could die:
5989 0 $v = eval { $self->is_visible($node) };
5990 } while ( $v
5991 and (!$timeout or time < $timeout_after ));
5992 0 ▶ if ($v and $timeout and time >= $timeout_after) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v and $timeout and time >= $timeout_after) 0 0 0
Condition0%0/6
$v and $timeout and time >= $timeout_after
!ll&&!rl&&r
000
$v and $timeout
!ll&&!rl&&r
000
MC/DC0%0/3
$v and $timeout and time >= $timeout_after
$v $timeout time >= $timeout_after
Truth table0%0/4
A and B and C
A= $vB= $timeoutC= time >= $timeout_after
ABCresult
0XX0
10X0
1100
1111
5993 0 ▶ if( $wait ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wait) { } 0 0 0
5994 return()
5995 0 } else {
5996 0 croak "Timeout of $timeout seconds reached while waiting for element to become invisible";
5997 };
5998 };
5999 0 return 1;
6000 };
6001  
6002 =head2 C<< $mech->wait_until_visible( %options ) >>
6003  
6004 $mech->wait_until_visible( selector => 'a.download' );
6005  
6006 Waits until an query returns a visible element.
6007  
6008 Takes the same options as L<< $mech->is_visible/->is_visible >>.
6009  
6010 In addition, the following options are accepted:
6011  
6012 =over 4
6013  
6014 =item *
6015  
6016 C<timeout> - the timeout after which the function will C<croak>. To catch
6017 the condition and handle it in your calling program, use an L<eval> block.
6018 A timeout of C<0> means to never time out.
6019  
6020 =item *
6021  
6022 C<sleep> - the interval in seconds used to L<sleep>. Subsecond
6023 intervals are possible.
6024  
6025 =back
6026  
6027 Note that when passing in a selector, that selector is requeried
6028 on every poll instance. So the following query will work as expected:
6029  
6030 xpath => '//*[contains(text(),"click here for download")]'
6031  
6032 =cut
6033  
6034 0 ▶sub wait_until_visible( $self, %options ) {
Subroutine wait_until_visible: not called CC=8 SCAR=42.8
Pod documented
6035 0 ▶ my $sleep = delete $options{ sleep } || 0.3;
Condition0%0/2
delete $options{'sleep'} || 0.3
l!l
00
MC/DC0%0/1
delete $options{'sleep'} || 0.3
delete $options{'sleep'}
Truth table0%0/2
A
A= delete $options{'sleep'}
Aresult
11
00
6036 0 ▶ my $timeout = delete $options{ timeout } || 0;
Condition0%0/2
delete $options{'timeout'} || 0
l!l
00
MC/DC0%0/1
delete $options{'timeout'} || 0
delete $options{'timeout'}
Truth table0%0/2
A
A= delete $options{'timeout'}
Aresult
11
00
6037  
6038 0 _default_limiter( 'any', \%options );
6039  
6040 0 my $timeout_after;
6041 0 ▶ if ($timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if ($timeout) 0 0 0
6042 0 $timeout_after = time + $timeout;
6043 };
6044 0 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
!$timeout_after || time < $timeout_after and do { do { my(@nodes) = grep({eval { do { $self->is_visible("dom", $_) } };} $self->_option_query(%options)); if (@nodes) { return @nodes; } ; $self->sleep($sleep) } } 0 0 0
Condition0%0/3
not $timeout_after or time < $timeout_after
l!l&&r!l&&!r
000
MC/DC0%0/2
not $timeout_after or time < $timeout_after
not $timeout_after time < $timeout_after
Truth table0%0/3
not(A) or B
A= not $timeout_afterB= time < $timeout_after
ABresult
1X1
011
000
6045 # If $node goes away due to a page reload, ->is_visible could die:
6046 my @nodes =
6047 0 grep { eval { $self->is_visible( dom => $_ ) } }
6048 $self->_option_query(%options);
6049  
6050 0 ▶ if( @nodes ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@nodes) 0 0 0
6051 return @nodes
6052 0 };
6053 0 $self->sleep( $sleep );
6054 } while (!$timeout_after or time < $timeout_after );
6055 0 ▶ if (time >= $timeout_after) {
Branch: 1 branch
BranchTrueFalseTotal
if (time >= $timeout_after) 0 0 0
6056 0 croak "Timeout of $timeout seconds reached while waiting for element to become invisible";
6057 };
6058 };
6059  
6060 =head1 CONTENT RENDERING METHODS
6061  
6062 =head2 C<< $mech->content_as_png() >>
6063  
6064 my $png_data = $mech->content_as_png();
6065  
6066 # Create scaled-down 480px wide preview
6067 my $png_data = $mech->content_as_png(undef, { width => 480 });
6068  
6069 Returns the given tab or the current page rendered as PNG image.
6070  
6071 All parameters are optional.
6072  
6073 =over 4
6074  
6075 =back
6076  
6077 This method is specific to WWW::Mechanize::Chrome.
6078  
6079 =cut
6080  
6081 0 ▶sub _as_raw_png( $self, $image ) {
Subroutine _as_raw_png: not called CC=1 SCAR=6.9
6082 0 my $data;
6083 0 $image->write( data => \$data, type => 'png' );
6084 0 $data
6085 }
6086  
6087 0 ▶sub _content_as_png($self, $rect={}, $target={} ) {
Subroutine _content_as_png: not called CC=7 SCAR=40.3
6088 0 ▶ if( !keys $rect->%* ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not keys %$rect) { } 0 0 0
6089 0 undef $rect;
6090 } else {
6091 0 ▶ $rect->{scale} //= 1;
Condition0%0/2
$rect->{"scale"} //= 1
l!l
00
MC/DC0%0/1
$rect->{"scale"} //= 1
$rect->{"scale"}
Truth table0%0/2
A
A= $rect->{"scale"}
Aresult
11
00
6092  
6093 0 ▶ $rect->{x} //= delete $rect->{left};
Condition0%0/3
$rect->{"x"} //= delete $rect->{"left"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$rect->{"x"} //= delete $rect->{"left"}
$rect->{"x"} delete $rect->{"left"}
Truth table0%0/3
A //= B
A= $rect->{"x"}B= delete $rect->{"left"}
ABresult
1X1
011
000
6094 0 ▶ $rect->{y} //= delete $rect->{top};
Condition0%0/3
$rect->{"y"} //= delete $rect->{"top"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$rect->{"y"} //= delete $rect->{"top"}
$rect->{"y"} delete $rect->{"top"}
Truth table0%0/3
A //= B
A= $rect->{"y"}B= delete $rect->{"top"}
ABresult
1X1
011
000
6095 };
6096 $self->target->send_message('Page.captureScreenshot',
6097 format => 'png',
6098 maybe clip => $rect,
6099 captureBeyondViewport => JSON::true
6100 0 ▶ )->then( sub( $res ) {
Subroutine __ANON__: not called CC=6 SCAR=37.4
6101 0 require Imager;
6102 0 my $img = Imager->new ( data => decode_base64( $res->{data} ), format => 'png' );
6103 # Cut out the wanted part
6104 0 ▶ if( scalar keys %$rect) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %$rect) 0 0 0
6105 0 $img = $img->crop( %$rect );
6106 };
6107 # Resize image to width/height
6108 0 ▶ if( scalar keys %$target) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %$target) 0 0 0
6109 0 my %args;
6110 $args{ ypixels } = $target->{ height }
6111 0 ▶ if $target->{height};
Branch: 1 branch
BranchTrueFalseTotal
if $target->{"height"} 0 0 0
6112 $args{ xpixels } = $target->{ width }
6113 0 ▶ if $target->{width};
Branch: 1 branch
BranchTrueFalseTotal
if $target->{"width"} 0 0 0
6114 0 ▶ $args{ scalefactor } = $target->{ scalex } || $target->{scaley};
Condition0%0/3
$target->{'scalex'} || $target->{'scaley'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$target->{'scalex'} || $target->{'scaley'}
$target->{'scalex'} $target->{'scaley'}
Truth table0%0/3
A || B
A= $target->{'scalex'}B= $target->{'scaley'}
ABresult
1X1
011
000
6115 0 $img = $img->scale( %args );
6116 };
6117 0 return Future->done( $img )
6118 0 });
6119 };
6120  
6121  
6122 0 ▶sub content_as_png($self, $rect={}, $target={}) {
Subroutine content_as_png: not called CC=3 SCAR=24.8
Pod documented
6123 0 my $img = $self->_content_as_png( $rect, $target )->get;
6124 0 return $self->_as_raw_png( $img );
6125 };
6126  
6127 0 ▶sub getResourceTree_future( $self ) {
Subroutine getResourceTree_future: not called CC=1 SCAR=6.9
Pod undocumented
6128 $self->target->send_message( 'Page.getResourceTree' )
6129 0 ▶ ->then( sub( $result ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
6130 Future->done( $result->{frameTree} )
6131 0 })
6132 0 }
6133  
6134 0 ▶sub getResourceContent_future( $self, $url_or_resource, $frameId=$self->frameId, %additional ) {
Subroutine getResourceContent_future: not called CC=4 SCAR=30.0
Pod undocumented
6135 0 ▶ my $url = ref $url_or_resource ? $url_or_resource->{url} : $url_or_resource;
Branch: 1 branch
BranchTrueFalseTotal
ref $url_or_resource ? : 0 0 0
6136 0 ▶ %additional = (%$url_or_resource,%additional) if ref $url_or_resource;
Branch: 1 branch
BranchTrueFalseTotal
if ref $url_or_resource 0 0 0
6137 $self->target->send_message( 'Page.getResourceContent', frameId => $frameId, url => $url )
6138 0 ▶ ->then( sub( $result ) {
Subroutine __ANON__: not called CC=2 SCAR=17.9
6139 0 ▶ if( delete $result->{base64Encoded}) {
Branch: 1 branch
BranchTrueFalseTotal
if (delete $result->{'base64Encoded'}) { } 0 0 0
6140 $result->{content} = decode_base64( $result->{content} )
6141 0 } else {
6142 0 $result->{_utf8} = 1;
6143 };
6144 0 %$result = (%additional, %$result);
6145 0 Future->done( $result )
6146 })
6147 0 }
6148  
6149 # Replace that later with MIME::Detect
6150 69 our %extensions = (
6151 'image/jpeg' => '.jpg',
6152 'image/png' => '.png',
6153 'image/gif' => '.gif',
6154 'text/html' => '.html',
6155 'text/plain' => '.txt',
6156 'text/stylesheet' => '.css',
6157 'text/javascript' => '.js',
6158 'application/javascript' => '.js',
6159 );
6160  
6161 0 ▶sub _saveResourceTree( $self, $tree, $names, $seen, $wanted, $save, $base_dir ) {
Subroutine _saveResourceTree: not called CC=10 SCAR=47.0
6162 0 my @requested;
6163 # Also fetch the frame itself?!
6164 # Or better reuse ->content?!
6165 # $tree->{frame}
6166 # build the map from URLs to file names
6167 # This should become a separate method
6168 # Also something like get_page_resources, that returns the linear
6169 # list of resources for all frames etc.
6170 my @wanted;
6171 0 for my $res ($tree->{frame}, @{ $tree->{resources}}) {
6172 0 ▶ if( $seen->{ $res->{url} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$seen{$res->{"url"}}) 0 0 0
6173 #warn "Skipping $res->{url} (already saved)";
6174 0 next;
6175 };
6176 0 ▶ if( !$wanted->($res) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&$wanted($res)) 0 0 0
6177 #warn "Don't want $res->{url}";
6178 0 next;
6179 };
6180 #warn "Do want $res->{url}";
6181  
6182 0 my $target;
6183 0 ▶ if( exists $names->{ $res->{url}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $$names{$res->{'url'}}) { } 0 0 0
6184 # User-specified names always take precedence
6185 0 $target = $names->{ $res->{url}};
6186 0 $names->{ $res->{url} } = $target;
6187  
6188 } else {
6189 # find a non-duplicate name
6190 0 $target = $self->filenameFromUrl( $res->{url}, $extensions{ $res->{mimeType} });
6191 0 my %filenames = reverse %$names;
6192  
6193 0 my $duplicates;
6194 0 my $old_target = $target;
6195 0 ▶ while( $filenames{ $target }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($filenames{$target}) 0 0 0
6196 0 $duplicates++;
6197 0 ( $target = $old_target )=~ s!\.(\w+)$!_$duplicates.$1!;
6198 };
6199 0 $names->{ $res->{url} } = File::Spec->catfile( $base_dir, $target );
6200 };
6201  
6202 0 push @wanted, $res;
6203 };
6204  
6205 # retrieve and save the resource content for each resource
6206 0 for my $res (@wanted) {
6207 0 my $fetch = $self->getResourceContent_future( $res );
6208 0 ▶ if( $save ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($save) 0 0 0
6209 #warn "Will save $res->{url}";
6210 0 ▶ $fetch = $fetch->then( $save )->else(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
6211 0 warn "Fetch failed:";
6212 0 warn "@_";
6213 0 });
6214 };
6215 0 push @requested, $fetch;
6216 };
6217  
6218 # recurse through the subframes
6219 0 ▶ if( my $t = $tree->{childFrames}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $t = $tree->{"childFrames"}) 0 0 0
6220 0 for my $child (@$t) {
6221 0 push @requested, $self->_saveResourceTree( $child, $names, $seen, $wanted, $save, $base_dir );
6222 };
6223 };
6224  
6225 0 ▶ return Future->wait_all( @requested )->catch(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
6226 0 warn $@;
6227 0 });
6228 }
6229  
6230 # Allow the options to specify whether to filter duplicates here
6231 0 ▶sub fetchResources_future( $self, %options ) {
Subroutine fetchResources_future: not called CC=6 SCAR=37.4
Pod undocumented
6232 0 ▶ $options{ save } ||= undef;
Condition0%0/2
$options{"save"} ||= undef
l!l
00
MC/DC0%0/1
$options{"save"} ||= undef
$options{"save"}
Truth table0%0/2
A
A= $options{"save"}
Aresult
11
00
6233 0 ▶ $options{ seen } ||= {};
Condition0%0/2
$options{"seen"} ||= {}
l!l
00
MC/DC0%0/1
$options{"seen"} ||= {}
$options{"seen"}
Truth table0%0/2
A
A= $options{"seen"}
Aresult
11
00
6234 0 ▶ $options{ names } ||= {};
Condition0%0/2
$options{"names"} ||= {}
l!l
00
MC/DC0%0/1
$options{"names"} ||= {}
$options{"names"}
Truth table0%0/2
A
A= $options{"names"}
Aresult
11
00
6235 0 ▶ $options{ target_dir } ||= '.';
Condition0%0/2
$options{"target_dir"} ||= "."
l!l
00
MC/DC0%0/1
$options{"target_dir"} ||= "."
$options{"target_dir"}
Truth table0%0/2
A
A= $options{"target_dir"}
Aresult
11
00
6236 0 ▶ $options{ wanted } ||= sub( $res ) { $res->{url} =~ /^(https?):/i };
Subroutine __ANON__: not called CC=1 SCAR=6.9
Condition0%0/3
$options{"wanted"} ||= sub ($res) { $res->{"url"} =~ /^(https?):/iu; }
l!l&&r!l&&!r
000
MC/DC0%0/2
$options{"wanted"} ||= sub ($res) { $res->{"url"} =~ /^(https?):/iu; }
$options{"wanted"} sub ($res) { $res->{"url"} =~ /^(https?):/iu; }
Truth table0%0/3
A ||= B
A= $options{"wanted"}B= sub ($res) { $res->{"url"} =~ /^(https?):/iu; }
ABresult
1X1
011
000
6237 0 my $seen = $options{ seen };
6238 0 my $names = $options{ names };
6239 0 my $wanted = $options{ wanted };
6240 0 my $save = $options{ save };
6241 0 my $base_dir = $options{ target_dir };
6242  
6243 0 my $s = $self;
6244 0 weaken $s;
6245  
6246 $self->getResourceTree_future
6247 0 ▶ ->then( sub( $tree ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
6248 0 $s->_saveResourceTree($tree, $names, $seen, $wanted, $save, $base_dir);
6249 0 ▶ })->catch(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
6250 0 warn @_;
6251 0 });
6252 }
6253  
6254 =head2 C<< $mech->saveResources_future >>
6255  
6256 my $file_map = $mech->saveResources_future(
6257 target_file => 'this_page.html',
6258 target_dir => 'this_page_files/',
6259 wanted => sub { $_[0]->{url} =~ m!^https?:!i },
6260 )->get();
6261  
6262 Rough prototype of "Save Complete Page" feature
6263  
6264 =cut
6265  
6266 0 ▶sub saveResources_future( $self, %options ) {
Subroutine saveResources_future: not called CC=5 SCAR=34.0
Pod documented
6267 my $target_file = $options{ target_file }
6268 0 ▶ or croak "Need filename to save as ('target_file')";
Branch: 1 branch
BranchTrueFalseTotal
my $target_file = $options{"target_file"} or croak("Need filename to save as ('target_file')") 0 0 0
6269 0 my $target_dir = $options{ target_dir };
6270 0 ▶ if( ! defined $target_dir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $target_dir) 0 0 0
6271 0 ($target_dir = $target_file) =~ s!\.\w+$! files!i;
6272 };
6273 0 ▶ if( not -e $target_dir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $target_dir) 0 0 0
6274 0 ▶ mkdir $target_dir
Branch: 1 branch
BranchTrueFalseTotal
mkdir $target_dir or croak("Couldn't create '${target_dir}': $!") 0 0 0
6275 or croak "Couldn't create '$target_dir': $!";
6276 }
6277  
6278 0 my %names = (
6279 $self->uri => $target_file,
6280 );
6281 0 my $s = $self;
6282 0 weaken $s;
6283 $self->fetchResources_future(
6284 names => \%names,
6285 seen => \my %seen,
6286 target_dir => $target_dir,
6287 maybe wanted => $options{ wanted },
6288 0 ▶ save => sub( $resource ) {
Subroutine __ANON__: not called CC=5 SCAR=34.0
6289 # For mime/html targets without a name, use the title?!
6290 # Rewrite all HTML, CSS links
6291  
6292 # We want to store the top HTML under the name passed in (!)
6293 0 ▶ $names{ $resource->{url} } ||= File::Spec->catfile( $target_dir, $names{ $resource->{url} });
Condition0%0/3
$names{$resource->{"url"}} ||= "File::Spec"->catfile($target_dir, $names{$resource->{"url"}})
l!l&&r!l&&!r
000
MC/DC0%0/2
$names{$resource->{"url"}} ||= "File::Spec"->catfile($target_dir, $names{$resource->{"url"}})
$names{$resource->{"url"}} "File::Spec"->catfile($target_dir, $names{$resource->{"url"}})
Truth table0%0/3
A ||= B
A= $names{$resource->{"url"}}B= "File::Spec"->catfile($target_dir, $names{$resource->{"url"}})
ABresult
1X1
011
000
6294 my $target = $names{ $resource->{url} }
6295 0 ▶ or die "Don't have a filename for URL '$resource->{url}' ?!";
Branch: 1 branch
BranchTrueFalseTotal
my $target = $names{$resource->{"url"}} or die qq[Don't have a filename for URL '$resource->{"url"}' ?!] 0 0 0
6296 0 $s->log( 'debug', "Saving '$resource->{url}' to '$target'" );
6297 0 ▶ open my $fh, '>', $target
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", $target or croak(qq[Couldn't save url '$resource->{"url"}' to ${target}: $!]) 0 0 0
6298 or croak "Couldn't save url '$resource->{url}' to $target: $!";
6299 0 ▶ if( $resource->{_utf8}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($resource->{'_utf8'}) { } 0 0 0
6300 0 binmode $fh, ':encoding(UTF-8)';
6301 } else {
6302 0 binmode $fh;
6303 };
6304  
6305 0 print $fh $resource->{content};
6306 0 CORE::close( $fh );
6307  
6308 0 Future->done( $resource );
6309 },
6310 0 ▶ )->then( sub( @resources ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
6311 0 Future->done( \%names );
6312 0 ▶ })->catch(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
6313 0 warn $@;
6314 0 });
6315 }
6316  
6317 0 ▶sub filenameFromUrl( $self, $url, $extension ) {
Subroutine filenameFromUrl: not called CC=1 SCAR=6.9
Pod undocumented
6318 0 my $target = URI->new( $url )->path;
6319  
6320 0 $target =~ s![\&\?\<\>\{\}\|\:\*]!_!g;
6321 0 $target =~ s!.*[/\\]!!;
6322  
6323 # Add/change extension here
6324  
6325 0 return $target
6326 }
6327  
6328 =head2 C<< $mech->viewport_size >>
6329  
6330 print Dumper $mech->viewport_size;
6331 $mech->viewport_size({ width => 1388, height => 792 });
6332  
6333 Returns (or sets) the new size of the viewport (the "window").
6334  
6335 The recognized keys are:
6336  
6337 width
6338 height
6339 deviceScaleFactor
6340 mobile
6341 screenWidth
6342 screenHeight
6343 positionX
6344 positionY
6345  
6346 =cut
6347  
6348 0 ▶sub viewport_size_future( $self, $new={} ) {
Subroutine viewport_size_future: not called CC=5 SCAR=34.0
Pod undocumented
6349 0 my $params = dclone $new;
6350 0 ▶ if( keys %$params) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %$params) { } 0 0 0
6351 0 my %reset = (
6352 mobile => JSON::false,
6353 width => 0,
6354 height => 0,
6355 deviceScaleFactor => 0,
6356 scale => 1,
6357 screenWidth => 0,
6358 screenHeight => 0,
6359 positionX => 0,
6360 positionY => 0,
6361 dontSetVisibleSize => JSON::false,
6362 screenOrientation => {
6363 type => 'landscapePrimary',
6364 angle => 0,
6365 },
6366 #viewport => {
6367 # 'x' => 0,
6368 # 'y' => 0,
6369 # width => 0,
6370 # height => 0,
6371 # scale => 1,
6372 #}
6373 );
6374 0 for my $field (qw( mobile width height deviceScaleFactor )) {
6375 0 ▶ if( ! exists $params->{ $field }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $params->{$field}) 0 0 0
6376 0 $params->{$field} = $reset{ $field };
6377 };
6378 };
6379 0 return $self->target->send_message('Emulation.setDeviceMetricsOverride', %$params );
6380 } else {
6381 0 return $self->target->send_message('Emulation.clearDeviceMetricsOverride' );
6382 };
6383 };
6384  
6385 0 ▶sub viewport_size( $self, $new={} ) {
Subroutine viewport_size: not called CC=2 SCAR=17.9
Pod documented
6386 0 $self->viewport_size_future($new)->get
6387 };
6388  
6389 =head2 C<< $mech->element_as_png( $element ) >>
6390  
6391 my $shiny = $mech->selector('#shiny', single => 1);
6392 my $i_want_this = $mech->element_as_png($shiny);
6393  
6394 Returns PNG image data for a single element
6395  
6396 =cut
6397  
6398 0 ▶sub element_as_png {
Subroutine element_as_png: not called CC=1 SCAR=6.9
Pod documented
6399 0 my ($self, $element) = @_;
6400  
6401 0 $self->render_element( element => $element, format => 'png' )
6402 };
6403  
6404 =head2 C<< $mech->render_element( %options ) >>
6405  
6406 my $shiny = $mech->selector('#shiny', single => 1);
6407 my $i_want_this= $mech->render_element(
6408 element => $shiny,
6409 format => 'png',
6410 );
6411  
6412 Returns the data for a single element
6413 or writes it to a file. It accepts
6414 all options of C<< ->render_content >>.
6415  
6416 Note that while the image will have the node in the upper left
6417 corner, the width and height of the resulting image will still
6418 be the size of the browser window. Cut the image using
6419 C<< element_coordinates >> if you need exactly the element.
6420  
6421 =cut
6422  
6423 0 ▶sub render_element {
Subroutine render_element: not called CC=3 SCAR=24.8
Pod documented
6424 0 my ($self, %options) = @_;
6425 my $element= delete $options{ element }
6426 0 ▶ or croak "No element given to render.";
Branch: 1 branch
BranchTrueFalseTotal
my $element = delete $options{"element"} or croak("No element given to render.") 0 0 0
6427  
6428 0 my $cliprect = $self->element_coordinates( $element );
6429 0 ▶ $cliprect->{scale} //= 1;
Condition0%0/2
$cliprect->{"scale"} //= 1
l!l
00
MC/DC0%0/1
$cliprect->{"scale"} //= 1
$cliprect->{"scale"}
Truth table0%0/2
A
A= $cliprect->{"scale"}
Aresult
11
00
6430 0 $cliprect->{ x } = delete $cliprect->{ left };
6431 0 $cliprect->{ y } = delete $cliprect->{ top };
6432  
6433 0 ▶ my $res = $self->_content_as_png($cliprect,)->then( sub( $img ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
6434 0 Future->done( $self->_as_raw_png( $img ));
6435 0 })->get;
6436  
6437 0 return $res
6438 };
6439  
6440 =head2 C<< $mech->element_coordinates( $element ) >>
6441  
6442 my $shiny = $mech->selector('#shiny', single => 1);
6443 my ($pos) = $mech->element_coordinates($shiny);
6444 print $pos->{left},',', $pos->{top};
6445  
6446 Returns the page-coordinates of the C<$element>
6447 in pixels as a hash with four entries, C<left>, C<top>, C<width> and C<height>.
6448  
6449 This function might get moved into another module more geared
6450 towards rendering HTML.
6451  
6452 =cut
6453  
6454 0 ▶sub element_coordinates {
Subroutine element_coordinates: not called CC=1 SCAR=6.9
Pod documented
6455 0 my ($self, $element) = @_;
6456 0 my $cliprect = $self->target->send_message('Runtime.callFunctionOn', objectId => $element->objectId, functionDeclaration => <<'JS', arguments => [], returnByValue => JSON::true)->get->{result}->{value};
6457 function() {
6458 var r = this.getBoundingClientRect();
6459 return {
6460 top : r.top
6461 , left: r.left
6462 , width: r.width
6463 , height: r.height
6464 }
6465 }
6466 JS
6467 };
6468  
6469 =head2 C<< $mech->render_content(%options) >>
6470  
6471 my $pdf_data = $mech->render_content( format => 'pdf' );
6472  
6473 Returns the current page rendered as PDF or PNG
6474 as a bytestring.
6475  
6476 Note that the PDF format will only be successful with headless Chrome. At least
6477 on Windows, when launching Chrome with a UI, printing to PDF will
6478 be unavailable.
6479  
6480 This method is specific to WWW::Mechanize::Chrome.
6481  
6482 =cut
6483  
6484 0 ▶sub render_content( $self, %options ) {
Subroutine render_content: not called CC=6 SCAR=37.4
Pod documented
6485 0 ▶ $options{ format } ||= 'png';
Condition0%0/2
$options{"format"} ||= "png"
l!l
00
MC/DC0%0/1
$options{"format"} ||= "png"
$options{"format"}
Truth table0%0/2
A
A= $options{"format"}
Aresult
11
00
6486  
6487 0 my $fmt = delete $options{ format };
6488 0 my $filename = delete $options{ filename };
6489  
6490 0 my $payload;
6491 0 ▶ if( $fmt eq 'png' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($fmt eq 'png') { } 0 0 0
elsif ($fmt eq 'pdf') { } 0 0 0
6492 0 $payload = $self->content_as_png( %options )
6493 } elsif( $fmt eq 'pdf' ) {
6494 0 $payload = $self->content_as_pdf( %options );
6495 };
6496  
6497 0 ▶ if( defined $filename ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $filename) 0 0 0
6498 0 ▶ open my $fh, '>:raw', $filename
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $filename or croak("Couldn't create '${filename}': $!") 0 0 0
6499 or croak "Couldn't create '$filename': $!";
6500 0 print {$fh} $payload;
6501 };
6502  
6503 0 $payload
6504 }
6505  
6506 =head2 C<< $mech->content_as_pdf(%options) >>
6507  
6508 my $pdf_data = $mech->content_as_pdf();
6509  
6510 my $pdf_data = $mech->content_as_pdf( format => 'A4' );
6511  
6512 my $pdf_data = $mech->content_as_pdf( paperWidth => 8, paperHeight => 11 );
6513  
6514 Returns the current page rendered in PDF format as a bytestring. The page format
6515 can be specified through the C<format> option.
6516  
6517 Note that this method will only be successful with headless Chrome. At least on
6518 Windows, when launching Chrome with a UI, printing to PDF will be unavailable.
6519 See the C<html-to-pdf.pl> script in the C<examples/> directory of this distribution.
6520  
6521 This method is specific to WWW::Mechanize::Chrome.
6522  
6523 =cut
6524  
6525 69 our %PaperFormats = (
6526 letter => {width => 8.5, height => 11 },
6527 legal => {width => 8.5, height => 14 },
6528 tabloid => {width => 11, height => 17 },
6529 ledger => {width => 17, height => 11 },
6530 a0 => {width => 33.1, height => 46.8 },
6531 a1 => {width => 23.4, height => 33.1 },
6532 a2 => {width => 16.5, height => 23.4 },
6533 a3 => {width => 11.7, height => 16.5 },
6534 a4 => {width => 8.27, height => 11.7 },
6535 a5 => {width => 5.83, height => 8.27 },
6536 a6 => {width => 4.13, height => 5.83 },
6537 );
6538  
6539 0 ▶sub content_as_pdf($self, %options) {
Subroutine content_as_pdf: not called CC=5 SCAR=34.0
Pod documented
6540 0 ▶ if( my $format = delete $options{ format }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $format = delete $options{"format"}) 0 0 0
6541 0 ▶ my $wh = $PaperFormats{ lc $format }
Branch: 1 branch
BranchTrueFalseTotal
my $wh = $WWW::Mechanize::Chrome::PaperFormats{lc $format} or croak("Unknown paper format '${format}'") 0 0 0
6542 or croak "Unknown paper format '$format'";
6543 0 @options{'paperWidth','paperHeight'} = @{$wh}{'width','height'};
6544 };
6545  
6546 0 my $base64 = $self->target->send_message('Page.printToPDF', %options)->get->{data};
6547 0 my $payload = decode_base64( $base64 );
6548 0 ▶ if( my $filename = delete $options{ filename } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $filename = delete $options{"filename"}) 0 0 0
6549 0 ▶ open my $fh, '>:raw', $filename
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $filename or croak("Couldn't create '${filename}': $!") 0 0 0
6550 or croak "Couldn't create '$filename': $!";
6551 0 print {$fh} $payload;
6552 };
6553 0 return $payload;
6554 };
6555  
6556 =head1 INTERNAL METHODS
6557  
6558 These are methods that are available but exist mostly as internal
6559 helper methods. Use of these is discouraged.
6560  
6561 =head2 C<< $mech->element_query( \@elements, \%attributes ) >>
6562  
6563 my $query = $mech->element_query(['input', 'select', 'textarea'],
6564 { name => 'foo' });
6565  
6566 Returns the XPath query that searches for all elements with C<tagName>s
6567 in C<@elements> having the attributes C<%attributes>. The C<@elements>
6568 will form an C<or> condition, while the attributes will form an C<and>
6569 condition.
6570  
6571 =cut
6572  
6573 0 ▶sub element_query {
Subroutine element_query: not called CC=1 SCAR=6.9
Pod documented
6574 0 my ($self, $elements, $attributes) = @_;
6575 my $query =
6576 './/*[(' .
6577 join( ' or ',
6578 map {
6579 0 sprintf qq{local-name(.)="%s"}, lc $_
6580 } @$elements
6581 )
6582 . ') and '
6583 . join( " and ",
6584 0 map { sprintf q{@%s="%s"}, $_, $attributes->{$_} }
6585 sort keys(%$attributes)
6586 )
6587 . ']';
6588 };
6589  
6590 sub post_process
6591 0 ▶{
Subroutine post_process: not called CC=3 SCAR=24.8
Pod undocumented
6592 0 my $self = shift;
6593 0 ▶ if ( $self->{report_js_errors} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"report_js_errors"}) 0 0 0
6594 0 ▶ if ( my @errors = $self->js_errors ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@errors) = $self->js_errors) 0 0 0
6595 0 $self->report_js_errors(@errors);
6596 0 $self->clear_js_errors;
6597 }
6598 }
6599 }
6600  
6601 sub report_js_errors
6602 0 ▶{
Subroutine report_js_errors: not called CC=5 SCAR=34.0
Pod documented
6603 0 my ( $self, @errors ) = @_;
6604 @errors = map {
6605 0 $_->{message} .
6606 0 ▶ ( @{$_->{trace}} ? " at $_->{trace}->[-1]->{file} line $_->{trace}->[-1]->{line}" : '') .
Branch: 1 branch
BranchTrueFalseTotal
@{$_->{'trace'};} && $_->{'trace'}[-1]{'function'} ? : 0 0 0
Condition0%0/3
@{$_->{"trace"};} and $_->{"trace"}[-1]{"function"}
!ll&&!rl&&r
000
MC/DC0%0/2
@{$_->{"trace"};} and $_->{"trace"}[-1]{"function"}
@{$_->{"trace"};} $_->{"trace"}[-1]{"function"}
Truth table0%0/3
A and B
A= @{$_->{"trace"};}B= $_->{"trace"}[-1]{"function"}
ABresult
0X0
100
111
6607 0 ▶ ( @{$_->{trace}} && $_->{trace}->[-1]->{function} ? " in function $_->{trace}->[-1]->{function}" : '')
Branch: 1 branch
BranchTrueFalseTotal
@{$_->{'trace'};} ? : 0 0 0
6608 } @errors;
6609 0 ▶ Carp::carp("javascript error: @errors") if @errors;
Branch: 1 branch
BranchTrueFalseTotal
if @errors 0 0 0
6610 }
6611  
6612 =head1 DEBUGGING METHODS
6613  
6614 This module can collect the screencasts that Chrome can produce. The screencasts
6615 are sent to your callback which either feeds them to C<ffmpeg> to create a video
6616 out of them or dumps them to disk as sequential images.
6617  
6618 sub saveFrame {
6619 my( $mech, $framePNG ) = @_;
6620 print $framePNG->{data};
6621  
6622 }
6623  
6624 $mech->setScreenFrameCallback( \&saveFrame );
6625 ... do stuff ...
6626 $mech->setScreenFrameCallback( undef ); # stop recording
6627  
6628 If you want a premade screencast receiver for debugging headless Chrome
6629 sessions, see L<Mojolicious::Plugin::PNGCast>.
6630  
6631 =cut
6632  
6633 0 ▶sub _handleScreencastFrame( $self, $frame ) {
Subroutine _handleScreencastFrame: not called CC=1 SCAR=6.9
6634 # Meh, this one doesn't get a response I guess. So, not ->send_message, just
6635 # send a JSON packet to acknowledge the frame
6636 0 my $s = $self;
6637 0 weaken $s;
6638 $self->target->send_message(
6639 'Page.screencastFrameAck',
6640 0 ▶ sessionId => 0+$frame->{params}->{sessionId} )->then(sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
6641 0 $s->log('trace', 'Screencast frame acknowledged');
6642 0 $frame->{params}->{data} = decode_base64( $frame->{params}->{data} );
6643 0 ▶ if( my $cb = $s->{ screenFrameCallback }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cb = $s->{"screenFrameCallback"}) 0 0 0
6644 0 $cb->( $s, $frame->{params} );
6645 }
6646 0 Future->done();
6647 0 })->retain;
6648 }
6649  
6650 0 ▶sub setScreenFrameCallback( $self, $callback=undef, %options ) {
Subroutine setScreenFrameCallback: not called CC=5 SCAR=34.0
Pod undocumented
6651 0 $self->{ screenFrameCallback } = $callback;
6652  
6653 0 ▶ $options{ format } ||= 'png';
Condition0%0/2
$options{"format"} ||= "png"
l!l
00
MC/DC0%0/1
$options{"format"} ||= "png"
$options{"format"}
Truth table0%0/2
A
A= $options{"format"}
Aresult
11
00
6654 0 ▶ $options{ everyNthFrame } ||= 1;
Condition0%0/2
$options{"everyNthFrame"} ||= 1
l!l
00
MC/DC0%0/1
$options{"everyNthFrame"} ||= 1
$options{"everyNthFrame"}
Truth table0%0/2
A
A= $options{"everyNthFrame"}
Aresult
11
00
6655  
6656 0 my $action;
6657 0 my $s = $self;
6658 0 weaken $s;
6659 0 ▶ if( $callback ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($callback) { } 0 0 0
6660 0 ▶ $self->{ screenFrameCallbackCollector } = sub( $frame ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
6661 0 $s->_handleScreencastFrame( $frame );
6662 0 };
6663 $self->{ screenCastFrameListener } =
6664 0 $self->add_listener('Page.screencastFrame', $self->{ screenFrameCallbackCollector });
6665 $action = $s->target->send_message(
6666 'Page.startScreencast',
6667 format => $options{ format },
6668 everyNthFrame => 0+$options{ everyNthFrame }
6669 0 );
6670 } else {
6671 0 ▶ $action = $self->target->send_message('Page.stopScreencast')->then( sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
6672 # well, actually, we should only reset this after we're sure that
6673 # the last frame has been processed. Maybe we should send ourselves
6674 # a fake event for that, or maybe Chrome tells us
6675 0 delete $s->{ screenCastFrameListener };
6676 0 Future->done(1);
6677 0 });
6678 }
6679 0 $action->get
6680 }
6681  
6682 =head2 C<< $mech->sleep >>
6683  
6684 $mech->sleep( 2 ); # wait for things to settle down
6685  
6686 Suspends the progress of the program while still handling messages from
6687 Chrome.
6688  
6689 The main use of this method is to give Chrome enough time to send all its
6690 screencast frames and to catch up before shutting down the connection.
6691  
6692 =cut
6693  
6694 0 ▶sub sleep_future( $self, $seconds ) {
Subroutine sleep_future: not called CC=1 SCAR=6.9
Pod undocumented
6695 0 $self->target->sleep( $seconds );
6696 }
6697  
6698 0 ▶sub sleep( $self, $seconds ) {
Subroutine sleep: not called CC=1 SCAR=6.9
Pod documented
6699 0 $self->sleep_future( $seconds )->get;
6700 }
6701  
6702 69 1;
6703  
6704 =head1 INCOMPATIBILITIES WITH WWW::Mechanize
6705  
6706 As this module is in a very early stage of development,
6707 there are many incompatibilities. The main thing is
6708 that only the most needed WWW::Mechanize methods
6709 have been implemented by me so far.
6710  
6711 =head2 Unsupported Methods
6712  
6713 At least the following methods are unsupported:
6714  
6715 =over 4
6716  
6717 =item *
6718  
6719 C<< ->find_all_inputs >>
6720  
6721 This function is likely best implemented through C<< $mech->selector >>.
6722  
6723 =item *
6724  
6725 C<< ->find_all_submits >>
6726  
6727 This function is likely best implemented through C<< $mech->selector >>.
6728  
6729 =item *
6730  
6731 C<< ->images >>
6732  
6733 This function is likely best implemented through C<< $mech->selector >>.
6734  
6735 =item *
6736  
6737 C<< ->find_image >>
6738  
6739 This function is likely best implemented through C<< $mech->selector >>.
6740  
6741 =item *
6742  
6743 C<< ->find_all_images >>
6744  
6745 This function is likely best implemented through C<< $mech->selector >>.
6746  
6747 =back
6748  
6749 =head2 Functions that will likely never be implemented
6750  
6751 These functions are unlikely to be implemented because
6752 they make little sense in the context of Chrome.
6753  
6754 =over 4
6755  
6756 =item *
6757  
6758 C<< ->clone >>
6759  
6760 =item *
6761  
6762 C<< ->credentials( $username, $password ) >>
6763  
6764 =item *
6765  
6766 C<< ->get_basic_credentials( $realm, $uri, $isproxy ) >>
6767  
6768 =item *
6769  
6770 C<< ->clear_credentials() >>
6771  
6772 =item *
6773  
6774 C<< ->put >>
6775  
6776 I have no use for it
6777  
6778 =item *
6779  
6780 C<< ->post >>
6781  
6782 This module does not yet support POST requests
6783  
6784 =back
6785  
6786 =head1 INSTALLING
6787  
6788 See L<WWW::Mechanize::Chrome::Install>
6789  
6790 =head1 SEE ALSO
6791  
6792 =over 4
6793  
6794 =item *
6795  
6796 L<https://chromedevtools.github.io/devtools-protocol/> - the Chrome DevTools Protocol
6797  
6798 =item *
6799  
6800 L<https://developer.chrome.com/devtools/docs/debugging-clients> - the Chrome
6801 DevTools homepage
6802  
6803 =item *
6804  
6805 L<https://github.com/GoogleChrome/lighthouse> - Google Lighthouse, the main
6806 client of the Chrome API
6807  
6808 =item *
6809  
6810 L<WWW::Mechanize> - the module whose API grandfathered this module
6811  
6812 =item *
6813  
6814 L<WWW::Mechanize::Chrome::Node> - objects representing HTML in Chrome
6815  
6816 =item *
6817  
6818 L<WWW::Mechanize::Firefox> - a similar module with a visible application
6819 automating Firefox , currently on hiatus, since Mozilla does not yet
6820 implement the Chrome DevTools Protocol properly
6821  
6822 =item *
6823  
6824 L<WWW::Mechanize::PhantomJS> - a similar module without a visible application
6825 automating PhantomJS , now discontinued since PhantomJS is discontinued
6826  
6827 =back
6828  
6829 =head1 MASQUERADING AS OTHER BROWSERS
6830  
6831 Some articles about what you need to change to appear as a different
6832 browser
6833  
6834 L<https://multilogin.com/why-mimicking-a-device-is-almost-impossible/>
6835  
6836 L<https://github.com/berstend/puppeteer-extra/tree/master/packages/puppeteer-extra-plugin-stealth>
6837  
6838 L<https://rebrowser.net/blog/how-to-access-main-context-objects-from-isolated-context-in-puppeteer-and-playwright>
6839  
6840 =head1 REPOSITORY
6841  
6842 The public repository of this module is
6843 L<https://github.com/Corion/www-mechanize-chrome>.
6844  
6845 =head1 SUPPORT
6846  
6847 The public support forum of this module is L<https://perlmonks.org/>.
6848  
6849 =head1 TALKS
6850  
6851 I've given a German talk at GPW 2017, see L<http://act.yapc.eu/gpw2017/talk/7027>
6852 and L<https://corion.net/talks> for the slides.
6853  
6854 At The Perl Conference 2017 in Amsterdam, I also presented a talk, see
6855 L<http://act.perlconference.org/tpc-2017-amsterdam/talk/7022>.
6856 The slides for the English presentation at TPCiA 2017 are at
6857 L<https://corion.net/talks/WWW-Mechanize-Chrome/www-mechanize-chrome.en.html>.
6858  
6859 At the London Perl Workshop 2017 in London, I also presented a talk, see
6860 L<Youtube|https://www.youtube.com/watch?v=V3WeO-iVkAc> . The slides for
6861 that talk are
6862 L<here|https://corion.net/talks/WWW-Mechanize-Chrome/www-mechanize-chrome.en.html>.
6863  
6864 =head1 BUG TRACKER
6865  
6866 Please report bugs in this module via the Github bug queue at
6867 L<https://github.com/Corion/WWW-Mechanize-Chrome/issues>
6868  
6869 =head1 CONTRIBUTING
6870  
6871 Please see L<WWW::Mechanize::Chrome::Contributing>.
6872  
6873 =head1 KNOWN ISSUES
6874  
6875 Please see L<WWW::Mechanize::Chrome::Troubleshooting>.
6876  
6877 =head1 AUTHOR
6878  
6879 Max Maischein C<corion@cpan.org>
6880  
6881 =head1 CONTRIBUTORS
6882  
6883 Andreas König C<andk@cpan.org>
6884  
6885 Tobias Leich C<froggs@cpan.org>
6886  
6887 Steven Dondley C<s@dondley.org>
6888  
6889 Joshua Pollack
6890  
6891 =head1 COPYRIGHT (c)
6892  
6893 Copyright 2010-2026 by Max Maischein C<corion@cpan.org>.
6894  
6895 =head1 LICENSE
6896  
6897 This module is released under the same terms as Perl itself.
6898  
6899 =cut
↑ Summary Chrome/DevToolsProtocol/Target.pm »