WWW/Mechanize/Chrome.pm

filter: Statementstmt 11.5% 231 / 1997 Branchbran 4.6% 41 / 876 Conditioncond 3.5% 23 / 642 MC/DCmcdc 0.2% 1 / 363 Subroutinesub 17.3% 54 / 312 Podpod 64.2% 104 / 162 totaltotal 10.4% 454 / 4352 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.79';
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 sub build_command_line {
451 4 ▶ my( $class, $options )= @_;
Subroutine build_command_line: called CC=51 SCAR=78.1
Pod undocumented
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 ▶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 1170 for my $p (@without_path) {
729 3492 my $this = File::Spec->catfile( $path, $p );
730 3492 ▶ if( -x $this ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-x $this) 0 3492 3492
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 ▶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 ▶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 ▶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 ▶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 ▶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 ▶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 ▶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 ▶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" 3 1 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 ▶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 $@ 0 1 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 ▶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 error_handler => sub {
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');
Subroutine __ANON__: not called CC=1 SCAR=6.9
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 {
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 )->then(sub {
1111 0 ▶ return Future->done( $self )
Subroutine __ANON__: not called CC=1 SCAR=6.9
1112 0 });
1113  
1114 0 return $res
1115 };
1116  
1117 ▶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 ▶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 ▶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 ▶ )->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 69 ▶ 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 ▶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 )
Subroutine __ANON__: not called CC=1 SCAR=6.9
1204 ->catch( sub(@args) {
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 my $res = $setup->then(sub {
1226 ▶ my $collect_JS_problems = sub( $msg ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1227 $s->_handleConsoleAPICall( $msg->{params} )
1228 0 ▶ };
Subroutine __ANON__: not called CC=3 SCAR=24.8
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 )->on_done(sub {
1260  
1261 # ->get() doesn't have ->get_future() yet
1262 0 ▶ if( ! (exists $options{ tab } )) {
Subroutine __ANON__: not called CC=4 SCAR=30.0
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 $s->{_fresh_document} = $s->add_listener('DOM.documentUpdated', sub {
1270 0 ▶ $s->{_currentNodeGeneration}++;
Subroutine __ANON__: not called CC=1 SCAR=6.9
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 ▶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 ▶sub frameId( $self ) {
Subroutine frameId: not called CC=1 SCAR=6.9
Pod undocumented
1294 $self->{frameId}
1295 0 }
1296  
1297 ▶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 ▶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 ▶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 {
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 sub driver {
1420 0 ▶ $_[0]->target
Subroutine driver: not called CC=1 SCAR=6.9
Pod documented
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 sub target {
1433 $_[0]->{target}
1434 1 ▶};
Subroutine target: called CC=1 SCAR=0.0
Pod documented
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 sub transport {
1446 0 ▶ $_[0]->driver->transport
Subroutine transport: not called CC=1 SCAR=6.9
Pod documented
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 ▶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 ▶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 ▶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 ▶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 ▶ 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 ▶ $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 $res = $setup->then(sub {
1561 0 ▶ $s->target->send_message('Target.setDiscoverTargets' => discover => JSON::true() )
Subroutine __ANON__: not called CC=1 SCAR=6.9
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 sub autodie {
1572 0 ▶ my( $self, $val )= @_;
Subroutine autodie: not called CC=2 SCAR=17.9
Pod documented
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 sub allow {
1587 0 ▶ my($self,%options)= @_;
Subroutine allow: not called CC=3 SCAR=24.8
Pod documented
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 ▶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 ▶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 ▶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 ▶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 ▶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 ▶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 ▶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 ▶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 ▶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 ▶ $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 ▶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)
Subroutine __ANON__: not called CC=1 SCAR=6.9
1769 ->then(sub( $res ) {
1770 0 return Future->done( @{ $res->{result}} )
1771 })
1772 0 }
1773  
1774 ▶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 ▶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 ▶ $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 ▶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 sub js_errors {
1854 0 ▶ my ($self) = @_;
Subroutine js_errors: not called CC=2 SCAR=17.9
Pod documented
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 sub clear_js_errors {
1867 0 ▶ my ($self) = @_;
Subroutine clear_js_errors: not called CC=1 SCAR=6.9
Pod documented
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 ▶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 ▶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 sub eval_in_chrome {
1962 0 ▶ my ($self, $code, @args) = @_;
Subroutine eval_in_chrome: not called CC=1 SCAR=6.9
Pod documented
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 ▶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',
Subroutine __ANON__: not called CC=1 SCAR=6.9
2000 returnByValue => JSON::false
2001 )->then(sub($result) {
2002 0 return Future->done( $result->{result}->{objectId});
2003 0 });
2004 } else {
2005 0 $objId = Future->done( $options{ objectId });
2006 };
2007  
2008 ▶ $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 ▶ })->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 sub callFunctionOn {
2036 0 ▶ my ($self,$str, %options) = @_;
Subroutine callFunctionOn: not called CC=1 SCAR=6.9
Pod documented
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 ▶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 ▶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 ▶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 sub close {
2083 1 ▶ my $pids = delete $_[0]->{pid};
Subroutine close: called CC=10 SCAR=37.6
Pod documented
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 ▶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 sub DESTROY {
2181 1 ▶ $_[0]->close();
Subroutine DESTROY: called CC=1 SCAR=0.0
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 ▶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 ▶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 ▶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 ▶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 ▶ $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 ▶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 ▶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 ▶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 ▶ 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 ▶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
Subroutine __ANON__: not called CC=8 SCAR=42.8
2422 ->then(sub( $ev ) {
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 ->then( sub {
2489 0 ▶ $nav = $_[0];
Subroutine __ANON__: not called CC=1 SCAR=6.9
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 })->then( sub {
2495 0 ▶ my $f;
Subroutine __ANON__: not called CC=3 SCAR=24.8
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 $f = $does_navigation->then( sub {
2499 0 ▶ @events = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
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 ▶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 my $events = $self->_mightNavigate( sub {
2532 0 ▶ $s->log('debug', "Navigating to [$url]");
Subroutine __ANON__: not called CC=1 SCAR=6.9
2533 0 $s->target->send_message(
2534 'Page.navigate',
2535 url => "$url"
2536 )
2537 }, url => "$url", %options, navigates => 1 )
2538 ->then( sub {
2539 0 ▶ $s->invalidate_cached_values;
Subroutine __ANON__: not called CC=1 SCAR=6.9
2540 0 Future->done( $s->response )
2541 })
2542 0 };
2543  
2544 ▶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 ▶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 ▶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 ▶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 ▶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 ->then(sub {
2627 0 ▶ $s->log('trace', "Have POST body", @_);
Subroutine __ANON__: not called CC=1 SCAR=6.9
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 ▶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 ▶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 ->then(sub {
2652 0 ▶ $s->log('debug', "Have body", @_);
Subroutine __ANON__: not called CC=2 SCAR=17.9
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 ▶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 ▶ $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 ▶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 ▶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 ▶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 sub post {
2919 0 ▶ my ($self, $url, %options) = @_;
Subroutine post: not called CC=2 SCAR=17.9
Pod documented
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 ▶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 $self->_mightNavigate( sub {
2990 0 ▶ $self->target->send_message('Page.reload', %options )
Subroutine __ANON__: not called CC=1 SCAR=6.9
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 ▶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 {
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.
3060  
3061 Note that currently, we only support one value per header.
3062  
3063 Chrome since version 63+ does not allow setting and sending the C<Referer>
3064 header anymore. The bug report is
3065 at L<https://bugs.chromium.org/p/chromium/issues/detail?id=849972>.
3066  
3067 =cut
3068  
3069 ▶sub _set_extra_headers_future( $self, %headers ) {
Subroutine _set_extra_headers_future: not called CC=2 SCAR=17.9
3070 0 $self->log('debug',"Setting additional headers", \%headers);
3071 # force-stringify all header values
3072 0 for (values %headers) { $_ = "$_" };
3073 0 $self->target->send_message('Network.setExtraHTTPHeaders',
3074 headers => \%headers
3075 );
3076 };
3077  
3078 ▶sub _set_extra_headers( $self, %headers ) {
Subroutine _set_extra_headers: not called CC=1 SCAR=6.9
3079 0 $self->_set_extra_headers_future(
3080 %headers
3081 )->get;
3082 };
3083  
3084 ▶sub add_header( $self, %headers ) {
Subroutine add_header: not called CC=1 SCAR=6.9
Pod documented
3085 $self->{ extra_headers } = {
3086 0 %{ $self->{ extra_headers } },
3087 %headers,
3088 };
3089 0 $self->_set_extra_headers( %{ $self->{ extra_headers } } );
3090 };
3091  
3092 =head2 C<< $mech->delete_header( $name , $name2... ) >>
3093  
3094 $mech->delete_header( 'User-Agent' );
3095  
3096 Removes HTTP headers from the agent's list of special headers. Note
3097 that Chrome may still send a header with its default value.
3098  
3099 =cut
3100  
3101 ▶sub delete_header( $self, @headers ) {
Subroutine delete_header: not called CC=1 SCAR=6.9
Pod documented
3102 0 delete @{ $self->{ extra_headers } }{ @headers };
3103 0 $self->_set_extra_headers( %{ $self->{ extra_headers } } );
3104 };
3105  
3106 =head2 C<< $mech->reset_headers >>
3107  
3108 $mech->reset_headers();
3109  
3110 Removes all custom headers and makes Chrome send its defaults again.
3111  
3112 =cut
3113  
3114 ▶sub reset_headers( $self ) {
Subroutine reset_headers: not called CC=1 SCAR=6.9
Pod documented
3115 0 $self->{ extra_headers } = {};
3116 0 $self->_set_extra_headers();
3117 };
3118  
3119 =head2 C<< $mech->block_urls() >>
3120  
3121 $mech->block_urls( '//facebook.com/js/conversions/tracking.js' );
3122  
3123 Sets the list of blocked URLs. These URLs will not be retrieved by Chrome
3124 when loading a page. This is useful to eliminate tracking images or to test
3125 resilience in face of bad network conditions.
3126  
3127 =cut
3128  
3129 ▶sub block_urls( $self, @urls ) {
Subroutine block_urls: not called CC=1 SCAR=6.9
Pod documented
3130 0 $self->target->send_message( 'Network.setBlockedURLs',
3131 urls => \@urls
3132 )->get;
3133 }
3134  
3135 =head2 C<< $mech->res() >> / C<< $mech->response(%options) >>
3136  
3137 my $response = $mech->response(headers => 0);
3138  
3139 Returns the current response as a L<HTTP::Response> object.
3140  
3141 =cut
3142  
3143 ▶sub response( $self ) {
Subroutine response: not called CC=1 SCAR=6.9
Pod documented
3144 $self->{response}
3145 0 };
3146  
3147 {
3148 69 ▶ no warnings 'once';
Subroutine BEGIN: called CC=1 SCAR=0.0
3149 69 *res = \&response;
3150 }
3151  
3152 # Call croak or log it, depending on the C< autodie > setting
3153 sub signal_condition {
3154 0 ▶ my ($self,$msg) = @_;
Subroutine signal_condition: not called CC=2 SCAR=17.9
Pod undocumented
3155 0 ▶ if ($self->{autodie}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'autodie'}) { } 0 0 0
3156 0 croak $msg
3157 } else {
3158 0 $self->log( 'warn', $msg );
3159 }
3160 };
3161  
3162 # Call croak on the C< autodie > setting if we have a non-200 status
3163 sub signal_http_status {
3164 0 ▶ my ($self) = @_;
Subroutine signal_http_status: not called CC=6 SCAR=37.4
Pod undocumented
3165 0 ▶ if ($self->{autodie}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'autodie'}) { } 0 0 0
3166 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
3167 # there was an error
3168 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
3169 };
3170 } else {
3171 # silent
3172 }
3173 };
3174  
3175 =head2 C<< $mech->success() >>
3176  
3177 $mech->get('https://google.com');
3178 print "Yay"
3179 if $mech->success();
3180  
3181 Returns a boolean telling whether the last request was successful.
3182 If there hasn't been an operation yet, returns false.
3183  
3184 This is a convenience function that wraps C<< $mech->res->is_success >>.
3185  
3186 =cut
3187  
3188 sub success {
3189 0 ▶ my $res = $_[0]->response();
Subroutine success: not called CC=2 SCAR=17.9
Pod documented
3190 0 ▶ $res and $res->is_success
Branch: 1 branch
BranchTrueFalseTotal
$res and $res->is_success 0 0 0
3191 }
3192  
3193 =head2 C<< $mech->status() >>
3194  
3195 $mech->get('https://google.com');
3196 print $mech->status();
3197 # 200
3198  
3199 Returns the HTTP status code of the response.
3200 This is a 3-digit number like 200 for OK, 404 for not found, and so on.
3201  
3202 =cut
3203  
3204 sub status {
3205 0 ▶ my ($self) = @_;
Subroutine status: not called CC=1 SCAR=6.9
Pod documented
3206 0 return $self->response()->code
3207 };
3208  
3209 =head2 C<< $mech->back() >>
3210  
3211 $mech->back();
3212  
3213 Goes one page back in the page history.
3214  
3215 Returns the (new) response.
3216  
3217 =cut
3218  
3219 ▶sub back( $self, %options ) {
Subroutine back: not called CC=1 SCAR=6.9
Pod documented
3220 $self->_mightNavigate( sub {
3221 ▶ $self->target->send_message('Page.getNavigationHistory')->then(sub($history) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3222 0 my $entry = $history->{entries}->[ $history->{currentIndex}-1 ];
3223 $self->target->send_message('Page.navigateToHistoryEntry', entryId => $entry->{id})
3224 0 ▶ });
Subroutine __ANON__: not called CC=1 SCAR=6.9
3225 0 }, navigates => 1, %options)
3226 ->get;
3227 };
3228  
3229 =head2 C<< $mech->forward() >>
3230  
3231 $mech->forward();
3232  
3233 Goes one page forward in the page history.
3234  
3235 Returns the (new) response.
3236  
3237 =cut
3238  
3239 ▶sub forward( $self, %options ) {
Subroutine forward: not called CC=1 SCAR=6.9
Pod documented
3240 $self->_mightNavigate( sub {
3241 ▶ $self->target->send_message('Page.getNavigationHistory')->then(sub($history) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3242 0 my $entry = $history->{entries}->[ $history->{currentIndex}+1 ];
3243 $self->target->send_message('Page.navigateToHistoryEntry', entryId => $entry->{id})
3244 0 ▶ });
Subroutine __ANON__: not called CC=1 SCAR=6.9
3245 0 }, navigates => 1, %options)
3246 ->get;
3247 }
3248  
3249 =head2 C<< $mech->stop() >>
3250  
3251 $mech->stop();
3252  
3253 Stops all loading in Chrome, as if you pressed C<ESC>.
3254  
3255 This function is mostly of use in callbacks or in a timer callback from your
3256 event loop.
3257  
3258 =cut
3259  
3260 ▶sub stop( $self ) {
Subroutine stop: not called CC=1 SCAR=6.9
Pod documented
3261 0 $self->target->send_message('Page.stopLoading')->get;
3262 }
3263  
3264 =head2 C<< $mech->uri() >>
3265  
3266 =head2 C<< $mech->uri_future() >>
3267  
3268 print "We are at " . $mech->uri;
3269 print "We are at " . $mech->uri_future->get;
3270  
3271 Returns the current document URI.
3272  
3273 =cut
3274  
3275 ▶sub uri_future( $self ) {
Subroutine uri_future: not called CC=1 SCAR=6.9
Pod documented
3276 ▶ $self->_cached_document->then(sub ($d) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3277 0 return Future->done( URI->new( $d->{root}->{documentURL} ))
3278 0 });
3279 }
3280  
3281 ▶sub uri( $self ) {
Subroutine uri: not called CC=1 SCAR=6.9
Pod documented
3282 0 $self->uri_future->get
3283 }
3284  
3285  
3286 =head2 C<< $mech->infinite_scroll( [$wait_time_in_seconds] ) >>
3287  
3288 $new_content_found = $mech->infinite_scroll(3);
3289  
3290 Loads content into pages that have "infinite scroll" capabilities by scrolling
3291 to the bottom of the web page and waiting up to the number of seconds, as set by
3292 the optional C<$wait_time_in_seconds> argument, for the browser to load more
3293 content. The default is to wait up to 20 seconds. For reasonably fast sites,
3294 the wait time can be set much lower.
3295  
3296 The method returns a boolean C<true> if new content is loaded, C<false>
3297 otherwise. You can scroll to the end (if there is one) of an infinitely
3298 scrolling page like so:
3299  
3300 while( $mech->infinite_scroll ) {
3301 # Tests for exiting the loop earlier
3302 last if $count++ >= 10;
3303 }
3304  
3305 =cut
3306  
3307 sub infinite_scroll {
3308 0 ▶ my $self = shift;
Subroutine infinite_scroll: not called CC=4 SCAR=30.0
Pod documented
3309 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
3310  
3311 0 my $current_height = $self->_get_body_height;
3312 0 $self->log('debug', "Current page body height: $current_height");
3313  
3314 0 $self->_scroll_to_bottom;
3315  
3316 0 my $new_height = $self->_get_body_height;
3317 0 $self->log('debug', "New page body height: $new_height");
3318  
3319 0 my $start_time = time();
3320 0 ▶ while (!($new_height > $current_height)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($new_height > $current_height) 0 0 0
3321  
3322 # wait for new elements to load until $wait_time is reached
3323 0 ▶ if (time() - $start_time > $wait_time) {
Branch: 1 branch
BranchTrueFalseTotal
if (time - $start_time > $wait_time) 0 0 0
3324 0 return 0;
3325 }
3326  
3327 # wait 1/10th sec for new elements to load
3328 0 $self->sleep(0.1);
3329 0 $new_height = $self->_get_body_height;
3330 }
3331 0 return 1;
3332 }
3333  
3334 sub _get_body_height {
3335 0 ▶ my $self = shift;
Subroutine _get_body_height: not called CC=1 SCAR=6.9
3336  
3337 0 my ($height) = $self->eval( 'document.body.scrollHeight' );
3338 0 return $height;
3339 }
3340  
3341 sub _scroll_to_bottom {
3342 0 ▶ my $self = shift;
Subroutine _scroll_to_bottom: not called CC=1 SCAR=6.9
3343  
3344 # scroll to bottom and wait for some content to load
3345 0 $self->eval( 'window.scroll(0,document.body.scrollHeight + 200)' );
3346 0 $self->sleep(0.1);
3347 }
3348  
3349 =head1 CONTENT METHODS
3350  
3351 =head2 C<< $mech->document_future() >>
3352  
3353 =head2 C<< $mech->document() >>
3354  
3355 print $self->document->{nodeId};
3356  
3357 Returns the C<document> node.
3358  
3359 This is WWW::Mechanize::Chrome specific.
3360  
3361 =cut
3362  
3363 ▶sub _cached_document($self) {
Subroutine _cached_document: not called CC=2 SCAR=13.0
3364 0 ▶ if( $self->{_document}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_document'}) { } 0 0 0
3365 #warn "Cached document";
3366 return Future->done( $self->{_document} )
3367  
3368 0 } else {
3369 #warn "Requesting fresh document";
3370 0 weaken( my $s = $self );
3371 ▶ return $self->document_future->then(sub ($d) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3372 #warn "Have fresh document";
3373 0 $s->{_document} = $d;
3374 Future->done( $s->{_document} )
3375 0 ▶ })->catch(sub(@error) {
Subroutine __ANON__: not called CC=1 SCAR=0.6
3376 69 ▶ use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
3377 0 warn "Error while retrieving document:".Dumper \@error;
3378 0 });
3379 }
3380 }
3381  
3382 sub _clear_cached_document {
3383 0 ▶ delete $_[0]->{_document};
Subroutine _clear_cached_document: not called CC=1 SCAR=6.9
3384 };
3385  
3386 # Move to DOMSnapshot.captureSnapshot / DOMSnapshot.DocumentSnapshot instead
3387 ▶sub document_future( $self ) {
Subroutine document_future: not called CC=1 SCAR=6.9
Pod documented
3388 0 return $self->target->send_message('DOM.getDocument', depth => -1, pierce => JSON::false );
3389 }
3390  
3391 ▶sub document( $self ) {
Subroutine document: not called CC=1 SCAR=6.9
Pod documented
3392 0 $self->_cached_document->get
3393 }
3394  
3395 ▶sub decoded_content($self) {
Subroutine decoded_content: not called CC=3 SCAR=24.8
Pod undocumented
3396 0 my $res;
3397 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
3398 0 ▶ if( $ct eq 'text/html' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ct eq 'text/html') { } 0 0 0
3399 ▶ $res = $self->_cached_document->then(sub( $root ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3400 # Join _all_ child nodes together to also fetch DOCTYPE nodes
3401 # and the stuff that comes after them
3402  
3403 my @content = map {
3404 0 my $nodeId = $_->{nodeId};
3405 0 $self->log('trace', "Fetching HTML for node " . $nodeId );
3406 0 $self->target->send_message('DOM.getOuterHTML', nodeId => 0+$nodeId )
3407 0 } @{ $root->{root}->{children} };
3408  
3409 ▶ return Future->wait_all( @content )
Subroutine __ANON__: not called CC=1 SCAR=6.9
3410 ->then( sub( @outerHTML_f ) {
3411 0 Future->done( join "", map { $_->get->{outerHTML} } @outerHTML_f );
3412 0 });
3413 0 });
3414 } else {
3415 # Return the raw body
3416 #use Data::Dumper;
3417 #warn Dumper $self->response;
3418 #warn $self->response->content;
3419  
3420 # The content is already decoded (?!)
3421 # I'm not sure how well this plays with encodings, and
3422 # binary content
3423 0 $res = Future->done($self->response->content);
3424 };
3425 0 return $res->get
3426 };
3427  
3428 =head2 C<< $mech->content( %options ) >>
3429  
3430 print $mech->content;
3431 print $mech->content( format => 'html' ); # default
3432 print $mech->content( format => 'text' ); # identical to ->text
3433 print $mech->content( format => 'mhtml' ); # identical to ->captureSnapshot
3434  
3435 This always returns the content as a Unicode string. It tries
3436 to decode the raw content according to its input encoding.
3437 This currently only works for HTML pages, not for images etc.
3438  
3439 Recognized options:
3440  
3441 =over 4
3442  
3443 =item *
3444  
3445 C<format> - the stuff to return
3446  
3447 The allowed values are C<html> and C<text>. The default is C<html>.
3448  
3449 =back
3450  
3451 =cut
3452  
3453 ▶sub content( $self, %options ) {
Subroutine content: not called CC=5 SCAR=34.0
Pod documented
3454 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
3455 0 my $format = delete $options{ format };
3456  
3457 0 my $content;
3458 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
3459 0 $content= $self->decoded_content()
3460 } elsif ( $format eq 'text' ) {
3461 0 $content= $self->text;
3462 } elsif ( $format eq 'mhtml' ) {
3463 0 $content= $self->captureSnapshot()->{data};
3464 } else {
3465 0 die qq{Unknown "format" parameter "$format"};
3466 };
3467 };
3468  
3469 =head2 C<< $mech->text() >>
3470  
3471 print $mech->text();
3472  
3473 Returns the text of the current HTML content. If the content isn't
3474 HTML, $mech will die.
3475  
3476 =cut
3477  
3478 sub text {
3479 0 ▶ my $self = shift;
Subroutine text: not called CC=1 SCAR=6.9
Pod documented
3480  
3481 # Waugh - this is highly inefficient but conveniently short to write
3482 # Maybe this should skip SCRIPT nodes...
3483 0 join '', map { $_->get_attribute('innerText', live => 1) } $self->xpath('//body', single => 1 );
3484 }
3485  
3486 =head2 C<< $mech->captureSnapshot_future() >>
3487  
3488 =head2 C<< $mech->captureSnapshot() >>
3489  
3490 print $mech->captureSnapshot( format => 'mhtml' )->{data};
3491  
3492 Returns the current page as MHTML.
3493  
3494 This is WWW::Mechanize::Chrome specific.
3495  
3496 =cut
3497  
3498 ▶sub captureSnapshot_future( $self, %options ) {
Subroutine captureSnapshot_future: not called CC=1 SCAR=6.9
Pod documented
3499 0 $self->target->send_message( 'Page.captureSnapshot', %options )
3500 }
3501  
3502 ▶sub captureSnapshot( $self, %options ) {
Subroutine captureSnapshot: not called CC=1 SCAR=6.9
Pod documented
3503 0 $self->captureSnapshot_future(%options)->get
3504 }
3505  
3506 =head2 C<< $mech->content_encoding() >>
3507  
3508 print "The content is encoded as ", $mech->content_encoding;
3509  
3510 Returns the encoding that the content is in. This can be used
3511 to convert the content from UTF-8 back to its native encoding.
3512  
3513 =cut
3514  
3515 sub content_encoding {
3516 0 ▶ my ($self) = @_;
Subroutine content_encoding: not called CC=3 SCAR=24.8
Pod documented
3517 # Let's trust the <meta http-equiv first, and the header second:
3518 # Also, a pox on Chrome for not having lower-case or upper-case
3519 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
3520 0 (my $ct= $meta->{attributes}->{'content'}) =~ s/^.*;\s*charset=\s*//i;
3521 0 ▶ return $ct
Branch: 1 branch
BranchTrueFalseTotal
if $ct 0 0 0
3522 if( $ct );
3523 };
3524 0 $self->response->header('Content-Type');
3525 };
3526  
3527 =head2 C<< $mech->update_html( $html ) >>
3528  
3529 $mech->update_html($html);
3530  
3531 Writes C<$html> into the current document. This is mostly
3532 implemented as a convenience method for L<HTML::Display::MozRepl>.
3533  
3534 The value passed in as C<$html> will be stringified.
3535  
3536 =cut
3537  
3538 ▶sub update_html_future( $self, $content ) {
Subroutine update_html_future: not called CC=1 SCAR=2.8
Pod undocumented
3539 0 my $doc = $self->_cached_document;
3540 ▶ return $doc->then(sub( $root ) {
Subroutine __ANON__: not called CC=2 SCAR=11.6
3541 # Find "HTML" child node:
3542 0 my $nodeId = $root->{root}->{children}->[0]->{nodeId};
3543 0 my $id;
3544 0 ▶ if( ! $nodeId ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $nodeId) { } 0 0 0
3545 69 ▶ use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
3546 0 warn Dumper $root;
3547 0 warn "Need / fetching nodeId from backendNodeId";
3548  
3549 0 my @parentNodes; # we only expect one ...
3550 ▶ my $setChildNodes = $self->add_listener('DOM.setChildNodes', sub( $ev ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3551 #use Data::Dumper; warn "setChildNodes: "; warn Dumper $ev;
3552 0 push @parentNodes, @{ $ev->{params}->{nodes} };
3553 0 });
3554  
3555 $id = $self->target->send_message('DOM.resolveNode', backendNodeId => $root->{root}->{children}->[0]->{backendNodeId} )
3556 ▶ ->then( sub ( $nodeInfo ) {
Subroutine __ANON__: not called CC=1 SCAR=0.6
3557 69 ▶ use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
3558 0 warn Dumper $nodeInfo;
3559 $self->target->send_message('DOM.requestNode', objectId => $nodeInfo->{object}->{objectId})
3560 #return Future->done( $nodeInfo->{node}->{nodeId} )
3561 0 ▶ })->catch(sub( @error ) {
Subroutine __ANON__: not called CC=1 SCAR=1.2
3562 69 ▶ use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
3563 0 warn "Couldn't find node: @error";
3564 0 warn Dumper \@error;
3565 ▶ })->then(sub ( $node ) {
Subroutine __ANON__: not called CC=1 SCAR=1.2
3566  
3567 # Implicitly, @parentNodes has been filled ...
3568  
3569 69 ▶ use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
3570 0 warn Dumper $node;
3571 return Future->done( $node->{nodeId} )
3572 #return Future->done( $childNodes[0]->{nodeId} )
3573 0 });
3574  
3575 } else {
3576 0 $id = $self->target->future->done( $nodeId );
3577 };
3578  
3579 $id->then( sub {
3580 0 ▶ $self->log('trace', "Setting HTML for node " . $nodeId );
Subroutine __ANON__: not called CC=1 SCAR=6.9
3581 $self->target->send_message('DOM.setOuterHTML', nodeId => 0+$nodeId, outerHTML => "$content" )
3582 ->then(sub {;
3583 0 ▶ $self->invalidate_cached_values;
Subroutine __ANON__: not called CC=1 SCAR=6.9
3584 0 Future->done()
3585 })
3586  
3587 # Also, we need to wait for a DOM.documentUpdated here before querying
3588 # again ... do we?!
3589 0 });
3590 0 });
3591 };
3592  
3593 ▶sub update_html( $self, $content ) {
Subroutine update_html: not called CC=1 SCAR=6.9
Pod documented
3594 0 $self->update_html_future($content)->get
3595 }
3596 =head2 C<< $mech->base() >>
3597  
3598 print $mech->base;
3599  
3600 Returns the URL base for the current page.
3601  
3602 The base is either specified through a C<base>
3603 tag or is the current URL.
3604  
3605 This method is specific to WWW::Mechanize::Chrome.
3606  
3607 =cut
3608  
3609 sub base {
3610 0 ▶ my ($self) = @_;
Subroutine base: not called CC=4 SCAR=30.0
Pod undocumented
3611 0 (my $base) = $self->selector('base');
3612 $base = $base->get_attribute('href', live => 1)
3613 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
3614 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
3615 };
3616  
3617 =head2 C<< $mech->content_type() >>
3618  
3619 =head2 C<< $mech->ct() >>
3620  
3621 print $mech->content_type;
3622  
3623 Returns the content type of the currently loaded document
3624  
3625 =cut
3626  
3627 sub content_type {
3628 0 ▶ my ($self) = @_;
Subroutine content_type: not called CC=5 SCAR=34.0
Pod documented
3629 # Let's trust the <meta http-equiv first, and the header second:
3630 # Also, a pox on Chrome for not having lower-case or upper-case
3631 0 my $ct;
3632 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
3633 0 $ct= $meta->{attributes}->{'content'};
3634 };
3635 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
3636  
3637 0 my $h= $r->headers;
3638 0 $ct= $h->header('Content-Type');
3639 };
3640 0 ▶ $ct =~ s/;.*$// if defined $ct;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ct 0 0 0
3641 0 $ct
3642 };
3643  
3644 {
3645 69 ▶ no warnings 'once';
Subroutine BEGIN: called CC=1 SCAR=0.0
3646 69 *ct = \&content_type;
3647 }
3648  
3649 =head2 C<< $mech->is_html() >>
3650  
3651 print $mech->is_html();
3652  
3653 Returns true/false on whether our content is HTML, according to the
3654 HTTP headers.
3655  
3656 =cut
3657  
3658 sub is_html {
3659 0 ▶ my $self = shift;
Subroutine is_html: not called CC=2 SCAR=17.9
Pod documented
3660 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
3661 }
3662  
3663 =head2 C<< $mech->title() >>
3664  
3665 print "We are on page " . $mech->title;
3666  
3667 Returns the current document title.
3668  
3669 =cut
3670  
3671 ▶sub title( $self ) {
Subroutine title: not called CC=1 SCAR=6.9
Pod documented
3672 $self->target->info->{title}
3673 0 };
3674  
3675 =head1 EXTRACTION METHODS
3676  
3677 =head2 C<< $mech->links() >>
3678  
3679 print $_->text . " -> " . $_->url . "\n"
3680 for $mech->links;
3681  
3682 Returns all links in the document as L<WWW::Mechanize::Link> objects.
3683  
3684 Currently accepts no parameters. See C<< ->xpath >>
3685 or C<< ->selector >> when you want more control.
3686  
3687 =cut
3688  
3689 69 our %link_spec = (
3690 a => { url => 'href', },
3691 area => { url => 'href', },
3692 frame => { url => 'src', },
3693 iframe => { url => 'src', },
3694 link => { url => 'href', },
3695 meta => { url => 'content', xpath => (join '',
3696 q{translate(@http-equiv,'ABCDEFGHIJKLMNOPQRSTUVWXYZ',},
3697 q{'abcdefghijklmnopqrstuvwxyz')="refresh"}), },
3698 );
3699 # taken from WWW::Mechanize. This should possibly just be reused there
3700 sub make_link {
3701 0 ▶ my ($self,$node,$base) = @_;
Subroutine make_link: not called CC=7 SCAR=40.3
Pod undocumented
3702  
3703 0 my $tag = lc $node->get_tag_name;
3704 0 my $url;
3705 0 ▶ if ($tag) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tag) 0 0 0
3706 0 ▶ if( ! exists $link_spec{ $tag }) {
Branch: 1 branch
BranchTrueFalseTotal
if (not exists $WWW::Mechanize::Chrome::link_spec{$tag}) { } 0 0 0
3707 0 carp "Unknown link-spec tag '$tag'";
3708 0 $url= '';
3709 } else {
3710 0 $url = $node->get_attribute( $link_spec{ $tag }->{url}, live => 1 );
3711 };
3712 };
3713  
3714 0 ▶ if ($tag eq 'meta') {
Branch: 1 branch
BranchTrueFalseTotal
if ($tag eq "meta") 0 0 0
3715 0 my $content = $url;
3716 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
3717 0 $url = $1;
3718 0 ▶ $url =~ s/^"(.+)"$/$1/ or $url =~ s/^'(.+)'$/$1/;
Branch: 1 branch
BranchTrueFalseTotal
$url =~ s/^"(.+)"$/$1/u or $url =~ s/^'(.+)'$/$1/u 0 0 0
3719 }
3720 else {
3721 0 undef $url;
3722 }
3723 };
3724  
3725 0 ▶ if (defined $url) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $url) { } 0 0 0
3726 #my $text => $node->get_attribute('text'),
3727 0 my $text = $node->get_text;
3728 0 $text =~ s!\A\s+!!s;
3729 0 $text =~ s!\s+\z!!s;
3730 0 my $res = WWW::Mechanize::Link->new({
3731 tag => $tag,
3732 name => $node->get_attribute('name', live => 1),
3733 base => $base,
3734 url => $url,
3735 text => $text,
3736 attrs => {},
3737 });
3738 0 return $res
3739 } else {
3740 ()
3741 0 };
3742 }
3743  
3744 sub links {
3745 0 ▶ my ($self) = @_;
Subroutine links: not called CC=1 SCAR=6.9
Pod documented
3746 0 my @links = $self->selector( join ",", sort keys %link_spec);
3747 0 my $base = $self->base;
3748 return map {
3749 0 $self->make_link($_,$base)
3750 } @links;
3751 };
3752  
3753 =head2 C<< $mech->selector( $css_selector, %options ) >>
3754  
3755 my @text = $mech->selector('p.content');
3756  
3757 Returns all nodes matching the given CSS selector. If
3758 C<$css_selector> is an array reference, it returns
3759 all nodes matched by any of the CSS selectors in the array.
3760  
3761 This takes the same options that C<< ->xpath >> does.
3762  
3763 This method is implemented via L<WWW::Mechanize::Plugin::Selector>.
3764  
3765 =cut
3766  
3767 sub selector {
3768 0 ▶ my ($self,$query,%options) = @_;
Subroutine selector: not called CC=5 SCAR=34.0
Pod documented
3769 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
3770 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
3771 0 $query = [$query];
3772 };
3773 0 ▶ my $root = $options{ node } ? './' : '';
Branch: 1 branch
BranchTrueFalseTotal
$options{'node'} ? : 0 0 0
3774 0 my @q = map { selector_to_xpath($_, root => $root) } @$query;
3775 0 $self->xpath(\@q, %options);
3776 };
3777  
3778 =head2 C<< $mech->find_link_dom( %options ) >>
3779  
3780 print $_->{innerHTML} . "\n"
3781 for $mech->find_link_dom( text_contains => 'CPAN' );
3782  
3783 A method to find links, like L<WWW::Mechanize>'s
3784 C<< ->find_links >> method. This method returns DOM objects from
3785 Chrome instead of WWW::Mechanize::Link objects.
3786  
3787 Note that Chrome
3788 might have reordered the links or frame links in the document
3789 so the absolute numbers passed via C<n>
3790 might not be the same between
3791 L<WWW::Mechanize> and L<WWW::Mechanize::Chrome>.
3792  
3793 The supported options are:
3794  
3795 =over 4
3796  
3797 =item *
3798  
3799 C<< text >> and C<< text_contains >> and C<< text_regex >>
3800  
3801 Match the text of the link as a complete string, substring or regular expression.
3802  
3803 Matching as a complete string or substring is a bit faster, as it is
3804 done in the XPath engine of Chrome.
3805  
3806 =item *
3807  
3808 C<< id >> and C<< id_contains >> and C<< id_regex >>
3809  
3810 Matches the C<id> attribute of the link completely or as part
3811  
3812 =item *
3813  
3814 C<< name >> and C<< name_contains >> and C<< name_regex >>
3815  
3816 Matches the C<name> attribute of the link
3817  
3818 =item *
3819  
3820 C<< url >> and C<< url_regex >>
3821  
3822 Matches the URL attribute of the link (C<href>, C<src> or C<content>).
3823  
3824 =item *
3825  
3826 C<< class >> - the C<class> attribute of the link
3827  
3828 =item *
3829  
3830 C<< n >> - the (1-based) index. Defaults to returning the first link.
3831  
3832 =item *
3833  
3834 C<< single >> - If true, ensure that only one element is found. Otherwise croak
3835 or carp, depending on the C<autodie> parameter.
3836  
3837 =item *
3838  
3839 C<< one >> - If true, ensure that at least one element is found. Otherwise croak
3840 or carp, depending on the C<autodie> parameter.
3841  
3842 The method C<croak>s if no link is found. If the C<single> option is true,
3843 it also C<croak>s when more than one link is found.
3844  
3845 =back
3846  
3847 =cut
3848  
3849 69 our %xpath_quote = (
3850 '"' => '\"',
3851 #"'" => "\\'",
3852 #'[' => '&#91;',
3853 #']' => '&#93;',
3854 #'[' => '[\[]',
3855 #'[' => '\[',
3856 #']' => '[\]]',
3857 );
3858  
3859 sub quote_xpath {
3860 0 ▶ local $_ = $_[0];
Subroutine quote_xpath: not called CC=2 SCAR=17.9
Pod undocumented
3861 0 ▶ s/(['"\[\]])/$xpath_quote{$1} || $1/ge;
Branch: 1 branch
BranchTrueFalseTotal
$WWW::Mechanize::Chrome::xpath_quote{$1} or $1 0 0 0
3862 0 $_
3863 };
3864  
3865 # Copied from WWW::Mechanize 1.97
3866 # Used by find_links to check for matches
3867 # The logic is such that ALL param criteria that are given must match
3868 ▶sub _match_any_link_params( $self, $link, $p ) {
Subroutine _match_any_link_params: not called CC=40 SCAR=74.0
3869 # No conditions, anything matches
3870 0 ▶ return 1 unless keys %$p;
Branch: 1 branch
BranchTrueFalseTotal
unless keys %$p 0 0 0
3871  
3872 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
3873 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
3874 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
3875 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
3876 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
3877 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
3878 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
3879 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
3880 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
3881 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
3882  
3883 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
3884 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
3885 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
3886 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
3887  
3888 # Success: everything that was defined passed.
3889 0 return 1;
3890 }
3891  
3892 sub find_link_dom {
3893 0 ▶ my ($self,%opts) = @_;
Subroutine find_link_dom: not called CC=24 SCAR=64.0
Pod documented
3894 0 my %xpath_options;
3895  
3896 # Clean up some legacy stuff
3897 0 delete @opts{ qw(synchronize) };
3898  
3899 0 for (qw(node document frames xpath selector)) {
3900 # Copy over XPath options that were passed in
3901 0 ▶ if (exists $opts{ $_ }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{$_}) 0 0 0
3902 0 $xpath_options{ $_ } = delete $opts{ $_ };
3903 };
3904 };
3905  
3906 0 my $single = delete $opts{ single };
3907 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
3908 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
3909 0 croak "It doesn't make sense to use 'single' and 'n' option together"
3910 };
3911 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
3912 0 ▶ $n--
Branch: 1 branch
BranchTrueFalseTotal
if $n ne "all" 0 0 0
3913 if ($n ne 'all'); # 1-based indexing
3914 0 my @spec;
3915  
3916 # Decode text and text_contains into XPath
3917 0 for my $lvalue (qw( text id name class )) {
3918 0 my %lefthand = (
3919 text => 'text()',
3920 );
3921 0 my %match_op = (
3922 '' => q{%s="%s"},
3923 'contains' => q{contains(%s,"%s")},
3924 # Ideally we would also handle *_regex here, but Chrome XPath
3925 # does not support fn:matches() :-(
3926 #'regex' => q{matches(%s,"%s","%s")},
3927 );
3928 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
3929 0 for my $op (keys %match_op) {
3930 0 my $v = $match_op{ $op };
3931 0 ▶ $op = '_'.$op if length($op);
Branch: 1 branch
BranchTrueFalseTotal
if length $op 0 0 0
3932 0 my $key = "${lvalue}$op";
3933  
3934 0 ▶ if (exists $opts{ $key }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{$key}) 0 0 0
3935 0 my $p = delete $opts{ $key };
3936 0 push @spec, sprintf $v, $lhs, $p;
3937 };
3938 };
3939 };
3940  
3941 0 ▶ if (my $p = delete $opts{ url }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $p = delete $opts{"url"}) 0 0 0
3942 0 push @spec, sprintf '@href = "%s" or @src="%s"', quote_xpath( $p ), quote_xpath( $p );
3943 }
3944 0 my @tags = (sort keys %link_spec);
3945 0 ▶ if (my $p = delete $opts{ tag }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $p = delete $opts{"tag"}) 0 0 0
3946 0 @tags = $p;
3947 };
3948 0 ▶ if (my $p = delete $opts{ tag_regex }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $p = delete $opts{"tag_regex"}) 0 0 0
3949 0 @tags = grep /$p/, @tags;
3950 };
3951 my $q = join '|',
3952 map {
3953 0 ▶ my $xp= exists $link_spec{ $_ } ? $link_spec{$_}->{xpath} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $WWW::Mechanize::Chrome::link_spec{$_} ? : 0 0 0
3954 0 my @full = map {qq{($_)}} grep {defined} (@spec, $xp);
3955 0 ▶ if (@full) {
Branch: 1 branch
BranchTrueFalseTotal
if (@full) { } 0 0 0
3956 0 sprintf "//%s[%s]", $_, join " and ", @full;
3957 } else {
3958 0 sprintf "//%s", $_
3959 };
3960 } (@tags);
3961 #warn $q;
3962  
3963 0 my @res = $self->xpath($q, %xpath_options );
3964  
3965 0 ▶ if (keys %opts) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %opts) 0 0 0
3966 # post-filter the remaining links
3967 # for all the options we don't support with XPath
3968 0 my $base = $self->base;
3969  
3970 @res = grep {
3971 0 $self->_match_any_link_params($self->make_link($_,$base),\%opts);
3972 } @res;
3973 };
3974  
3975 0 ▶ if ($one) {
Branch: 1 branch
BranchTrueFalseTotal
if ($one) 0 0 0
3976 0 ▶ if (0 == @res) { $self->signal_condition( "No link found matching '$q'" )};
Branch: 1 branch
BranchTrueFalseTotal
if (0 == @res) 0 0 0
3977 0 ▶ if ($single) {
Branch: 1 branch
BranchTrueFalseTotal
if ($single) 0 0 0
3978 0 ▶ if (1 < @res) {
Branch: 1 branch
BranchTrueFalseTotal
if (1 < @res) 0 0 0
3979 0 $self->highlight_node(@res);
3980 0 $self->signal_condition(
3981 sprintf "%d elements found found matching '%s'", scalar @res, $q
3982 );
3983 };
3984 };
3985 };
3986  
3987 0 ▶ if ($n eq 'all') {
Branch: 1 branch
BranchTrueFalseTotal
if ($n eq "all") 0 0 0
3988 return @res
3989 0 };
3990 0 $res[$n]
3991 }
3992  
3993 =head2 C<< $mech->find_link( %options ) >>
3994  
3995 print $_->text . "\n"
3996 for $mech->find_link( text_contains => 'CPAN' );
3997  
3998 A method quite similar to L<WWW::Mechanize>'s method.
3999 The options are documented in C<< ->find_link_dom >>.
4000  
4001 Returns a L<WWW::Mechanize::Link> object.
4002  
4003 This defaults to not look through child frames.
4004  
4005 =cut
4006  
4007 sub find_link {
4008 0 ▶ my ($self,%opts) = @_;
Subroutine find_link: not called CC=4 SCAR=30.0
Pod documented
4009 0 my $base = $self->base;
4010 croak "Option 'all' not available for ->find_link. Did you mean to call ->find_all_links()?"
4011 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
4012 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
4013 0 return $self->make_link($link, $base)
4014 } else {
4015 return
4016 0 };
4017 };
4018  
4019 =head2 C<< $mech->find_all_links( %options ) >>
4020  
4021 print $_->text . "\n"
4022 for $mech->find_all_links( text_regex => qr/google/i );
4023  
4024 Finds all links in the document.
4025 The options are documented in C<< ->find_link_dom >>.
4026  
4027 Returns them as list or an array reference, depending
4028 on context.
4029  
4030 This defaults to not look through child frames.
4031  
4032 =cut
4033  
4034 sub find_all_links {
4035 0 ▶ my ($self, %opts) = @_;
Subroutine find_all_links: not called CC=2 SCAR=17.9
Pod documented
4036 0 $opts{ n } = 'all';
4037 0 my $base = $self->base;
4038 my @matches = map {
4039 0 $self->make_link($_, $base);
4040 } $self->find_all_links_dom( frames => 0, %opts );
4041 0 ▶ return @matches if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 0 0 0
4042 0 return \@matches;
4043 };
4044  
4045 =head2 C<< $mech->find_all_links_dom %options >>
4046  
4047 print $_->{innerHTML} . "\n"
4048 for $mech->find_all_links_dom( text_regex => qr/google/i );
4049  
4050 Finds all matching linky DOM nodes in the document.
4051 The options are documented in C<< ->find_link_dom >>.
4052  
4053 Returns them as list or an array reference, depending
4054 on context.
4055  
4056 This defaults to not look through child frames.
4057  
4058 =cut
4059  
4060 sub find_all_links_dom {
4061 0 ▶ my ($self,%opts) = @_;
Subroutine find_all_links_dom: not called CC=2 SCAR=17.9
Pod documented
4062 0 $opts{ n } = 'all';
4063 0 my @matches = $self->find_link_dom( frames => 0, %opts );
4064 0 ▶ return @matches if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 0 0 0
4065 0 return \@matches;
4066 };
4067  
4068 =head2 C<< $mech->follow_link( $link ) >>
4069  
4070 =head2 C<< $mech->follow_link( %options ) >>
4071  
4072 $mech->follow_link( xpath => '//a[text() = "Click here!"]' );
4073  
4074 Follows the given link. Takes the same parameters that C<find_link_dom>
4075 uses.
4076  
4077 Note that C<< ->follow_link >> will only try to follow link-like
4078 things like C<A> tags.
4079  
4080 =cut
4081  
4082 sub follow_link {
4083 0 ▶ my ($self,$link,%opts);
Subroutine follow_link: not called CC=2 SCAR=17.9
Pod documented
4084 0 ▶ if (@_ == 2) { # assume only a link parameter
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 2) { } 0 0 0
4085 0 ($self,$link) = @_;
4086 0 $self->click($link);
4087 } else {
4088 0 ($self,%opts) = @_;
4089 0 _default_limiter( one => \%opts );
4090 0 $link = $self->find_link_dom(%opts);
4091 0 $self->click({ dom => $link, %opts });
4092 }
4093 }
4094  
4095 sub activate_parent_container {
4096 0 ▶ my( $self, $doc )= @_;
Subroutine activate_parent_container: not called CC=1 SCAR=6.9
Pod undocumented
4097 0 $self->activate_container( $doc, 1 );
4098 };
4099  
4100 sub activate_container {
4101 0 ▶ my( $self, $doc, $just_parent )= @_;
Subroutine activate_container: not called CC=7 SCAR=40.3
Pod undocumented
4102 0 my $driver= $self->driver;
4103  
4104 0 ▶ if( ! $doc->{__path}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($doc->{"__path"}) 0 0 0
4105 0 die "Invalid document without __path encountered. I'm sorry.";
4106 };
4107 # Activate the root window/frame
4108 #warn "Activating root frame:";
4109 #$driver->switch_to_frame();
4110 #warn "Activating root frame done.";
4111  
4112 0 for my $el ( @{ $doc->{__path} }) {
4113 #warn "Switching frames downwards ($el)";
4114 #warn "Tag: " . $el->get_tag_name;
4115 #warn Dumper $el;
4116 0 warn sprintf "Switching during path to %s %s", $el->get_tag_name, $el->get_attribute('src', live => 1);
4117 0 $driver->switch_to_frame( $el );
4118 };
4119  
4120 0 ▶ if( ! $just_parent ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($just_parent) 0 0 0
4121 0 warn sprintf "Activating container %s too", $doc->{id};
4122 # Now, unless it's the root frame, activate the container. The root frame
4123 # already is activated above.
4124 0 warn "Getting tag";
4125 0 my $tag= $doc->get_tag_name;
4126 #my $src= $doc->get_attribute('src');
4127 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
4128 #warn sprintf "Switching to final container %s %s", $tag, $src;
4129 0 $driver->switch_to_frame( $doc );
4130 };
4131 #warn sprintf "Switched to final/main container %s %s", $tag, $src;
4132 };
4133 #warn $self->target->get_current_url;
4134 #warn $self->target->get_title;
4135 #my $body= $doc->get_attribute('contentDocument');
4136 0 my $body= $driver->find_element('/*', 'xpath');
4137 0 ▶ if( $body ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body) 0 0 0
4138 0 warn "Now active container: " . $body->get_attribute('innerHTML', live => 1);
4139 #$body= $body->get_attribute('document');
4140 #warn $body->get_attribute('innerHTML');
4141 };
4142 };
4143  
4144 =head2 C<< $mech->xpath( $query, %options ) >>
4145  
4146 my $link = $mech->xpath('//a[id="clickme"]', one => 1);
4147 # croaks if there is no link or more than one link found
4148  
4149 my @para = $mech->xpath('//p');
4150 # Collects all paragraphs
4151  
4152 my @para_text = $mech->xpath('//p/text()', type => $mech->xpathResult('STRING_TYPE'));
4153 # Collects all paragraphs as text
4154  
4155 Runs an XPath query in Chrome against the current document.
4156  
4157 If you need more information about the returned results,
4158 use the C<< ->xpathEx() >> function.
4159  
4160 Note that Chrome sometimes returns a node with node id 0. This node then
4161 cannot be found again using the Chrome API. This is bad luck and results in
4162 a warning.
4163  
4164 The options allow the following keys:
4165  
4166 =over 4
4167  
4168 =item *
4169  
4170 C<< document >> - document in which the query is to be executed. Use this to
4171 search a node within a specific subframe of C<< $mech->document >>.
4172  
4173 =item *
4174  
4175 C<< frames >> - if true, search all documents in all frames and iframes.
4176 This may or may not conflict with C<node>. This will default to the
4177 C<frames> setting of the WWW::Mechanize::Chrome object.
4178  
4179 =item *
4180  
4181 C<< node >> - node relative to which the query is to be executed. Note
4182 that you will have to use a relative XPath expression as well. Use
4183  
4184 .//foo
4185  
4186 instead of
4187  
4188 //foo
4189  
4190 Querying relative to a node only works for restricting to children of the node,
4191 not for anything else. This is because we need to do the ancestor filtering
4192 ourselves instead of having a Chrome API for it.
4193  
4194 =item *
4195  
4196 C<< single >> - If true, ensure that only one element is found. Otherwise croak
4197 or carp, depending on the C<autodie> parameter.
4198  
4199 =item *
4200  
4201 C<< one >> - If true, ensure that at least one element is found. Otherwise croak
4202 or carp, depending on the C<autodie> parameter.
4203  
4204 =item *
4205  
4206 C<< maybe >> - If true, ensure that at most one element is found. Otherwise
4207 croak or carp, depending on the C<autodie> parameter.
4208  
4209 =item *
4210  
4211 C<< all >> - If true, return all elements found. This is the default.
4212 You can use this option if you want to use C<< ->xpath >> in scalar context
4213 to count the number of matched elements, as it will otherwise emit a warning
4214 for each usage in scalar context without any of the above restricting options.
4215  
4216 =item *
4217  
4218 C<< any >> - no error is raised, no matter if an item is found or not.
4219  
4220 =back
4221  
4222 Returns the matched results as L<WWW::Mechanize::Chrome::Node> objects.
4223  
4224 You can pass in a list of queries as an array reference for the first parameter.
4225 The result will then be the list of all elements matching any of the queries.
4226  
4227 This is a method that is not implemented in WWW::Mechanize.
4228  
4229 In the long run, this should go into a general plugin for
4230 L<WWW::Mechanize>.
4231  
4232 =cut
4233  
4234 # This unwraps a tree of child nodes into a flat hash indexed by nodeId
4235 0 ▶sub _unwrapChildNodeTree( $self, $nodes, $tree={} ) {
Subroutine _unwrapChildNodeTree: not called CC=4 SCAR=30.0
4236 0 for my $node (@$nodes) {
4237 0 $tree->{ $node->{nodeId} } = $node;
4238 0 ▶ if( $node->{children}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->{"children"}) 0 0 0
4239 0 $self->_unwrapChildNodeTree( $node->{children}, $tree );
4240 };
4241 }
4242 0 return $tree
4243 }
4244  
4245 ▶sub _performSearch( $self, %args ) {
Subroutine _performSearch: not called CC=2 SCAR=17.9
4246 0 my $subTreeId = $args{ subTreeId };
4247 0 my $query = $args{ query };
4248 0 weaken( my $s = $self );
4249  
4250 0 my $doc;
4251 # Retry a search up to three times if the page changes in the meantime
4252 my $nodeGeneration;
4253 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
4254 0 my $retries = 3;
4255 0 my $last_search;
4256 my $search = repeat {
4257 0 ▶ $nodeGeneration = $self->{_currentNodeGeneration};
Subroutine __ANON__: not called CC=1 SCAR=6.9
4258 # Lock the document, hoping that no intermittent update messes up our IDs
4259 # Just to make sure we avoid nodeId 0 ?!
4260 # https://github.com/cyrus-and/chrome-remote-interface/issues/165
4261 ▶ my $wait = $s->_cached_document->then(sub( $r ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
4262 0 $doc = $r->{root};
4263 0 Future->done
4264 0 });
4265  
4266 ▶ $wait = $wait->then( sub(@info) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
4267 0 my $res = $s->target->send_message( 'DOM.performSearch', query => $query );
4268 0 return $res
4269 0 });
4270 0 return $wait
4271  
4272 ▶ } while => sub($search) {
Subroutine __ANON__: not called CC=4 SCAR=30.0
4273 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
4274  
4275 0 ▶ if( $retry ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($retry) 0 0 0
4276 # close the previous search attempt
4277 ▶ my $se = $search->then(sub($results) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
4278 0 my $searchId = $results->{searchId};
4279 #warn "!!! Discarding search";
4280 0 $s->target->send_message( 'DOM.discardSearchResults',
4281 searchId => $searchId,
4282 );
4283 0 });
4284 #warn "Closed search: $se";
4285 0 $se->retain;
4286 }
4287  
4288 0 ▶ if( $retry ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($retry) 0 0 0
4289 0 $s->log('trace', "Retrying search ($retries attempts left)");
4290 }
4291 $retry
4292 0 };
4293  
4294 ▶ $search->then(sub($results) {
Subroutine __ANON__: not called CC=3 SCAR=24.8
4295 0 $s->log('debug', "XPath query '$query' (". $results->{resultCount} . " node(s))");
4296  
4297 0 ▶ if( $results->{resultCount} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($results->{'resultCount'}) { } 0 0 0
4298 0 my $searchResults;
4299 0 my $searchId = $results->{searchId};
4300 0 my @childNodes;
4301 ▶ my $setChildNodes = $self->add_listener('DOM.setChildNodes', sub( $ev ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
4302 #use Data::Dumper; warn "setChildNodes: "; warn Dumper $ev;
4303 0 push @childNodes, @{ $ev->{params}->{nodes} };
4304 0 });
4305  
4306 0 my $childNodes;
4307 0 ▶ if( defined $subTreeId ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $subTreeId) { } 0 0 0
4308 0 $childNodes =
4309 $self->target->send_message( 'DOM.requestChildNodes',
4310 nodeId => 0+$subTreeId,
4311 depth => -1, # we want/need the whole subtree
4312 )
4313 } else {
4314 0 $childNodes = Future->done;
4315 };
4316 my $search = $self->target->send_message( 'DOM.getSearchResults',
4317 searchId => $results->{searchId},
4318 fromIndex => 0,
4319 toIndex => 0+$results->{resultCount},
4320 0 );
4321 # We can't immediately discard our search results until we find out
4322 # what invalidates node ids.
4323 # So we currently accumulate memory until we disconnect. Oh well.
4324 # And node ids still get invalidated
4325 #)->followed_by( sub( $results ) {
4326 # $searchResults = $results->get;
4327 # $self->target->send_message( 'DOM.discardSearchResults',
4328 # searchId => $searchId,
4329 # );
4330 #}
4331  
4332 Future->wait_all( $childNodes, $search )->then(sub {
4333 # The result of $childNodes is indirect here, by pushing
4334 # the setChildNodes messages onto @childNodes
4335 0 ▶ my @discard = $childNodes->get();
Subroutine __ANON__: not called CC=1 SCAR=6.9
4336  
4337 0 return $search;
4338  
4339 ▶ })->then( sub( $response ) {
Subroutine __ANON__: not called CC=5 SCAR=34.0
4340 # you might get a node with nodeId 0. This one
4341 # can't be retrieved. Bad luck.
4342 0 ▶ if($response->{nodeIds}->[0] == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->{"nodeIds"}[0] == 0) 0 0 0
4343 # Maybe we did receive exactly one childnode?!
4344 #if( @childNodes == 1 ) {
4345 # warn "Maybe we can hacky-salvage this?! Forcing nodeId to $childNodes[0]->{nodeId}";
4346 # # Nope - in the bad case, we always get the root node
4347 # # instead of something usable :-/
4348 # $response->{nodeIds}->[0] = $childNodes[0]->{nodeId};
4349 #} else {
4350  
4351 #warn "Bad luck: Node with nodeId 0 found. Info for this one cannot be retrieved";
4352 0 $self->signal_condition( "Bad luck: Node with nodeId 0 found. Info for this one cannot be retrieved" );
4353 #};
4354 };
4355  
4356 # Resolve the found nodes directly with the
4357 # found node ids instead of returning the numbers and fetching
4358 # them later
4359 # We could also prefill some data with the results from
4360 # $childNodes here, if we have that?!
4361 # We build and search the document here:
4362 0 my %node_ids;
4363 #use Data::Dumper;
4364 #warn Dumper $doc;
4365 0 my @scan = @{ $doc->{children}};
4366 0 ▶ while( my $node = shift @scan ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $node = shift @scan) 0 0 0
4367 0 $node_ids{ $node->{nodeId}} = $node;
4368  
4369 #warn join ",", sort keys %node_ids;
4370 0 ▶ if( $node->{children} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->{"children"}) 0 0 0
4371 unshift @scan,
4372 0 map { $_->{parentNodeId} = $node->{nodeId}; $_ }
4373 0 @{$node->{children}};
4374 };
4375 };
4376  
4377 #my @nodes = map {
4378 # WWW::Mechanize::Chrome::Node->fetchNode(
4379 # nodeId => 0+$_,
4380 # driver => $self->target,
4381 # );
4382 #} @{ $response->{nodeIds}};
4383 my @nodes = map {
4384 0 my $nid = $_;
4385 #my $request_f = $self->target->send_message('DOM.pushNodesByBackendIdsToFrontend',
4386 #backendNodeIds => [$node_ids{$_}->{backendNodeId}])
4387 #->then(sub( $info ) {
4388 # warn Dumper $info;
4389  
4390 # Convert the array of attributes to a hash of attributes ...
4391 0 ▶ if( ref $node_ids{$nid}->{attributes} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node_ids{$nid}{"attributes"} eq "ARRAY") 0 0 0
4392 $node_ids{$nid}->{attributes} = +{
4393 0 @{ $node_ids{$nid}->{attributes} }
4394 };
4395 };
4396 Future->done(
4397 WWW::Mechanize::Chrome::Node->new(
4398 0 +{ %{$node_ids{$nid} },
4399 driver => $self->target,
4400 }
4401 ))
4402 #});
4403 0 } @{ $response->{nodeIds}};
4404  
4405 0 Future->wait_all( @nodes )
4406 ▶ })->then( sub( @fetched_nodes ) {
Subroutine __ANON__: not called CC=12 SCAR=50.5
4407 # This should already happen through the DESTROY callback
4408 # but we'll be explicit here
4409 0 $setChildNodes->unregister;
4410 0 undef $setChildNodes;
4411  
4412 # Resolve the found nodes directly with the
4413 # found node ids instead of returning the numbers and fetching
4414 # them later
4415 0 my @foundNodes = map { $_->get() } @fetched_nodes;
4416 0 my $nodes = $self->_unwrapChildNodeTree( \@childNodes );
4417  
4418 0 for (@foundNodes) {
4419 0 my $id = $_->nodeId;
4420 0 ▶ if( ! defined $id ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $id) 0 0 0
4421 #use Data::Dumper;
4422 #warn "Found node without nodeId: " . Dumper $_;
4423 # Sometimes we get a spurious, empty node, so we ignore that
4424 # Maybe that is because the node we searched for went
4425 # away, but we'd need to associate the information
4426 # before we get the response, so ...
4427 0 next;
4428 };
4429 # Backfill here instead of overwriting!
4430 0 ▶ if( my $n = $nodes->{$id} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $n = $nodes->{$id}) 0 0 0
4431 0 for my $key (qw( backendNodeId parentId )) {
4432 0 $_->{ $key } = $n->{ $key };
4433 };
4434 0 ▶ if( ! $_->{backendNodeId} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($_->{"backendNodeId"}) 0 0 0
4435 0 die "No backend node id found via " . Dumper $n;
4436 };
4437 };
4438 0 $nodes->{ $id } = $_;
4439 };
4440  
4441 # Filter @found for those nodes that have $nodeId as
4442 # ancestor because we can't restrict the search in Chrome
4443 # directly...
4444 0 ▶ if( $subTreeId ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($subTreeId) { } 0 0 0
4445  
4446 0 $self->log('trace', "Filtering query results for ancestor backendNodeId $subTreeId");
4447  
4448 # Find all nodes contained in our subtree
4449 0 my @scan = @{ $doc->{children}};
4450 0 my $subTree;
4451 my $inSubTree;
4452 0 my %foundNodes = map { $_->nodeId => $_ } @foundNodes;
4453 0 @foundNodes = ();
4454  
4455 0 ▶ while( my $node = shift @scan ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $node = shift @scan) 0 0 0
4456 #warn join ",", sort keys %node_ids;
4457  
4458 0 ▶ if( $node->{backendNodeId} == $subTreeId ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->{"backendNodeId"} == $subTreeId) 0 0 0
4459 0 $subTree = $node;
4460 0 $inSubTree = 1;
4461 0 @scan = @{$subTree->{children}};
4462 0 next;
4463 };
4464  
4465 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
4466 0 push @foundNodes, $foundNodes{ $node->{nodeId}};
4467 };
4468  
4469 0 ▶ if( $node->{children} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->{"children"}) 0 0 0
4470 unshift @scan,
4471 0 map { $_->{parentNodeId} = $node->{nodeId}; $_ }
4472 0 @{$node->{children}};
4473 };
4474 };
4475  
4476 0 $self->log('debug', "filtered XPath query '$query' for ancestor $subTreeId (". (0+@foundNodes) . " node(s))");
4477 } else {
4478 #warn "*** Not filtering for any parent node";
4479 };
4480  
4481 # Downstream wants a double-nested Future, so do it here
4482 # until we fix downstream
4483 0 Future->wait_all( Future->done( @foundNodes ));
4484 0 });
4485 } else {
4486 0 return Future->done()
4487 };
4488 0 });
4489 }
4490  
4491 ▶sub xpath( $self, $query, %options) {
Subroutine xpath: not called CC=25 SCAR=64.8
Pod documented
4492 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
4493 0 $query = [$query];
4494 };
4495 0 ▶ if( not exists $options{ frames }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options{"frames"}) 0 0 0
4496 0 $options{ frames }= $self->{frames};
4497 };
4498  
4499 0 my $single = $options{ single };
4500 0 my $first = $options{ one };
4501 0 my $maybe = $options{ maybe };
4502 0 my $any = $options{ any };
4503 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
4504 0 ▶ if( $index >= 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($index >= 1) 0 0 0
4505 0 $index--;
4506 };
4507 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
4508 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
4509  
4510 # Construct some helper variables
4511 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
4512 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
4513  
4514 # Sanity check for the common error of
4515 # my $item = $mech->xpath("//foo");
4516 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
4517 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
4518 "You asked for many elements but seem to only want a single item.",
4519 "Did you forget to pass the 'single' option with a true value?",
4520 "Pass 'all => 1' to suppress this message and receive the count of items.",
4521 ) if defined wantarray and !wantarray;
4522 };
4523  
4524 0 my @res;
4525  
4526 0 ▶ if( $options{ document }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{"document"}) 0 0 0
4527 0 warn sprintf "Document %s", $options{ document }->{id};
4528 };
4529  
4530 #my $doc= $options{ document } ? Future->done( $options{ document } ) : $self->document_future;
4531 0 my $doc = Future->done();
4532  
4533 0 weaken(my $s = $self);
4534  
4535 $doc->then( sub {
4536 0 ▶ my $q = join "|", @$query;
Subroutine __ANON__: not called CC=2 SCAR=17.9
4537  
4538 0 my @found;
4539 my $id;
4540 0 ▶ if ($options{ node }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{'node'}) { } 0 0 0
4541 0 $id = $options{ node }->backendNodeId;
4542 #warn "Performing search (below '$id')";
4543 } else {
4544 #warn "Performing search across complete DOM";
4545 };
4546 Future->wait_all(
4547 map {
4548 0 $s->_performSearch( query => $_, subTreeId => $id )
4549 } @$query
4550 );
4551 })->then( sub {
4552 0 ▶ my @found = map { my @r = $_->get; @r ? map { $_->get } @r : () } @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
@r ? : 0 0 0
4553 #for( @found ) {
4554 # use Data::Dumper;
4555 # warn "Found " . Dumper $_;
4556 #};
4557 0 push @res, @found;
4558 0 Future->done( 1 );
4559 0 })->get;
4560  
4561 # Determine if we want only one element
4562 # or a list, like WWW::Mechanize::Chrome
4563  
4564 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
4565 0 $self->signal_condition( sprintf "No elements found for %s", $options{ user_info } );
4566 };
4567 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
4568 #$self->highlight_node(@res);
4569 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
4570 0 $self->signal_condition( sprintf "%d elements found for %s", (scalar @res), $options{ user_info } );
4571 };
4572  
4573 0 ▶ $return_first_element ? $res[$index] : @res
Branch: 1 branch
BranchTrueFalseTotal
$return_first_element ? : 0 0 0
4574 }
4575  
4576 =head2 C<< $mech->by_id( $id, %options ) >>
4577  
4578 my @text = $mech->by_id('_foo:bar');
4579  
4580 Returns all nodes matching the given ids. If
4581 C<$id> is an array reference, it returns
4582 all nodes matched by any of the ids in the array.
4583  
4584 This method is equivalent to calling C<< ->xpath >> :
4585  
4586 $self->xpath(qq{//*[\@id="$_"]}, %options)
4587  
4588 It is convenient when your element ids get mistaken for
4589 CSS selectors.
4590  
4591 =cut
4592  
4593 sub by_id {
4594 0 ▶ my ($self,$query,%options) = @_;
Subroutine by_id: not called CC=4 SCAR=30.0
Pod documented
4595 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
4596 0 $query = [$query];
4597 };
4598 $options{ user_info } ||= "id "
4599 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
4600 . " found";
4601 0 $query = [map { qq{.//*[\@id="$_"]} } @$query];
4602 0 $self->xpath($query, %options)
4603 }
4604  
4605 =head2 C<< $mech->click( $name [,$x ,$y] ) >>
4606  
4607 # If the element is within a <form> element
4608 $mech->click( 'go' );
4609  
4610 # If the element is anywhere on the page
4611 $mech->click({ xpath => '//button[@name="go"]' });
4612  
4613 Has the effect of clicking a button (or other element) on the current form. The
4614 first argument is the C<name> of the button to be clicked. The second and third
4615 arguments (optional) allow you to specify the (x,y) coordinates of the click.
4616  
4617 If there is only one button on the form, C<< $mech->click() >> with
4618 no arguments simply clicks that one button.
4619  
4620 If you pass in a hash reference instead of a name,
4621 the following keys are recognized:
4622  
4623 =over 4
4624  
4625 =item *
4626  
4627 C<text> - Find the element to click by its contained text
4628  
4629 =item *
4630  
4631 C<selector> - Find the element to click by the CSS selector
4632  
4633 =item *
4634  
4635 C<xpath> - Find the element to click by the XPath query
4636  
4637 =item *
4638  
4639 C<dom> - Click on the passed DOM element
4640  
4641 You can use this to click on arbitrary page elements. There is no convenient
4642 way to pass x/y co-ordinates when using the C<dom> option.
4643  
4644 =item *
4645  
4646 C<id> - Click on the element with the given id
4647  
4648 This is useful if your document ids contain characters that
4649 do look like CSS selectors. It is equivalent to
4650  
4651 xpath => qq{//*[\@id="$id"]}
4652  
4653 =item *
4654  
4655 C<intrapage> - Override the detection of whether to wait for a HTTP response
4656 or not. Setting this will never wait for an HTTP response.
4657  
4658 =back
4659  
4660 Returns a L<HTTP::Response> object.
4661  
4662 As a deviation from the WWW::Mechanize API, you can also pass a
4663 hash reference as the first parameter. In it, you can specify
4664 the parameters to search much like for the C<find_link> calls.
4665  
4666 =cut
4667  
4668 sub click {
4669 0 ▶ my ($self,$name,$x,$y) = @_;
Subroutine click: not called CC=11 SCAR=48.8
Pod documented
4670 0 my %options;
4671 my @buttons;
4672  
4673 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
4674 0 croak("->click called with undef link");
4675 ▶ } 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
4676 0 $options{ dom } = $name;
4677 } elsif (ref $name eq 'HASH') { # options
4678 0 %options = %$name;
4679 } else {
4680 0 $options{ name } = $name;
4681 };
4682  
4683 0 ▶ if( exists $options{ text }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options{"text"}) 0 0 0
4684 0 $options{ xpath } = sprintf q{//*[text() = "%s"]}, quote_xpath( $options{ text });
4685 };
4686  
4687 0 ▶ if (exists $options{ name }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options{"name"}) 0 0 0
4688 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
4689 $options{ xpath } = [
4690 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),
4691 ];
4692 0 ▶ if ($options{ name } eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{"name"} eq "") 0 0 0
4693 0 push @{ $options{ xpath }},
4694 q{//*[(translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") = "button" or translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")="input") and @type="button" or @type="submit" or @type="image"]},
4695 ;
4696 };
4697 0 $options{ user_info } = "Button with name '$name'";
4698 };
4699  
4700 0 ▶ if ($options{ dom }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{'dom'}) { } 0 0 0
4701 0 @buttons = $options{ dom };
4702 } else {
4703 0 @buttons = $self->_option_query(%options);
4704 };
4705  
4706 # Get the node as an object so we can find its position and send the clicks:
4707 0 $self->log('trace', sprintf "Resolving nodeId %d to object for clicking", $buttons[0]->nodeId );
4708 0 my $id = $buttons[0]->objectId;
4709 #warn Dumper $self->target->send_message('Runtime.getProperties', objectId => $id)->get;
4710 #warn Dumper $self->target->send_message('Runtime.callFunctionOn', objectId => $id, functionDeclaration => 'function() { this.focus(); }', arguments => [])->get;
4711  
4712 $self->_mightNavigate( sub {
4713 0 ▶ $self->target->send_message('Runtime.callFunctionOn', objectId => $id, functionDeclaration => 'function() { this.click(); }', arguments => [])
Subroutine __ANON__: not called CC=1 SCAR=6.9
4714 0 }, %options)
4715 ->get;
4716  
4717 0 return $self->response;
4718 }
4719  
4720 # Internal method to run either an XPath, CSS or id query against the DOM
4721 # Returns the element(s) found
4722 69 my %rename = (
4723 xpath => 'xpath',
4724 selector => 'selector',
4725 id => 'by_id',
4726 by_id => 'by_id',
4727 );
4728  
4729 sub _option_query {
4730 0 ▶ my ($self,%options) = @_;
Subroutine _option_query: not called CC=5 SCAR=34.0
4731 0 my ($method,$q);
4732 0 for my $meth (keys %rename) {
4733 0 ▶ if (exists $options{ $meth }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options{$meth}) 0 0 0
4734 0 $q = delete $options{ $meth };
4735 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
4736 }
4737 };
4738 0 _default_limiter( 'one' => \%options );
4739 0 ▶ croak "Need either a name, a selector or an xpath key!"
Branch: 1 branch
BranchTrueFalseTotal
unless $method 0 0 0
4740 if not $method;
4741 0 return $self->$method( $q, %options );
4742 };
4743  
4744 # Return the default limiter if no other limiting option is set:
4745 sub _default_limiter {
4746 0 ▶ my ($default, $options) = @_;
Subroutine _default_limiter: not called CC=2 SCAR=17.9
4747 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
4748 0 $options->{ $default } = 1;
4749 };
4750 return ()
4751 0 };
4752  
4753 =head2 C<< $mech->click_button( ... ) >>
4754  
4755 $mech->click_button( name => 'go' );
4756 $mech->click_button( input => $mybutton );
4757  
4758 Has the effect of clicking a button on the current form by specifying its
4759 name, value, or index. Its arguments are a list of key/value pairs. Only
4760 one of name, number, input or value must be specified in the keys.
4761  
4762 =over 4
4763  
4764 =item *
4765  
4766 C<name> - name of the button
4767  
4768 =item *
4769  
4770 C<value> - value of the button
4771  
4772 =item *
4773  
4774 C<input> - DOM node
4775  
4776 =item *
4777  
4778 C<id> - id of the button
4779  
4780 =item *
4781  
4782 C<number> - number of the button
4783  
4784 =back
4785  
4786 If you find yourself wanting to specify a button through its
4787 C<selector> or C<xpath>, consider using C<< ->click >> instead.
4788  
4789 =cut
4790  
4791 ▶sub click_button($self,%options) {
Subroutine click_button: not called CC=8 SCAR=42.8
Pod documented
4792 0 my $node;
4793 my $xpath;
4794 0 my $user_message;
4795 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
4796 0 $node = delete $options{ input };
4797 } elsif (exists $options{ name }) {
4798 0 my $v = delete $options{ name };
4799 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);
4800 0 $user_message = "Button name '$v' unknown";
4801 } elsif (exists $options{ value }) {
4802 0 my $v = delete $options{ value };
4803 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);
4804 0 $user_message = "Button value '$v' unknown";
4805 } elsif (exists $options{ id }) {
4806 0 my $v = delete $options{ id };
4807 0 $xpath = sprintf '//*[@id="%s"]', $v;
4808 0 $user_message = "Button id '$v' unknown";
4809 } elsif (exists $options{ number }) {
4810 0 my $v = delete $options{ number };
4811 0 $xpath = sprintf '//*[translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") = "button" or (translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") = "input" and @type="submit")][%s]', $v;
4812 0 $user_message = "Button number '$v' out of range";
4813 };
4814 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
4815 node => $self->current_form,
4816 single => 1,
4817 user_message => $user_message,
4818 );
4819 0 ▶ if ($node) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node) { } 0 0 0
4820 0 $self->click({ dom => $node, %options });
4821 } else {
4822  
4823 0 $self->signal_condition($user_message);
4824 };
4825  
4826 }
4827  
4828 =head1 FORM METHODS
4829  
4830 =head2 C<< $mech->current_form() >>
4831  
4832 print $mech->current_form->{name};
4833  
4834 Returns the current form.
4835  
4836 This method is incompatible with L<WWW::Mechanize>.
4837 It returns the DOM C<< <form> >> object and not
4838 a L<HTML::Form> instance.
4839  
4840 The current form will be reset by WWW::Mechanize::Chrome
4841 on calls to C<< ->get() >> and C<< ->get_local() >>,
4842 and on calls to C<< ->submit() >> and C<< ->submit_with_fields >>.
4843  
4844 =cut
4845  
4846 sub current_form {
4847 0 ▶ my( $self, %options )= @_;
Subroutine current_form: not called CC=2 SCAR=17.9
Pod documented
4848 # Find the first <FORM> element from the currently active element
4849 0 ▶ $self->form_number(1) unless $self->{current_form};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"current_form"} 0 0 0
4850 0 $self->{current_form};
4851 }
4852  
4853 sub clear_current_form {
4854 0 ▶ undef $_[0]->{current_form};
Subroutine clear_current_form: not called CC=1 SCAR=6.9
Pod undocumented
4855 };
4856  
4857 ▶sub invalidate_cached_values($self) {
Subroutine invalidate_cached_values: not called CC=1 SCAR=6.9
Pod undocumented
4858 0 $self->clear_current_form;
4859 0 $self->_clear_cached_document;
4860 }
4861  
4862 sub active_form {
4863 0 ▶ my( $self, %options )= @_;
Subroutine active_form: not called CC=2 SCAR=17.9
Pod undocumented
4864 # Find the first <FORM> element from the currently active element
4865 0 my $focus= $self->target->get_active_element;
4866  
4867 0 ▶ if( !$focus ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($focus) 0 0 0
4868 0 warn "No active element, hence no active form";
4869 return
4870 0 };
4871  
4872 0 my $form= $self->xpath( './ancestor-or-self::FORM', node => $focus, maybe => 1 );
4873  
4874 }
4875  
4876 =head2 C<< $mech->dump_forms( [$fh] ) >>
4877  
4878 open my $fh, '>', 'form-log.txt'
4879 or die "Couldn't open logfile 'form-log.txt': $!";
4880 $mech->dump_forms( $fh );
4881  
4882 Prints a dump of the forms on the current page to
4883 the filehandle C<$fh>. If C<$fh> is not specified or is undef, it dumps
4884 to C<STDOUT>.
4885  
4886 =cut
4887  
4888 sub dump_forms {
4889 0 ▶ my $self = shift;
Subroutine dump_forms: not called CC=8 SCAR=42.8
Pod documented
4890 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
4891  
4892 0 for my $form ( $self->forms ) {
4893 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
4894 #for my $f ($self->xpath( './/*', node => $form )) {
4895 #for my $f ($self->xpath( './/*[contains(" "+translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")+" "," input textarea button select "
4896 # )]', node => $form )) {
4897 0 for my $f ($self->xpath( './/*[contains(" input textarea button select ",concat(" ",translate(local-name(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")," "))]', node => $form )) {
4898 0 my $type;
4899 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
4900 0 $type= " ($type)";
4901 };
4902  
4903 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
4904 };
4905 }
4906 0 return;
4907 }
4908  
4909 =head2 C<< $mech->form_name( $name [, %options] ) >>
4910  
4911 $mech->form_name( 'search' );
4912  
4913 Selects the current form by its name. The options
4914 are identical to those accepted by the L<< /$mech->xpath >> method.
4915  
4916 =cut
4917  
4918 sub form_name {
4919 0 ▶ my ($self,$name,%options) = @_;
Subroutine form_name: not called CC=1 SCAR=6.9
Pod documented
4920 0 $name = quote_xpath( $name );
4921 0 _default_limiter( single => \%options );
4922 0 $self->{current_form} = $self->selector("form[name='$name']",
4923 user_info => "form name '$name'",
4924 %options
4925 );
4926 };
4927  
4928 =head2 C<< $mech->form_id( $id [, %options] ) >>
4929  
4930 $mech->form_id( 'login' );
4931  
4932 Selects the current form by its C<id> attribute.
4933 The options
4934 are identical to those accepted by the L<< /$mech->xpath >> method.
4935  
4936 This is equivalent to calling
4937  
4938 $mech->by_id($id,single => 1,%options)
4939  
4940 =cut
4941  
4942 sub form_id {
4943 0 ▶ my ($self,$name,%options) = @_;
Subroutine form_id: not called CC=1 SCAR=6.9
Pod documented
4944  
4945 0 _default_limiter( single => \%options );
4946 0 $self->{current_form} = $self->by_id($name,
4947 user_info => "form with id '$name'",
4948 %options
4949 );
4950 };
4951  
4952 =head2 C<< $mech->form_number( $number [, %options] ) >>
4953  
4954 $mech->form_number( 2 );
4955  
4956 Selects the I<number>th form.
4957 The options
4958 are identical to those accepted by the L<< /$mech->xpath >> method.
4959  
4960 =cut
4961  
4962 sub form_number {
4963 0 ▶ my ($self,$number,%options) = @_;
Subroutine form_number: not called CC=1 SCAR=6.9
Pod documented
4964  
4965 0 _default_limiter( single => \%options );
4966 0 $self->{current_form} = $self->xpath("(//form)[$number]",
4967 user_info => "form number $number",
4968 %options
4969 );
4970 0 $self->{current_form};
4971 };
4972  
4973 =head2 C<< $mech->form_with_fields( [$options], @fields ) >>
4974  
4975 $mech->form_with_fields(
4976 'user', 'password'
4977 );
4978  
4979 Find the form which has the listed fields.
4980  
4981 If the first argument is a hash reference, it's taken
4982 as options to C<< ->xpath >>.
4983  
4984 See also L<< /$mech->submit_form >>.
4985  
4986 =cut
4987  
4988 sub form_with_fields {
4989 0 ▶ my ($self,@fields) = @_;
Subroutine form_with_fields: not called CC=2 SCAR=17.9
Pod documented
4990 0 my $options = {};
4991 0 ▶ if (ref $fields[0] eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $fields[0] eq "HASH") 0 0 0
4992 0 $options = shift @fields;
4993 };
4994 0 my @clauses = map { $self->element_query([qw[input select textarea]], { 'name' => $_ })} @fields;
4995  
4996 0 my $q = "//form[" . join( " and ", @clauses)."]";
4997 #warn $q;
4998 0 _default_limiter( single => $options );
4999 0 $self->{current_form} = $self->xpath($q,
5000 user_info => "form with fields [@fields]",
5001 %$options
5002 );
5003 #warn $form;
5004 0 $self->{current_form};
5005 };
5006  
5007 =head2 C<< $mech->forms( %options ) >>
5008  
5009 my @forms = $mech->forms();
5010  
5011 When called in a list context, returns a list
5012 of the forms found in the last fetched page.
5013 In a scalar context, returns a reference to
5014 an array with those forms.
5015  
5016 The options
5017 are identical to those accepted by the L<< /$mech->selector >> method.
5018  
5019 The returned elements are the DOM C<< <form> >> elements.
5020  
5021 =cut
5022  
5023 sub forms {
5024 0 ▶ my ($self, %options) = @_;
Subroutine forms: not called CC=2 SCAR=17.9
Pod documented
5025 0 my @res = $self->selector('form', %options);
5026 return wantarray ? @res
5027 0 ▶ : \@res
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
5028 };
5029  
5030 =head2 C<< $mech->field( $selector, $value, [, $index, \@pre_events [,\@post_events]] ) >>
5031  
5032 $mech->field( user => 'joe' );
5033 $mech->field( not_empty => '', 0, [], [] ); # bypass JS validation
5034 $mech->field( date => '2020-04-01', 2 ); # set second field named "date"
5035  
5036 Sets the field with the name given in C<$selector> to the given value.
5037 Returns the value.
5038  
5039 The method understands very basic CSS selectors in the value for C<$selector>,
5040 like the L<HTML::Form> find_input() method.
5041  
5042 A selector prefixed with '#' must match the id attribute of the input.
5043 A selector prefixed with '.' matches the class attribute. A selector
5044 prefixed with '^' or with no prefix matches the name attribute.
5045  
5046 By passing the array reference C<@pre_events>, you can indicate which
5047 Javascript events you want to be triggered before setting the value.
5048 C<@post_events> contains the events you want to be triggered
5049 after setting the value.
5050  
5051 By default, the events set in the
5052 constructor for C<pre_events> and C<post_events>
5053 are triggered.
5054  
5055 =cut
5056  
5057 0 ▶sub field($self,$name,$value,$index=undef,$pre=undef,$post=undef) {
Subroutine field: not called CC=5 SCAR=34.0
Pod documented
5058 0 ▶ if( ref $index ) { # old API
Branch: 1 branch
BranchTrueFalseTotal
if (ref $index) 0 0 0
5059 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!";
5060 0 $post = $pre;
5061 0 $pre = $index;
5062 0 $index = undef;
5063 };
5064 0 $self->get_set_value(
5065 name => $name,
5066 value => $value,
5067 pre => $pre,
5068 post => $post,
5069 index => $index,
5070 node => $self->current_form,
5071 );
5072 }
5073  
5074 =head2 C<< $mech->sendkeys( %options ) >>
5075  
5076 $mech->sendkeys( string => "Hello World" );
5077  
5078 Sends a series of keystrokes. The keystrokes can be either a string or a
5079 reference to an array containing the detailed data as hashes.
5080  
5081 =over 4
5082  
5083 =item B<string> - the string to send as keystrokes
5084  
5085 =item B<keys> - reference of the array to send as keystrokes
5086  
5087 =item B<delay> - delay in ms to sleep between keys
5088  
5089 =back
5090  
5091 =cut
5092  
5093 ▶sub sendkeys_future( $self, %options ) {
Subroutine sendkeys_future: not called CC=4 SCAR=30.0
Pod undocumented
5094 $options{ keys } ||= [ map +{ type => 'char', text => $_ },
5095 split m//, $options{ string }
5096 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
5097  
5098 0 my $f = Future->done(1);
5099  
5100 0 for my $key (@{ $options{ keys }}) {
5101 $f = $f->then(sub {
5102 0 ▶ $self->target->send_message('Input.dispatchKeyEvent', %$key );
Subroutine __ANON__: not called CC=1 SCAR=6.9
5103 0 });
5104 0 ▶ if( defined $options{ delay }) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options{"delay"}) 0 0 0
5105 $f->then(sub {
5106 0 ▶ $self->sleep( $options{ delay });
Subroutine __ANON__: not called CC=1 SCAR=6.9
5107 0 });
5108 };
5109 };
5110  
5111 0 return $f
5112 };
5113  
5114 ▶sub sendkeys( $self, %options ) {
Subroutine sendkeys: not called CC=1 SCAR=6.9
Pod documented
5115 0 $self->sendkeys_future( %options )->get
5116 }
5117  
5118 =head2 C<< $mech->upload( $selector, $value ) >>
5119  
5120 $mech->upload( user_picture => 'C:/Users/Joe/face.png' );
5121  
5122 Sets the file upload field with the name given in C<$selector> to the given
5123 file. The filename must be an absolute path and filename in the local
5124 filesystem.
5125  
5126 The method understands very basic CSS selectors in the value for C<$selector>,
5127 like the C<< ->field >> method.
5128  
5129 =cut
5130  
5131 # Page.setInterceptFileChooserDialog
5132 # doesn't help anything, since we can only suppress that dialog but not
5133 # supply file names or anything. See the ->upload() method for how to actually
5134 # set filenames
5135  
5136 ▶sub upload($self,$name,$value) {
Subroutine upload: not called CC=3 SCAR=24.8
Pod documented
5137 0 my %options;
5138  
5139 0 my @fields = $self->_field_by_name(
5140 name => $name,
5141 user_info => "upload field with name '$name'",
5142 %options );
5143 0 ▶ $value = [$value]
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value 0 0 0
5144 if ! ref $value;
5145  
5146 # Stringify all files:
5147 0 @$value = map { "$_" } @$value;
5148  
5149 0 ▶ if( @fields ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@fields) 0 0 0
5150 0 $self->target->send_message('DOM.setFileInputFiles',
5151 nodeId => 0+$fields[0]->nodeId,
5152 files => $value,
5153 )->get;
5154 }
5155  
5156 }
5157  
5158  
5159 =head2 C<< $mech->value( $selector_or_element, [ $index | %options] ) >>
5160  
5161 print $mech->value( 'user' );
5162  
5163 Returns the value of the field given by C<$selector_or_name> or of the
5164 DOM element passed in.
5165  
5166 If you have multiple fields with the same name, you can use the index
5167 to specify the index directly:
5168  
5169 print $mech->value( 'date', 2 ); # get the second field named "date"
5170  
5171 The legacy form of
5172  
5173 $mech->value( name => value );
5174  
5175 is not supported anymore.
5176  
5177 For fields that can have multiple values, like a C<select> field,
5178 the method is context sensitive and returns the first selected
5179 value in scalar context and all values in list context.
5180  
5181 Note that this method does not support file uploads. See the C<< ->upload >>
5182 method for that.
5183  
5184 =cut
5185  
5186 sub value {
5187 0 ▶ if (@_ == 3) {
Subroutine value: not called CC=4 SCAR=30.0
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 3) { } 0 0 0
5188 0 my ($self,$name,$index) = @_;
5189  
5190 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
5191 0 $self->signal_condition("Non-numeric index passed to ->value(). Did you mean to call ->field('$name' => '$index') ?");
5192 };
5193  
5194 0 return $self->get_set_value(
5195 node => $self->current_form,
5196 index => $index,
5197 name => $name,
5198 );
5199  
5200 } else {
5201 0 my ($self,$name,%options) = @_;
5202 0 return $self->get_set_value(
5203 node => $self->current_form,
5204 %options,
5205 name => $name,
5206 );
5207 };
5208 };
5209  
5210 =head2 C<< $mech->get_set_value( %options ) >>
5211  
5212 Allows fine-grained access to getting/setting a value
5213 with a different API. Supported keys are:
5214  
5215 name
5216 value
5217 pre
5218 post
5219  
5220 in addition to all keys that C<< $mech->xpath >> supports.
5221  
5222 =cut
5223  
5224 sub _field_by_name {
5225 0 ▶ my ($self,%options) = @_;
Subroutine _field_by_name: not called CC=5 SCAR=34.0
5226 0 my @fields;
5227 0 my $name = delete $options{ name };
5228 0 my $attr = 'name';
5229 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
5230 0 $attr = 'name'
5231 } elsif ($name =~ s/^#//) {
5232 0 $attr = 'id'
5233 } elsif ($name =~ s/^\.//) {
5234 0 $attr = 'class'
5235 };
5236 0 ▶ if (blessed $name) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($name)) { } 0 0 0
5237 0 @fields = $name;
5238 } else {
5239 0 _default_limiter( single => \%options );
5240 0 my $query = $self->element_query([qw[input select textarea]], { $attr => $name });
5241 0 @fields = $self->xpath($query,%options);
5242 };
5243 @fields
5244 0 }
5245  
5246 =head2 C<< $mech->set_field( %options ) >>
5247  
5248 $mech->set_field(
5249 field => $field_node,
5250 value => 'foo',
5251 );
5252  
5253 Low level value setting method. Use this if you have an input element outside
5254 of a E<lt>formE<gt> tag.
5255  
5256 =cut
5257  
5258 ▶sub set_field($self, %options ) {
Subroutine set_field: not called CC=21 SCAR=61.4
Pod documented
5259 0 my $value = delete $options{ value };
5260 0 my $pre = delete $options{pre};
5261 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
5262 if (defined $pre and ! ref $pre);
5263 0 my $post = delete $options{post};
5264 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
5265 if (defined $post and ! ref $post);
5266 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
5267 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
5268 my $obj = delete $options{ field }
5269 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
5270 0 my $tag = $obj->get_tag_name();
5271  
5272 0 my %method = (
5273 input => 'value',
5274 textarea => 'content',
5275 select => 'selected',
5276 );
5277 0 my $method = $method{ lc $tag };
5278 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
5279 0 $method = 'checked';
5280 };
5281  
5282 0 my $id = $obj->objectId;
5283 0 ▶ if( ! $id ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($id) 0 0 0
5284 0 warn "No object id for nodeId " . $obj->nodeId;
5285 };
5286  
5287 # Send pre-change events:
5288 0 for my $ev (@$pre) {
5289 0 $self->target->send_message(
5290 'Runtime.callFunctionOn',
5291 objectId => $id,
5292 functionDeclaration => <<'JS',
5293 function(ev) {
5294 var event = new Event(ev, {
5295 view : window,
5296 bubbles: true,
5297 cancelable: true
5298 });
5299 this.dispatchEvent(event);
5300 }
5301 JS
5302 arguments => [{ value => $ev }],
5303 );
5304 };
5305  
5306 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
5307 0 $self->target->send_message('DOM.setAttributeValue', nodeId => 0+$obj->nodeId, name => 'value', value => "$value" )->get;
5308  
5309 } elsif( 'selected' eq $method ) {
5310 # ignoring undef; but [] would reset to no option
5311 0 ▶ if (defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) 0 0 0
5312  
5313 0 ▶ $value = [ $value ] unless ref $value;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value 0 0 0
5314 0 $self->target->send_message(
5315 'Runtime.callFunctionOn',
5316 objectId => $id,
5317 functionDeclaration => <<'JS',
5318 function(newValue) {
5319 var i, j;
5320 if (this.multiple == true) {
5321 for (i=0; i<this.options.length; i++) {
5322 this.options[i].selected = false
5323 }
5324 }
5325 for (j=0; j<newValue.length; j++) {
5326 for (i=0; i<this.options.length; i++) {
5327 if (this.options[i].value == newValue[j]) {
5328 this.options[i].selected = true
5329 }
5330 }
5331 }
5332 }
5333 JS
5334 arguments => [{ value => $value }],
5335 )->get;
5336 }
5337 } elsif( 'checked' eq $method ) {
5338 0 ▶ if (defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) 0 0 0
5339 0 ▶ $value = [ $value ] unless ref $value;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value 0 0 0
5340 0 $obj->set_attribute('checked' => JSON::true);
5341 }
5342 } elsif( 'content' eq $method ) {
5343 0 $self->target->send_message('Runtime.callFunctionOn',
5344 objectId => $id,
5345 functionDeclaration => 'function(newValue) { this.innerHTML = newValue }',
5346 arguments => [{ value => $value }]
5347 )->get;
5348 } else {
5349 0 die "Don't know how to set the value for node '$tag', sorry";
5350 };
5351  
5352 # Send post-change events
5353 # Send pre-change events:
5354 0 for my $ev (@$post) {
5355 0 $self->target->send_message(
5356 'Runtime.callFunctionOn',
5357 objectId => $id,
5358 functionDeclaration => <<'JS',
5359 function(ev) {
5360 var event = new Event(ev, {
5361 view : window,
5362 bubbles: true,
5363 cancelable: true
5364 });
5365 this.dispatchEvent(event);
5366 }
5367 JS
5368 arguments => [{ value => $ev }],
5369 );
5370 };
5371 }
5372  
5373 ▶sub get_set_value($self,%options) {
Subroutine get_set_value: not called CC=20 SCAR=60.4
Pod documented
5374 0 my $set_value = exists $options{ value };
5375 0 my $value = delete $options{ value };
5376 0 my $pre = delete $options{pre};
5377 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
5378 if (defined $pre and ! ref $pre);
5379 0 my $post = delete $options{post};
5380 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
5381 if (defined $post and ! ref $post);
5382 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
5383 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
5384 0 my $name = delete $options{ name };
5385 0 my $index = delete $options{ index };
5386  
5387 0 my $index_name = '';
5388 0 ▶ if( defined $index ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $index) 0 0 0
5389 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
5390 0 $index_name = "${index}st ";
5391  
5392 ▶ } 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
5393 0 $index_name = "${index}nd ";
5394  
5395 ▶ } 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
5396 0 $index_name = "${index}rd ";
5397  
5398 } else {
5399 0 $index_name = "${index}th ";
5400 }
5401 };
5402 0 my @fields = $self->_field_by_name(
5403 name => $name,
5404 user_info => "${index_name}input with name '$name'",
5405 index => $index,
5406 %options );
5407  
5408 0 ▶ if (my $obj = $fields[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $obj = $fields[0]) { } 0 0 0
5409  
5410 0 ▶ if ($set_value) {
Branch: 1 branch
BranchTrueFalseTotal
if ($set_value) 0 0 0
5411 0 $self->set_field(
5412 field => $obj,
5413 value => $value,
5414 pre => $pre,
5415 post => $post,
5416 );
5417 };
5418  
5419 # Don't bother to fetch the field's value if it's not wanted
5420 0 ▶ return unless defined wantarray;
Branch: 1 branch
BranchTrueFalseTotal
unless defined wantarray 0 0 0
5421  
5422 # We could save some work here for the simple case of single-select
5423 # dropdowns by not enumerating all options
5424 0 my $tag = $obj->get_tag_name();
5425 0 ▶ if ('SELECT' eq uc $tag) {
Branch: 1 branch
BranchTrueFalseTotal
if ('SELECT' eq uc $tag) { } 0 0 0
5426 0 my $id = $obj->objectId;
5427 0 ▶ if( ! $id ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($id) 0 0 0
5428 0 warn "No object id for nodeId " . $obj->nodeId;
5429 };
5430 my $arr = $self->target->send_message(
5431 'Runtime.callFunctionOn',
5432 objectId => $id,
5433 functionDeclaration => <<'JS',
5434 function() {
5435 var i;
5436 var arr = [];
5437 for (i=0; i<this.options.length; i++) {
5438 if (this.options[i].selected == true) {
5439 arr.push(this.options[i].value);
5440 }
5441 }
5442 return arr;
5443 }
5444 JS
5445 arguments => [],
5446 0 returnByValue => JSON::true)->get->{result};
5447  
5448 0 my @values = @{$arr->{value}};
5449 0 ▶ if (wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 0 0
5450 return @values
5451 0 } else {
5452 0 return $values[0];
5453 }
5454 } else {
5455 0 return $obj->get_attribute('value', live => 1);
5456 };
5457 } else {
5458 return
5459 0 }
5460 }
5461  
5462 =head2 C<< $mech->select( $name, $value ) >>
5463  
5464 =head2 C<< $mech->select( $name, \@values ) >>
5465  
5466 $mech->select( 'items', 'banana' );
5467  
5468 Given the name of a C<select> field, set its value to the value
5469 specified. If the field is not C<< <select multiple> >> and the
5470 C<$value> is an array, only the B<first> value will be set.
5471 Passing C<$value> as a hash with
5472 an C<n> key selects an item by number (e.g.
5473 C<< {n => 3} >> or C<< {n => [2,4]} >>).
5474 The numbering starts at 1. This applies to the current form.
5475  
5476 If you have a field with C<< <select multiple> >> and you pass a single
5477 C<$value>, then C<$value> will be added to the list of fields selected,
5478 without clearing the others. However, if you pass an array reference,
5479 then all previously selected values will be cleared.
5480  
5481 Returns true on successfully setting the value. On failure, returns
5482 false and calls C<< $self>warn() >> with an error message.
5483  
5484 =cut
5485  
5486 ▶sub select($self, $name, $value) {
Subroutine select: not called CC=16 SCAR=56.1
Pod documented
5487 0 my $field;
5488 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
5489 0 ($field) = $self->_field_by_name(
5490 node => $self->current_form,
5491 name => $name,
5492 #%options,
5493 );
5494 0 1;
5495 }) {
5496 # the field was not found
5497 0 return;
5498 };
5499  
5500 0 my @options = $self->xpath( './/option', node => $field);
5501 0 my @by_index;
5502 my @by_value;
5503 0 my $single = $field->get_attribute('type', live => 1) eq "select-one";
5504 0 my $deselect;
5505  
5506 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
5507 0 for (keys %$value) {
5508 0 ▶ $self->warn(qq{Unknown select value parameter "$_"})
Branch: 1 branch
BranchTrueFalseTotal
unless $_ eq "n" 0 0 0
5509 unless $_ eq 'n';
5510 }
5511  
5512 0 $deselect = ref $value->{n};
5513 0 ▶ @by_index = ref $value->{n} ? @{ $value->{n} } : $value->{n};
Branch: 1 branch
BranchTrueFalseTotal
ref $value->{'n'} ? : 0 0 0
5514 ▶ } 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
5515 # clear all preselected values
5516 0 $deselect = 1;
5517 0 @by_value = @{ $value };
5518 } else {
5519 0 @by_value = $value;
5520 };
5521  
5522 0 ▶ if ($deselect) {
Branch: 1 branch
BranchTrueFalseTotal
if ($deselect) 0 0 0
5523 0 for my $o (@options) {
5524 0 $o->{selected} = 0;
5525 }
5526 };
5527  
5528 0 ▶ if ($single) {
Branch: 1 branch
BranchTrueFalseTotal
if ($single) 0 0 0
5529 # Only use the first element for single-element boxes
5530 0 ▶ $#by_index = 0+@by_index ? 0 : -1;
Branch: 1 branch
BranchTrueFalseTotal
0 + @by_index ? : 0 0 0
5531 0 ▶ $#by_value = 0+@by_value ? 0 : -1;
Branch: 1 branch
BranchTrueFalseTotal
0 + @by_value ? : 0 0 0
5532 };
5533  
5534 # Select the items, either by index or by value
5535 0 for my $idx (@by_index) {
5536 0 $options[$idx-1]->set_attribute('selected' => 1 );
5537 };
5538  
5539 0 for my $v (@by_value) {
5540 0 my $option = $self->xpath( sprintf( './/option[@value="%s"]', quote_xpath( $v )) , node => $field, single => 1 );
5541 0 $option->set_attribute( 'selected' => '1' );
5542 };
5543  
5544 0 return @by_index + @by_value > 0;
5545 }
5546  
5547 =head2 C<< $mech->tick( $name, $value [, $set ] ) >>
5548  
5549 $mech->tick("confirmation_box", 'yes');
5550  
5551 "Ticks" the first checkbox that has both the name and value associated with it
5552 on the current form. Dies if there is no named check box for that value.
5553 Passing in a false value as the third optional argument will cause the
5554 checkbox to be unticked.
5555  
5556 (Un)ticking the checkbox is done by sending a click event to it if needed.
5557 If C<$value> is C<undef>, the first checkbox matching C<$name> will
5558 be (un)ticked.
5559  
5560 If C<$name> is a reference to a hash, that hash will be used
5561 as the options to C<< ->find_link_dom >> to find the element.
5562  
5563 =cut
5564  
5565 0 ▶sub tick($self, $name, $value=undef, $set=1) {
Subroutine tick: not called CC=18 SCAR=58.3
Pod documented
5566 0 my %options;
5567 my @boxes;
5568  
5569 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
5570 0 croak("->tick called with undef name");
5571 ▶ } 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
5572 0 $options{ dom } = $name;
5573 } elsif (ref $name eq 'HASH') { # options
5574 0 %options = %$name;
5575 } else {
5576 0 $options{ name } = $name;
5577 };
5578  
5579 0 ▶ if (exists $options{ name }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options{"name"}) 0 0 0
5580 0 my $attr = 'name';
5581 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
5582 0 $attr = 'name'
5583 } elsif ($name =~ s/^#//) {
5584 0 $attr = 'id'
5585 } elsif ($name =~ s/^\.//) {
5586 0 $attr = 'class'
5587 };
5588 0 $name = quotemeta($name);
5589 0 ▶ $value = quotemeta($value) if $value;
Branch: 1 branch
BranchTrueFalseTotal
if $value 0 0 0
5590  
5591 0 _default_limiter( one => \%options );
5592 0 my $q = $self->element_query(
5593 ['input'],
5594 {
5595 $attr => $name,
5596 type => 'checkbox',
5597 maybe value => $value,
5598 }
5599 );
5600 0 $options{ xpath } = $q;
5601 #$options{ xpath } = [
5602 # defined $value
5603 # ? sprintf( q{//input[@type="checkbox" and @%s="%s" and @value="%s"]}, $attr, $name, $value)
5604 # : sprintf( q{//input[@type="checkbox" and @%s="%s"]}, $attr, $name)
5605 #];
5606 0 ▶ $options{ user_info } = defined $value
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 0 0 0
5607 ? "Checkbox with name '$name' and value '$value'"
5608 : "Checkbox with name '$name'";
5609 };
5610  
5611 0 ▶ if ($options{ dom }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{'dom'}) { } 0 0 0
5612 0 @boxes = $options{ dom };
5613 } else {
5614 0 @boxes = $self->_option_query(%options);
5615 };
5616  
5617 0 my $target = $boxes[0];
5618 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
5619 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
5620 0 ▶ if ($set) {
Branch: 1 branch
BranchTrueFalseTotal
if ($set) { } 0 0 0
5621 0 $target->set_attribute('checked', 'checked');
5622 } else {
5623 0 $target->set_attribute('checked', undef);
5624 };
5625 };
5626 };
5627  
5628 =head2 C<< $mech->untick( $name, $value ) >>
5629  
5630 $mech->untick('spam_confirm','yes',undef)
5631  
5632 Causes the checkbox to be unticked. Shorthand for
5633  
5634 $mech->tick($name,$value,undef)
5635  
5636 =cut
5637  
5638 sub untick {
5639 0 ▶ my ($self, $name, $value) = @_;
Subroutine untick: not called CC=1 SCAR=6.9
Pod documented
5640 0 $self->tick( $name, $value, undef );
5641 };
5642  
5643 =head2 C<< $mech->submit( $form ) >>
5644  
5645 $mech->submit;
5646  
5647 Submits the form. Note that this does B<not> fire the C<onClick>
5648 event and thus also does not fire eventual Javascript handlers.
5649 Maybe you want to use C<< $mech->click >> instead.
5650  
5651 The default is to submit the current form as returned
5652 by C<< $mech->current_form >>.
5653  
5654 =cut
5655  
5656 0 ▶sub submit($self,$dom_form = $self->current_form) {
Subroutine submit: not called CC=3 SCAR=24.8
Pod documented
5657 0 ▶ if ($dom_form) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dom_form) { } 0 0 0
5658 # We should prepare for navigation here as well
5659 # The __proto__ invocation is so we can have a HTML form field entry
5660 # named "submit"
5661  
5662 $self->_mightNavigate( sub {
5663 0 ▶ $self->target->send_message(
Subroutine __ANON__: not called CC=1 SCAR=6.9
5664 'Runtime.callFunctionOn',
5665 objectId => $dom_form->objectId,
5666 functionDeclaration => 'function() { var action = this.action; var isCallable = action && typeof(action) === "function"; if( isCallable) { action() } else { this.__proto__.submit.apply(this) }}'
5667 );
5668 })
5669 0 ->get;
5670  
5671 0 $self->invalidate_cached_values;
5672 } else {
5673 0 croak "I don't know which form to submit, sorry.";
5674 }
5675 0 return $self->response;
5676 };
5677  
5678 =head2 C<< $mech->submit_form( %options ) >>
5679  
5680 $mech->submit_form(
5681 with_fields => {
5682 user => 'me',
5683 pass => 'secret',
5684 }
5685 );
5686  
5687 This method lets you select a form from the previously fetched page,
5688 fill in its fields, and submit it. It combines the form_number/form_name,
5689 C<< ->set_fields >> and C<< ->click methods >> into one higher level call. Its
5690 arguments are a list of key/value pairs, all of which are optional.
5691  
5692 =over 4
5693  
5694 =item *
5695  
5696 C<< form => $mech->current_form() >>
5697  
5698 Specifies the form to be filled and submitted. Defaults to the current form.
5699  
5700 =item *
5701  
5702 C<< fields => \%fields >>
5703  
5704 Specifies the fields to be filled in the current form
5705  
5706 =item *
5707  
5708 C<< with_fields => \%fields >>
5709  
5710 Probably all you need for the common case. It combines a smart form selector
5711 and data setting in one operation. It selects the first form that contains
5712 all fields mentioned in \%fields. This is nice because you don't need to
5713 know the name or number of the form to do this.
5714  
5715 (calls L<< /$mech->form_with_fields() >> and L<< /$mech->set_fields() >>).
5716  
5717 If you choose this, the form_number, form_name, form_id and fields options
5718 will be ignored.
5719  
5720 =back
5721  
5722 =cut
5723  
5724 ▶sub submit_form($self,%options) {;
Subroutine submit_form: not called CC=9 SCAR=45.0
Pod documented
5725  
5726 0 my $form = delete $options{ form };
5727 0 my $fields;
5728 0 ▶ if (! $form) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($form) 0 0 0
5729 0 ▶ if ($fields = delete $options{ with_fields }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fields = delete $options{'with_fields'}) { } 0 0 0
5730 0 my @names = keys %$fields;
5731 0 $form = $self->form_with_fields( \%options, @names );
5732 0 ▶ if (! $form) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($form) 0 0 0
5733 0 $self->signal_condition("Couldn't find a matching form for @names.");
5734 return
5735 0 };
5736 } else {
5737 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
5738 0 $form = $self->current_form;
5739 };
5740 };
5741  
5742 0 ▶ if (! $form) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($form) 0 0 0
5743 0 $self->signal_condition("No form found to submit.");
5744 return
5745 0 };
5746 #warn Dumper $fields;
5747 #$self->log('debug', sprintf 'Submitting form %s with fields %s', $form->{id}, Dumper $fields);
5748 0 $self->do_set_fields( form => $form, fields => $fields );
5749  
5750 0 my $response;
5751 0 ▶ if ( $options{button} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{'button'}) { } 0 0 0
5752 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
5753 }
5754 else {
5755 0 $response = $self->submit();
5756 }
5757 0 return $response;
5758  
5759 }
5760  
5761 =head2 C<< $mech->set_fields( $name => $value, ... ) >>
5762  
5763 $mech->set_fields(
5764 user => 'me',
5765 pass => 'secret',
5766 );
5767  
5768 This method sets multiple fields of the current form. It takes a list of
5769 field name and value pairs. If there is more than one field with the same
5770 name, the first one found is set. If you want to select which of the
5771 duplicate field to set, use a value which is an anonymous array which
5772 has the field value and its number as the 2 elements.
5773  
5774 $mech->set_fields(
5775 user => 'me',
5776 pass => 'secret',
5777 pass => [ 'secret', 2 ], # repeated password field
5778 );
5779  
5780 =cut
5781  
5782 ▶sub set_fields($self, %fields) {;
Subroutine set_fields: not called CC=2 SCAR=17.9
Pod documented
5783 0 my $f = $self->current_form;
5784 0 ▶ if (! $f) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($f) 0 0 0
5785 0 croak "Can't set fields: No current form set.";
5786 };
5787 0 $self->do_set_fields(form => $f, fields => \%fields);
5788 };
5789  
5790 ▶sub do_set_fields($self, %options) {
Subroutine do_set_fields: not called CC=3 SCAR=24.8
Pod undocumented
5791 0 my $form = delete $options{ form };
5792 0 my $fields = delete $options{ fields };
5793  
5794 0 ▶ while (my($n,$v) = each %$fields) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$fields) 0 0 0
5795 0 my $index = undef;
5796 0 ▶ if (ref $v) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v) 0 0 0
5797 0 ($v,my $num) = @$v;
5798 0 $index = $num;
5799 };
5800  
5801 0 $self->get_set_value( node => $form, name => $n, value => $v, index => $index, %options );
5802 }
5803 };
5804  
5805 =head1 CONTENT MONITORING METHODS
5806  
5807 =head2 C<< $mech->is_visible( $element ) >>
5808  
5809 =head2 C<< $mech->is_visible( %options ) >>
5810  
5811 if ($mech->is_visible( selector => '#login' )) {
5812 print "You can log in now.";
5813 };
5814  
5815 Returns true if the element is visible, that is, it is
5816 a member of the DOM and neither it nor its ancestors have
5817 a CSS C<visibility> attribute of C<hidden> or
5818 a C<display> attribute of C<none>.
5819  
5820 You can either pass in a DOM element or a set of key/value
5821 pairs to search the document for the element you want.
5822  
5823 =over 4
5824  
5825 =item *
5826  
5827 C<xpath> - the XPath query
5828  
5829 =item *
5830  
5831 C<selector> - the CSS selector
5832  
5833 =item *
5834  
5835 C<dom> - a DOM node
5836  
5837 =back
5838  
5839 The remaining options are passed through to either the
5840 L<< /$mech->xpath|xpath >> or L<< /$mech->selector|selector >> method.
5841  
5842 =cut
5843  
5844 sub is_visible {
5845 0 ▶ my( $self, @args ) = @_;
Subroutine is_visible: not called CC=5 SCAR=34.0
Pod documented
5846 0 my %options;
5847 0 ▶ if (2 == @_) {
Branch: 1 branch
BranchTrueFalseTotal
if (2 == @_) { } 0 0 0
5848 0 ($self,$options{dom}) = @_;
5849 } else {
5850 0 ($self,%options) = @_;
5851 };
5852 0 _default_limiter( 'maybe', \%options );
5853 0 ▶ if (! $options{dom}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options{"dom"}) 0 0 0
5854 0 $options{dom} = $self->_option_query(%options);
5855 };
5856 # No element means not visible
5857 return
5858 0 ▶ unless $options{ dom };
Branch: 1 branch
BranchTrueFalseTotal
unless $options{"dom"} 0 0 0
5859 #$options{ window } ||= $self->tab->{linkedBrowser}->{contentWindow};
5860  
5861 0 my $id = $options{ dom }->objectId;
5862 0 my ($val, $type) = $self->callFunctionOn(<<'JS', objectId => $id, arguments => []); #->get;
5863 function ()
5864 {
5865 var obj = this;
5866 while (obj) {
5867 // No object
5868 if (!obj) return false;
5869  
5870 try {
5871 if( obj["parentNode"] ) 1;
5872 } catch (e) {
5873 // Dead object
5874 return false
5875 };
5876 // Descends from document, so we're done
5877 if (obj.parentNode === obj.ownerDocument) {
5878 return true;
5879 };
5880 // Not in the DOM
5881 if (!obj.parentNode) {
5882 return false;
5883 };
5884 // Direct style check
5885 if (obj.style) {
5886 if (obj.style.display == 'none') return false;
5887 if (obj.style.visibility == 'hidden') return false;
5888 };
5889  
5890 if (window.getComputedStyle) {
5891 var style = window.getComputedStyle(obj, null);
5892 if (style.display == 'none') {
5893 return false; }
5894 if (style.visibility == 'hidden') {
5895 return false;
5896 };
5897 };
5898 obj = obj.parentNode;
5899 };
5900 // The object does not live in the DOM at all
5901 return false
5902 }
5903 JS
5904 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
5905 or die "Don't know how to handle Javascript type '$type'";
5906 0 return $val
5907 };
5908  
5909 =head2 C<< $mech->wait_until_invisible( $element ) >>
5910  
5911 =head2 C<< $mech->wait_until_invisible( %options ) >>
5912  
5913 $mech->wait_until_invisible( $please_wait );
5914  
5915 Waits until an element is not visible anymore.
5916  
5917 Takes the same options as L<< $mech->is_visible/->is_visible >>.
5918  
5919 In addition, the following options are accepted:
5920  
5921 =over 4
5922  
5923 =item *
5924  
5925 C<timeout> - the timeout after which the function will C<croak>. To catch
5926 the condition and handle it in your calling program, use an L<eval> block.
5927 A timeout of C<0> means to never time out.
5928  
5929 See also C<max_wait> if you want to wait a limited time for an element to
5930 appear.
5931  
5932 =item *
5933  
5934 C<max_wait> - the maximum time to wait until the function will return.
5935 A max_wait of C<0> means to never time out. If the element is still visible,
5936 the function will return a false value.
5937  
5938 =item *
5939  
5940 C<sleep> - the interval in seconds used to L<sleep>. Subsecond
5941 intervals are possible.
5942  
5943 =back
5944  
5945 Note that when passing in a selector, that selector is requeried
5946 on every poll instance. So the following query will work as expected:
5947  
5948 xpath => '//*[contains(text(),"stand by")]'
5949  
5950 This also means that if your selector query relies on finding
5951 a changing text, you need to pass the node explicitly instead of
5952 passing the selector.
5953  
5954 =cut
5955  
5956 sub wait_until_invisible {
5957 0 ▶ my( $self, %options );
Subroutine wait_until_invisible: not called CC=16 SCAR=56.1
Pod documented
5958 0 ▶ if (2 == @_) {
Branch: 1 branch
BranchTrueFalseTotal
if (2 == @_) { } 0 0 0
5959 0 ($self,$options{dom}) = @_;
5960 } else {
5961 0 ($self,%options) = @_;
5962 };
5963 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
5964 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
5965 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
5966 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
5967  
5968 0 _default_limiter( 'maybe', \%options );
5969  
5970 0 my $timeout_after;
5971 0 ▶ if ($timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if ($timeout) 0 0 0
5972 0 $timeout_after = time + $timeout;
5973 };
5974 0 my $v;
5975 my $node;
5976 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
5977 0 $node = $options{ dom };
5978 0 ▶ if (! $node) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($node) 0 0 0
5979 0 $node = $self->_option_query(%options);
5980 };
5981 return
5982 0 ▶ unless $node;
Branch: 1 branch
BranchTrueFalseTotal
unless $node 0 0 0
5983 0 $self->sleep( $sleep );
5984  
5985 # If $node goes away due to a page reload, ->is_visible could die:
5986 0 $v = eval { $self->is_visible($node) };
5987 } while ( $v
5988 and (!$timeout or time < $timeout_after ));
5989 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
5990 0 ▶ if( $wait ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wait) { } 0 0 0
5991 return()
5992 0 } else {
5993 0 croak "Timeout of $timeout seconds reached while waiting for element to become invisible";
5994 };
5995 };
5996 0 return 1;
5997 };
5998  
5999 =head2 C<< $mech->wait_until_visible( %options ) >>
6000  
6001 $mech->wait_until_visible( selector => 'a.download' );
6002  
6003 Waits until an query returns a visible element.
6004  
6005 Takes the same options as L<< $mech->is_visible/->is_visible >>.
6006  
6007 In addition, the following options are accepted:
6008  
6009 =over 4
6010  
6011 =item *
6012  
6013 C<timeout> - the timeout after which the function will C<croak>. To catch
6014 the condition and handle it in your calling program, use an L<eval> block.
6015 A timeout of C<0> means to never time out.
6016  
6017 =item *
6018  
6019 C<sleep> - the interval in seconds used to L<sleep>. Subsecond
6020 intervals are possible.
6021  
6022 =back
6023  
6024 Note that when passing in a selector, that selector is requeried
6025 on every poll instance. So the following query will work as expected:
6026  
6027 xpath => '//*[contains(text(),"click here for download")]'
6028  
6029 =cut
6030  
6031 ▶sub wait_until_visible( $self, %options ) {
Subroutine wait_until_visible: not called CC=8 SCAR=42.8
Pod documented
6032 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
6033 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
6034  
6035 0 _default_limiter( 'any', \%options );
6036  
6037 0 my $timeout_after;
6038 0 ▶ if ($timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if ($timeout) 0 0 0
6039 0 $timeout_after = time + $timeout;
6040 };
6041 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
6042 # If $node goes away due to a page reload, ->is_visible could die:
6043 my @nodes =
6044 0 grep { eval { $self->is_visible( dom => $_ ) } }
6045 $self->_option_query(%options);
6046  
6047 0 ▶ if( @nodes ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@nodes) 0 0 0
6048 return @nodes
6049 0 };
6050 0 $self->sleep( $sleep );
6051 } while (!$timeout_after or time < $timeout_after );
6052 0 ▶ if (time >= $timeout_after) {
Branch: 1 branch
BranchTrueFalseTotal
if (time >= $timeout_after) 0 0 0
6053 0 croak "Timeout of $timeout seconds reached while waiting for element to become invisible";
6054 };
6055 };
6056  
6057 =head1 CONTENT RENDERING METHODS
6058  
6059 =head2 C<< $mech->content_as_png() >>
6060  
6061 my $png_data = $mech->content_as_png();
6062  
6063 # Create scaled-down 480px wide preview
6064 my $png_data = $mech->content_as_png(undef, { width => 480 });
6065  
6066 Returns the given tab or the current page rendered as PNG image.
6067  
6068 All parameters are optional.
6069  
6070 =over 4
6071  
6072 =back
6073  
6074 This method is specific to WWW::Mechanize::Chrome.
6075  
6076 =cut
6077  
6078 ▶sub _as_raw_png( $self, $image ) {
Subroutine _as_raw_png: not called CC=1 SCAR=6.9
6079 0 my $data;
6080 0 $image->write( data => \$data, type => 'png' );
6081 0 $data
6082 }
6083  
6084 0 ▶sub _content_as_png($self, $rect={}, $target={} ) {
Subroutine _content_as_png: not called CC=7 SCAR=40.3
6085 0 ▶ if( !keys $rect->%* ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not keys %$rect) { } 0 0 0
6086 0 undef $rect;
6087 } else {
6088 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
6089  
6090 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
6091 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
6092 };
6093 ▶ $self->target->send_message('Page.captureScreenshot',
Subroutine __ANON__: not called CC=6 SCAR=37.4
6094 format => 'png',
6095 maybe clip => $rect,
6096 captureBeyondViewport => JSON::true
6097 )->then( sub( $res ) {
6098 0 require Imager;
6099 0 my $img = Imager->new ( data => decode_base64( $res->{data} ), format => 'png' );
6100 # Cut out the wanted part
6101 0 ▶ if( scalar keys %$rect) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %$rect) 0 0 0
6102 0 $img = $img->crop( %$rect );
6103 };
6104 # Resize image to width/height
6105 0 ▶ if( scalar keys %$target) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %$target) 0 0 0
6106 0 my %args;
6107 $args{ ypixels } = $target->{ height }
6108 0 ▶ if $target->{height};
Branch: 1 branch
BranchTrueFalseTotal
if $target->{"height"} 0 0 0
6109 $args{ xpixels } = $target->{ width }
6110 0 ▶ if $target->{width};
Branch: 1 branch
BranchTrueFalseTotal
if $target->{"width"} 0 0 0
6111 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
6112 0 $img = $img->scale( %args );
6113 };
6114 0 return Future->done( $img )
6115 0 });
6116 };
6117  
6118  
6119 0 ▶sub content_as_png($self, $rect={}, $target={}) {
Subroutine content_as_png: not called CC=3 SCAR=24.8
Pod documented
6120 0 my $img = $self->_content_as_png( $rect, $target )->get;
6121 0 return $self->_as_raw_png( $img );
6122 };
6123  
6124 ▶sub getResourceTree_future( $self ) {
Subroutine getResourceTree_future: not called CC=1 SCAR=6.9
Pod undocumented
6125 ▶ $self->target->send_message( 'Page.getResourceTree' )
Subroutine __ANON__: not called CC=1 SCAR=6.9
6126 ->then( sub( $result ) {
6127 Future->done( $result->{frameTree} )
6128 0 })
6129 0 }
6130  
6131 0 ▶sub getResourceContent_future( $self, $url_or_resource, $frameId=$self->frameId, %additional ) {
Subroutine getResourceContent_future: not called CC=4 SCAR=30.0
Pod undocumented
6132 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
6133 0 ▶ %additional = (%$url_or_resource,%additional) if ref $url_or_resource;
Branch: 1 branch
BranchTrueFalseTotal
if ref $url_or_resource 0 0 0
6134 ▶ $self->target->send_message( 'Page.getResourceContent', frameId => $frameId, url => $url )
Subroutine __ANON__: not called CC=2 SCAR=17.9
6135 ->then( sub( $result ) {
6136 0 ▶ if( delete $result->{base64Encoded}) {
Branch: 1 branch
BranchTrueFalseTotal
if (delete $result->{'base64Encoded'}) { } 0 0 0
6137 $result->{content} = decode_base64( $result->{content} )
6138 0 } else {
6139 0 $result->{_utf8} = 1;
6140 };
6141 0 %$result = (%additional, %$result);
6142 0 Future->done( $result )
6143 })
6144 0 }
6145  
6146 # Replace that later with MIME::Detect
6147 69 our %extensions = (
6148 'image/jpeg' => '.jpg',
6149 'image/png' => '.png',
6150 'image/gif' => '.gif',
6151 'text/html' => '.html',
6152 'text/plain' => '.txt',
6153 'text/stylesheet' => '.css',
6154 'text/javascript' => '.js',
6155 'application/javascript' => '.js',
6156 );
6157  
6158 ▶sub _saveResourceTree( $self, $tree, $names, $seen, $wanted, $save, $base_dir ) {
Subroutine _saveResourceTree: not called CC=10 SCAR=47.0
6159 0 my @requested;
6160 # Also fetch the frame itself?!
6161 # Or better reuse ->content?!
6162 # $tree->{frame}
6163 # build the map from URLs to file names
6164 # This should become a separate method
6165 # Also something like get_page_resources, that returns the linear
6166 # list of resources for all frames etc.
6167 my @wanted;
6168 0 for my $res ($tree->{frame}, @{ $tree->{resources}}) {
6169 0 ▶ if( $seen->{ $res->{url} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$seen{$res->{"url"}}) 0 0 0
6170 #warn "Skipping $res->{url} (already saved)";
6171 0 next;
6172 };
6173 0 ▶ if( !$wanted->($res) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&$wanted($res)) 0 0 0
6174 #warn "Don't want $res->{url}";
6175 0 next;
6176 };
6177 #warn "Do want $res->{url}";
6178  
6179 0 my $target;
6180 0 ▶ if( exists $names->{ $res->{url}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $$names{$res->{'url'}}) { } 0 0 0
6181 # User-specified names always take precedence
6182 0 $target = $names->{ $res->{url}};
6183 0 $names->{ $res->{url} } = $target;
6184  
6185 } else {
6186 # find a non-duplicate name
6187 0 $target = $self->filenameFromUrl( $res->{url}, $extensions{ $res->{mimeType} });
6188 0 my %filenames = reverse %$names;
6189  
6190 0 my $duplicates;
6191 0 my $old_target = $target;
6192 0 ▶ while( $filenames{ $target }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($filenames{$target}) 0 0 0
6193 0 $duplicates++;
6194 0 ( $target = $old_target )=~ s!\.(\w+)$!_$duplicates.$1!;
6195 };
6196 0 $names->{ $res->{url} } = File::Spec->catfile( $base_dir, $target );
6197 };
6198  
6199 0 push @wanted, $res;
6200 };
6201  
6202 # retrieve and save the resource content for each resource
6203 0 for my $res (@wanted) {
6204 0 my $fetch = $self->getResourceContent_future( $res );
6205 0 ▶ if( $save ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($save) 0 0 0
6206 #warn "Will save $res->{url}";
6207 $fetch = $fetch->then( $save )->else(sub {
6208 0 ▶ warn "Fetch failed:";
Subroutine __ANON__: not called CC=1 SCAR=6.9
6209 0 warn "@_";
6210 0 });
6211 };
6212 0 push @requested, $fetch;
6213 };
6214  
6215 # recurse through the subframes
6216 0 ▶ if( my $t = $tree->{childFrames}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $t = $tree->{"childFrames"}) 0 0 0
6217 0 for my $child (@$t) {
6218 0 push @requested, $self->_saveResourceTree( $child, $names, $seen, $wanted, $save, $base_dir );
6219 };
6220 };
6221  
6222 return Future->wait_all( @requested )->catch(sub {
6223 0 ▶ warn $@;
Subroutine __ANON__: not called CC=1 SCAR=6.9
6224 0 });
6225 }
6226  
6227 # Allow the options to specify whether to filter duplicates here
6228 ▶sub fetchResources_future( $self, %options ) {
Subroutine fetchResources_future: not called CC=6 SCAR=37.4
Pod undocumented
6229 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
6230 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
6231 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
6232 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
6233 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) {
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
6234 0 my $seen = $options{ seen };
6235 0 my $names = $options{ names };
6236 0 my $wanted = $options{ wanted };
6237 0 my $save = $options{ save };
6238 0 my $base_dir = $options{ target_dir };
6239  
6240 0 my $s = $self;
6241 0 weaken $s;
6242  
6243 ▶ $self->getResourceTree_future
Subroutine __ANON__: not called CC=1 SCAR=6.9
6244 ->then( sub( $tree ) {
6245 0 $s->_saveResourceTree($tree, $names, $seen, $wanted, $save, $base_dir);
6246 })->catch(sub {
6247 0 ▶ warn @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
6248 0 });
6249 }
6250  
6251 =head2 C<< $mech->saveResources_future >>
6252  
6253 my $file_map = $mech->saveResources_future(
6254 target_file => 'this_page.html',
6255 target_dir => 'this_page_files/',
6256 wanted => sub { $_[0]->{url} =~ m!^https?:!i },
6257 )->get();
6258  
6259 Rough prototype of "Save Complete Page" feature
6260  
6261 =cut
6262  
6263 ▶sub saveResources_future( $self, %options ) {
Subroutine saveResources_future: not called CC=5 SCAR=34.0
Pod documented
6264 my $target_file = $options{ target_file }
6265 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
6266 0 my $target_dir = $options{ target_dir };
6267 0 ▶ if( ! defined $target_dir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $target_dir) 0 0 0
6268 0 ($target_dir = $target_file) =~ s!\.\w+$! files!i;
6269 };
6270 0 ▶ if( not -e $target_dir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $target_dir) 0 0 0
6271 0 ▶ mkdir $target_dir
Branch: 1 branch
BranchTrueFalseTotal
mkdir $target_dir or croak("Couldn't create '${target_dir}': $!") 0 0 0
6272 or croak "Couldn't create '$target_dir': $!";
6273 }
6274  
6275 0 my %names = (
6276 $self->uri => $target_file,
6277 );
6278 0 my $s = $self;
6279 0 weaken $s;
6280 $self->fetchResources_future(
6281 names => \%names,
6282 seen => \my %seen,
6283 target_dir => $target_dir,
6284 maybe wanted => $options{ wanted },
6285 ▶ save => sub( $resource ) {
Subroutine __ANON__: not called CC=5 SCAR=34.0
6286 # For mime/html targets without a name, use the title?!
6287 # Rewrite all HTML, CSS links
6288  
6289 # We want to store the top HTML under the name passed in (!)
6290 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
6291 my $target = $names{ $resource->{url} }
6292 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
6293 0 $s->log( 'debug', "Saving '$resource->{url}' to '$target'" );
6294 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
6295 or croak "Couldn't save url '$resource->{url}' to $target: $!";
6296 0 ▶ if( $resource->{_utf8}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($resource->{'_utf8'}) { } 0 0 0
6297 0 binmode $fh, ':encoding(UTF-8)';
6298 } else {
6299 0 binmode $fh;
6300 };
6301  
6302 0 print $fh $resource->{content};
6303 0 CORE::close( $fh );
6304  
6305 0 Future->done( $resource );
6306 },
6307 ▶ )->then( sub( @resources ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
6308 0 Future->done( \%names );
6309 })->catch(sub {
6310 0 ▶ warn $@;
Subroutine __ANON__: not called CC=1 SCAR=6.9
6311 0 });
6312 }
6313  
6314 ▶sub filenameFromUrl( $self, $url, $extension ) {
Subroutine filenameFromUrl: not called CC=1 SCAR=6.9
Pod undocumented
6315 0 my $target = URI->new( $url )->path;
6316  
6317 0 $target =~ s![\&\?\<\>\{\}\|\:\*]!_!g;
6318 0 $target =~ s!.*[/\\]!!;
6319  
6320 # Add/change extension here
6321  
6322 0 return $target
6323 }
6324  
6325 =head2 C<< $mech->viewport_size >>
6326  
6327 print Dumper $mech->viewport_size;
6328 $mech->viewport_size({ width => 1388, height => 792 });
6329  
6330 Returns (or sets) the new size of the viewport (the "window").
6331  
6332 The recognized keys are:
6333  
6334 width
6335 height
6336 deviceScaleFactor
6337 mobile
6338 screenWidth
6339 screenHeight
6340 positionX
6341 positionY
6342  
6343 =cut
6344  
6345 0 ▶sub viewport_size_future( $self, $new={} ) {
Subroutine viewport_size_future: not called CC=5 SCAR=34.0
Pod undocumented
6346 0 my $params = dclone $new;
6347 0 ▶ if( keys %$params) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %$params) { } 0 0 0
6348 0 my %reset = (
6349 mobile => JSON::false,
6350 width => 0,
6351 height => 0,
6352 deviceScaleFactor => 0,
6353 scale => 1,
6354 screenWidth => 0,
6355 screenHeight => 0,
6356 positionX => 0,
6357 positionY => 0,
6358 dontSetVisibleSize => JSON::false,
6359 screenOrientation => {
6360 type => 'landscapePrimary',
6361 angle => 0,
6362 },
6363 #viewport => {
6364 # 'x' => 0,
6365 # 'y' => 0,
6366 # width => 0,
6367 # height => 0,
6368 # scale => 1,
6369 #}
6370 );
6371 0 for my $field (qw( mobile width height deviceScaleFactor )) {
6372 0 ▶ if( ! exists $params->{ $field }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $params->{$field}) 0 0 0
6373 0 $params->{$field} = $reset{ $field };
6374 };
6375 };
6376 0 return $self->target->send_message('Emulation.setDeviceMetricsOverride', %$params );
6377 } else {
6378 0 return $self->target->send_message('Emulation.clearDeviceMetricsOverride' );
6379 };
6380 };
6381  
6382 0 ▶sub viewport_size( $self, $new={} ) {
Subroutine viewport_size: not called CC=2 SCAR=17.9
Pod documented
6383 0 $self->viewport_size_future($new)->get
6384 };
6385  
6386 =head2 C<< $mech->element_as_png( $element ) >>
6387  
6388 my $shiny = $mech->selector('#shiny', single => 1);
6389 my $i_want_this = $mech->element_as_png($shiny);
6390  
6391 Returns PNG image data for a single element
6392  
6393 =cut
6394  
6395 sub element_as_png {
6396 0 ▶ my ($self, $element) = @_;
Subroutine element_as_png: not called CC=1 SCAR=6.9
Pod documented
6397  
6398 0 $self->render_element( element => $element, format => 'png' )
6399 };
6400  
6401 =head2 C<< $mech->render_element( %options ) >>
6402  
6403 my $shiny = $mech->selector('#shiny', single => 1);
6404 my $i_want_this= $mech->render_element(
6405 element => $shiny,
6406 format => 'png',
6407 );
6408  
6409 Returns the data for a single element
6410 or writes it to a file. It accepts
6411 all options of C<< ->render_content >>.
6412  
6413 Note that while the image will have the node in the upper left
6414 corner, the width and height of the resulting image will still
6415 be the size of the browser window. Cut the image using
6416 C<< element_coordinates >> if you need exactly the element.
6417  
6418 =cut
6419  
6420 sub render_element {
6421 0 ▶ my ($self, %options) = @_;
Subroutine render_element: not called CC=3 SCAR=24.8
Pod documented
6422 my $element= delete $options{ element }
6423 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
6424  
6425 0 my $cliprect = $self->element_coordinates( $element );
6426 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
6427 0 $cliprect->{ x } = delete $cliprect->{ left };
6428 0 $cliprect->{ y } = delete $cliprect->{ top };
6429  
6430 ▶ my $res = $self->_content_as_png($cliprect,)->then( sub( $img ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
6431 0 Future->done( $self->_as_raw_png( $img ));
6432 0 })->get;
6433  
6434 0 return $res
6435 };
6436  
6437 =head2 C<< $mech->element_coordinates( $element ) >>
6438  
6439 my $shiny = $mech->selector('#shiny', single => 1);
6440 my ($pos) = $mech->element_coordinates($shiny);
6441 print $pos->{left},',', $pos->{top};
6442  
6443 Returns the page-coordinates of the C<$element>
6444 in pixels as a hash with four entries, C<left>, C<top>, C<width> and C<height>.
6445  
6446 This function might get moved into another module more geared
6447 towards rendering HTML.
6448  
6449 =cut
6450  
6451 sub element_coordinates {
6452 0 ▶ my ($self, $element) = @_;
Subroutine element_coordinates: not called CC=1 SCAR=6.9
Pod documented
6453 0 my $cliprect = $self->target->send_message('Runtime.callFunctionOn', objectId => $element->objectId, functionDeclaration => <<'JS', arguments => [], returnByValue => JSON::true)->get->{result}->{value};
6454 function() {
6455 var r = this.getBoundingClientRect();
6456 return {
6457 top : r.top
6458 , left: r.left
6459 , width: r.width
6460 , height: r.height
6461 }
6462 }
6463 JS
6464 };
6465  
6466 =head2 C<< $mech->render_content(%options) >>
6467  
6468 my $pdf_data = $mech->render_content( format => 'pdf' );
6469  
6470 Returns the current page rendered as PDF or PNG
6471 as a bytestring.
6472  
6473 Note that the PDF format will only be successful with headless Chrome. At least
6474 on Windows, when launching Chrome with a UI, printing to PDF will
6475 be unavailable.
6476  
6477 This method is specific to WWW::Mechanize::Chrome.
6478  
6479 =cut
6480  
6481 ▶sub render_content( $self, %options ) {
Subroutine render_content: not called CC=6 SCAR=37.4
Pod documented
6482 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
6483  
6484 0 my $fmt = delete $options{ format };
6485 0 my $filename = delete $options{ filename };
6486  
6487 0 my $payload;
6488 0 ▶ if( $fmt eq 'png' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($fmt eq 'png') { } 0 0 0
elsif ($fmt eq 'pdf') { } 0 0 0
6489 0 $payload = $self->content_as_png( %options )
6490 } elsif( $fmt eq 'pdf' ) {
6491 0 $payload = $self->content_as_pdf( %options );
6492 };
6493  
6494 0 ▶ if( defined $filename ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $filename) 0 0 0
6495 0 ▶ open my $fh, '>:raw', $filename
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $filename or croak("Couldn't create '${filename}': $!") 0 0 0
6496 or croak "Couldn't create '$filename': $!";
6497 0 print {$fh} $payload;
6498 };
6499  
6500 0 $payload
6501 }
6502  
6503 =head2 C<< $mech->content_as_pdf(%options) >>
6504  
6505 my $pdf_data = $mech->content_as_pdf();
6506  
6507 my $pdf_data = $mech->content_as_pdf( format => 'A4' );
6508  
6509 my $pdf_data = $mech->content_as_pdf( paperWidth => 8, paperHeight => 11 );
6510  
6511 Returns the current page rendered in PDF format as a bytestring. The page format
6512 can be specified through the C<format> option.
6513  
6514 Note that this method will only be successful with headless Chrome. At least on
6515 Windows, when launching Chrome with a UI, printing to PDF will be unavailable.
6516 See the C<html-to-pdf.pl> script in the C<examples/> directory of this distribution.
6517  
6518 This method is specific to WWW::Mechanize::Chrome.
6519  
6520 =cut
6521  
6522 69 our %PaperFormats = (
6523 letter => {width => 8.5, height => 11 },
6524 legal => {width => 8.5, height => 14 },
6525 tabloid => {width => 11, height => 17 },
6526 ledger => {width => 17, height => 11 },
6527 a0 => {width => 33.1, height => 46.8 },
6528 a1 => {width => 23.4, height => 33.1 },
6529 a2 => {width => 16.5, height => 23.4 },
6530 a3 => {width => 11.7, height => 16.5 },
6531 a4 => {width => 8.27, height => 11.7 },
6532 a5 => {width => 5.83, height => 8.27 },
6533 a6 => {width => 4.13, height => 5.83 },
6534 );
6535  
6536 ▶sub content_as_pdf($self, %options) {
Subroutine content_as_pdf: not called CC=5 SCAR=34.0
Pod documented
6537 0 ▶ if( my $format = delete $options{ format }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $format = delete $options{"format"}) 0 0 0
6538 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
6539 or croak "Unknown paper format '$format'";
6540 0 @options{'paperWidth','paperHeight'} = @{$wh}{'width','height'};
6541 };
6542  
6543 0 my $base64 = $self->target->send_message('Page.printToPDF', %options)->get->{data};
6544 0 my $payload = decode_base64( $base64 );
6545 0 ▶ if( my $filename = delete $options{ filename } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $filename = delete $options{"filename"}) 0 0 0
6546 0 ▶ open my $fh, '>:raw', $filename
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $filename or croak("Couldn't create '${filename}': $!") 0 0 0
6547 or croak "Couldn't create '$filename': $!";
6548 0 print {$fh} $payload;
6549 };
6550 0 return $payload;
6551 };
6552  
6553 =head1 INTERNAL METHODS
6554  
6555 These are methods that are available but exist mostly as internal
6556 helper methods. Use of these is discouraged.
6557  
6558 =head2 C<< $mech->element_query( \@elements, \%attributes ) >>
6559  
6560 my $query = $mech->element_query(['input', 'select', 'textarea'],
6561 { name => 'foo' });
6562  
6563 Returns the XPath query that searches for all elements with C<tagName>s
6564 in C<@elements> having the attributes C<%attributes>. The C<@elements>
6565 will form an C<or> condition, while the attributes will form an C<and>
6566 condition.
6567  
6568 =cut
6569  
6570 sub element_query {
6571 0 ▶ my ($self, $elements, $attributes) = @_;
Subroutine element_query: not called CC=1 SCAR=6.9
Pod documented
6572 my $query =
6573 './/*[(' .
6574 join( ' or ',
6575 map {
6576 0 sprintf qq{local-name(.)="%s"}, lc $_
6577 } @$elements
6578 )
6579 . ') and '
6580 . join( " and ",
6581 0 map { sprintf q{@%s="%s"}, $_, $attributes->{$_} }
6582 sort keys(%$attributes)
6583 )
6584 . ']';
6585 };
6586  
6587 sub post_process
6588 {
6589 0 ▶ my $self = shift;
Subroutine post_process: not called CC=3 SCAR=24.8
Pod undocumented
6590 0 ▶ if ( $self->{report_js_errors} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"report_js_errors"}) 0 0 0
6591 0 ▶ if ( my @errors = $self->js_errors ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@errors) = $self->js_errors) 0 0 0
6592 0 $self->report_js_errors(@errors);
6593 0 $self->clear_js_errors;
6594 }
6595 }
6596 }
6597  
6598 sub report_js_errors
6599 {
6600 0 ▶ my ( $self, @errors ) = @_;
Subroutine report_js_errors: not called CC=5 SCAR=34.0
Pod documented
6601 @errors = map {
6602 0 $_->{message} .
6603 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
6604 0 ▶ ( @{$_->{trace}} && $_->{trace}->[-1]->{function} ? " in function $_->{trace}->[-1]->{function}" : '')
Branch: 1 branch
BranchTrueFalseTotal
@{$_->{'trace'};} ? : 0 0 0
6605 } @errors;
6606 0 ▶ Carp::carp("javascript error: @errors") if @errors;
Branch: 1 branch
BranchTrueFalseTotal
if @errors 0 0 0
6607 }
6608  
6609 =head1 DEBUGGING METHODS
6610  
6611 This module can collect the screencasts that Chrome can produce. The screencasts
6612 are sent to your callback which either feeds them to C<ffmpeg> to create a video
6613 out of them or dumps them to disk as sequential images.
6614  
6615 sub saveFrame {
6616 my( $mech, $framePNG ) = @_;
6617 print $framePNG->{data};
6618  
6619 }
6620  
6621 $mech->setScreenFrameCallback( \&saveFrame );
6622 ... do stuff ...
6623 $mech->setScreenFrameCallback( undef ); # stop recording
6624  
6625 If you want a premade screencast receiver for debugging headless Chrome
6626 sessions, see L<Mojolicious::Plugin::PNGCast>.
6627  
6628 =cut
6629  
6630 ▶sub _handleScreencastFrame( $self, $frame ) {
Subroutine _handleScreencastFrame: not called CC=1 SCAR=6.9
6631 # Meh, this one doesn't get a response I guess. So, not ->send_message, just
6632 # send a JSON packet to acknowledge the frame
6633 0 my $s = $self;
6634 0 weaken $s;
6635 $self->target->send_message(
6636 'Page.screencastFrameAck',
6637 sessionId => 0+$frame->{params}->{sessionId} )->then(sub {
6638 0 ▶ $s->log('trace', 'Screencast frame acknowledged');
Subroutine __ANON__: not called CC=2 SCAR=17.9
6639 0 $frame->{params}->{data} = decode_base64( $frame->{params}->{data} );
6640 0 ▶ if( my $cb = $s->{ screenFrameCallback }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cb = $s->{"screenFrameCallback"}) 0 0 0
6641 0 $cb->( $s, $frame->{params} );
6642 }
6643 0 Future->done();
6644 0 })->retain;
6645 }
6646  
6647 0 ▶sub setScreenFrameCallback( $self, $callback=undef, %options ) {
Subroutine setScreenFrameCallback: not called CC=5 SCAR=34.0
Pod undocumented
6648 0 $self->{ screenFrameCallback } = $callback;
6649  
6650 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
6651 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
6652  
6653 0 my $action;
6654 0 my $s = $self;
6655 0 weaken $s;
6656 0 ▶ if( $callback ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($callback) { } 0 0 0
6657 ▶ $self->{ screenFrameCallbackCollector } = sub( $frame ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
6658 0 $s->_handleScreencastFrame( $frame );
6659 0 };
6660 $self->{ screenCastFrameListener } =
6661 0 $self->add_listener('Page.screencastFrame', $self->{ screenFrameCallbackCollector });
6662 $action = $s->target->send_message(
6663 'Page.startScreencast',
6664 format => $options{ format },
6665 everyNthFrame => 0+$options{ everyNthFrame }
6666 0 );
6667 } else {
6668 $action = $self->target->send_message('Page.stopScreencast')->then( sub {
6669 # well, actually, we should only reset this after we're sure that
6670 # the last frame has been processed. Maybe we should send ourselves
6671 # a fake event for that, or maybe Chrome tells us
6672 0 ▶ delete $s->{ screenCastFrameListener };
Subroutine __ANON__: not called CC=1 SCAR=6.9
6673 0 Future->done(1);
6674 0 });
6675 }
6676 0 $action->get
6677 }
6678  
6679 =head2 C<< $mech->sleep >>
6680  
6681 $mech->sleep( 2 ); # wait for things to settle down
6682  
6683 Suspends the progress of the program while still handling messages from
6684 Chrome.
6685  
6686 The main use of this method is to give Chrome enough time to send all its
6687 screencast frames and to catch up before shutting down the connection.
6688  
6689 =cut
6690  
6691 ▶sub sleep_future( $self, $seconds ) {
Subroutine sleep_future: not called CC=1 SCAR=6.9
Pod undocumented
6692 0 $self->target->sleep( $seconds );
6693 }
6694  
6695 ▶sub sleep( $self, $seconds ) {
Subroutine sleep: not called CC=1 SCAR=6.9
Pod documented
6696 0 $self->sleep_future( $seconds )->get;
6697 }
6698  
6699 69 1;
6700  
6701 =head1 INCOMPATIBILITIES WITH WWW::Mechanize
6702  
6703 As this module is in a very early stage of development,
6704 there are many incompatibilities. The main thing is
6705 that only the most needed WWW::Mechanize methods
6706 have been implemented by me so far.
6707  
6708 =head2 Unsupported Methods
6709  
6710 At least the following methods are unsupported:
6711  
6712 =over 4
6713  
6714 =item *
6715  
6716 C<< ->find_all_inputs >>
6717  
6718 This function is likely best implemented through C<< $mech->selector >>.
6719  
6720 =item *
6721  
6722 C<< ->find_all_submits >>
6723  
6724 This function is likely best implemented through C<< $mech->selector >>.
6725  
6726 =item *
6727  
6728 C<< ->images >>
6729  
6730 This function is likely best implemented through C<< $mech->selector >>.
6731  
6732 =item *
6733  
6734 C<< ->find_image >>
6735  
6736 This function is likely best implemented through C<< $mech->selector >>.
6737  
6738 =item *
6739  
6740 C<< ->find_all_images >>
6741  
6742 This function is likely best implemented through C<< $mech->selector >>.
6743  
6744 =back
6745  
6746 =head2 Functions that will likely never be implemented
6747  
6748 These functions are unlikely to be implemented because
6749 they make little sense in the context of Chrome.
6750  
6751 =over 4
6752  
6753 =item *
6754  
6755 C<< ->clone >>
6756  
6757 =item *
6758  
6759 C<< ->credentials( $username, $password ) >>
6760  
6761 =item *
6762  
6763 C<< ->get_basic_credentials( $realm, $uri, $isproxy ) >>
6764  
6765 =item *
6766  
6767 C<< ->clear_credentials() >>
6768  
6769 =item *
6770  
6771 C<< ->put >>
6772  
6773 I have no use for it
6774  
6775 =item *
6776  
6777 C<< ->post >>
6778  
6779 This module does not yet support POST requests
6780  
6781 =back
6782  
6783 =head1 INSTALLING
6784  
6785 See L<WWW::Mechanize::Chrome::Install>
6786  
6787 =head1 SEE ALSO
6788  
6789 =over 4
6790  
6791 =item *
6792  
6793 L<https://chromedevtools.github.io/devtools-protocol/> - the Chrome DevTools Protocol
6794  
6795 =item *
6796  
6797 L<https://developer.chrome.com/devtools/docs/debugging-clients> - the Chrome
6798 DevTools homepage
6799  
6800 =item *
6801  
6802 L<https://github.com/GoogleChrome/lighthouse> - Google Lighthouse, the main
6803 client of the Chrome API
6804  
6805 =item *
6806  
6807 L<WWW::Mechanize> - the module whose API grandfathered this module
6808  
6809 =item *
6810  
6811 L<WWW::Mechanize::Chrome::Node> - objects representing HTML in Chrome
6812  
6813 =item *
6814  
6815 L<WWW::Mechanize::Firefox> - a similar module with a visible application
6816 automating Firefox , currently on hiatus, since Mozilla does not yet
6817 implement the Chrome DevTools Protocol properly
6818  
6819 =item *
6820  
6821 L<WWW::Mechanize::PhantomJS> - a similar module without a visible application
6822 automating PhantomJS , now discontinued since PhantomJS is discontinued
6823  
6824 =back
6825  
6826 =head1 MASQUERADING AS OTHER BROWSERS
6827  
6828 Some articles about what you need to change to appear as a different
6829 browser
6830  
6831 L<https://multilogin.com/why-mimicking-a-device-is-almost-impossible/>
6832  
6833 L<https://github.com/berstend/puppeteer-extra/tree/master/packages/puppeteer-extra-plugin-stealth>
6834  
6835 L<https://rebrowser.net/blog/how-to-access-main-context-objects-from-isolated-context-in-puppeteer-and-playwright>
6836  
6837 =head1 REPOSITORY
6838  
6839 The public repository of this module is
6840 L<https://github.com/Corion/www-mechanize-chrome>.
6841  
6842 =head1 SUPPORT
6843  
6844 The public support forum of this module is L<https://perlmonks.org/>.
6845  
6846 =head1 TALKS
6847  
6848 I've given a German talk at GPW 2017, see L<http://act.yapc.eu/gpw2017/talk/7027>
6849 and L<https://corion.net/talks> for the slides.
6850  
6851 At The Perl Conference 2017 in Amsterdam, I also presented a talk, see
6852 L<http://act.perlconference.org/tpc-2017-amsterdam/talk/7022>.
6853 The slides for the English presentation at TPCiA 2017 are at
6854 L<https://corion.net/talks/WWW-Mechanize-Chrome/www-mechanize-chrome.en.html>.
6855  
6856 At the London Perl Workshop 2017 in London, I also presented a talk, see
6857 L<Youtube|https://www.youtube.com/watch?v=V3WeO-iVkAc> . The slides for
6858 that talk are
6859 L<here|https://corion.net/talks/WWW-Mechanize-Chrome/www-mechanize-chrome.en.html>.
6860  
6861 =head1 BUG TRACKER
6862  
6863 Please report bugs in this module via the Github bug queue at
6864 L<https://github.com/Corion/WWW-Mechanize-Chrome/issues>
6865  
6866 =head1 CONTRIBUTING
6867  
6868 Please see L<WWW::Mechanize::Chrome::Contributing>.
6869  
6870 =head1 KNOWN ISSUES
6871  
6872 Please see L<WWW::Mechanize::Chrome::Troubleshooting>.
6873  
6874 =head1 AUTHOR
6875  
6876 Max Maischein C<corion@cpan.org>
6877  
6878 =head1 CONTRIBUTORS
6879  
6880 Andreas König C<andk@cpan.org>
6881  
6882 Tobias Leich C<froggs@cpan.org>
6883  
6884 Steven Dondley C<s@dondley.org>
6885  
6886 Joshua Pollack
6887  
6888 =head1 COPYRIGHT (c)
6889  
6890 Copyright 2010-2026 by Max Maischein C<corion@cpan.org>.
6891  
6892 =head1 LICENSE
6893  
6894 This module is released under the same terms as Perl itself.
6895  
6896 =cut
↑ Summary Chrome/DevToolsProtocol/Target.pm »