WebKit.pm

filter: Statementstmt 81.8% 9 / 11 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 86.6% 13 / 15 CC 1 SCAR 0.7
CC
1
Cov
82%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« WebKit/Client/Element.pm ↑ Summary
1 package EV::WebKit;
2 1 ▶use v5.10; use strict; use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3 our $VERSION = '0.04';
4  
5 1 ▶use Glib::Object::Introspection;
Subroutine BEGIN: called CC=1 SCAR=2.6
6 use Glib::IO; # Gio bindings: Cancellable, MemoryInputStream
7 use EV::WebKit::Element;
8 use File::Spec::Functions 'rel2abs';
9 use File::Path ();
10 use File::Temp ();
11 use Scalar::Util qw(weaken refaddr);
12 use Carp (); # Carp::croak -- core, no prereq change
13  
14 # Element's find/find_all share this package's _need_selector, so without this
15 # Carp blamed Element.pm's own line rather than the caller's -- the only croak
16 # in the class that did. Every other one in the dist points at the call site.
17 our @CARP_NOT = ('EV::WebKit::Element');
18  
19 use constant NAV_SETTLE_DELAY => 0.15; # deadline for the settle race in _finish_nav -- only a page with NO <title> ever waits it out
20  
21 # id-keyed registry counter for _finish_nav's settle slots ({_settle}), same
22 # idea as $_defer_seq below -- declared up here because _finish_nav references
23 # it directly, so it must be in scope before its first use.
24 my $_settle_seq = 0;
25  
26 # generation counter for {pending} (the in-flight nav slot): every
27 # _start_nav mints a new one. Lets _finish_nav tell "the timeout timer that
28 # belongs to THIS pending nav" apart from "a newer nav that has since
29 # superseded it" -- see _start_nav/_finish_nav below.
30 my $_nav_seq = 0;
31  
32 # Identifies each queued pdf() job, so its watchdog (armed at enqueue, keyed in
33 # {_pdf_timers}) can be disarmed on completion, and so _pdf_pump can tell that a
34 # job's caller has already given up -- all without any closure capturing the job
35 # or its PrintOperation. See pdf/_pdf_pump/_pdf_run.
36 my $_pdf_seq = 0;
37  
38 # True while a WebKit/GLib signal handler that calls USER code is on the stack.
39 # Seven do, the same seven the POD names under EV::break: on_dialog
40 # (script-dialog), on_policy (decide-policy), on_console
41 # (script-message-received), on_authenticate (authenticate), on_file_chooser
42 # (run-file-chooser), on_download (download-started), and a mock_scheme
43 # producer. Code running there is nested inside WebKit's own dispatch frame, NOT
44 # on a clean EV tick -- which is why quit() must not do its work in place when
45 # called from one (see quit).
46 #
47 # The RESULT callbacks are a different matter: those are delivered by
48 # _defer/_defer_final, i.e. already on a clean tick, and leave this false. So do
49 # on_load/on_error/on_navigate, and on_close, which defers for this same reason.
50 our $IN_DISPATCH = 0;
51  
52 # Pending _defer_final deliveries, keyed by a monotonic id. File-scoped, NOT
53 # per-instance, so a final callback still fires after its browser is dropped
54 # (see _defer_final). Entries are transient: each timer deletes its own.
55 my %FINAL;
56  
57 my @TYPELIBS = (
58 [qw/Gtk 4.0 Gtk4/], [qw/Gdk 4.0 Gdk4/], [qw/JavaScriptCore 6.0 JSC/],
59 [qw/Soup 3.0 Soup/], [qw/WebKit 6.0 WebKit/],
60 );
61  
62 my $SETUP; # 1 = ok, 0 = failed, undef = not tried
63 sub _setup {
64 return $SETUP if defined $SETUP;
65 $SETUP = eval {
66 Glib::Object::Introspection->setup(basename=>$_->[0], version=>$_->[1], package=>$_->[2])
67 for @TYPELIBS;
68 1; # GI namespace setup only -- display-independent
69 } ? 1 : 0;
70 return $SETUP;
71 }
72  
73 my $GTK_INIT;
74 my $GTK_DISPLAY; # the display GTK actually connected to, process-wide
75 # Gtk4::init() aborts without a display, so call it ONLY after a display exists.
76 # It also runs at most ONCE per process: GTK connects to one X display and every
77 # later instance shares it, whatever it asked for. Remember which, so new() can
78 # say so instead of silently ignoring a display => option (a window that quietly
79 # appears on the wrong display, or a bogus display that "works", is worse than
80 # an error).
81 # init_check, NOT init: Gtk4::init() calls exit(1) on a display it cannot open.
82 # That is not a Perl exception -- eval cannot see it, and nothing after new()
83 # runs. A set-but-DEAD $DISPLAY is the common case: a cron job or unit file
84 # carrying DISPLAY=:0, a detached ssh session, an xvfb-run whose server has
85 # gone, a typo in display => ':1'. init_check returns false instead, so this
86 # can be a clean die.
87 sub _init_gtk {
88 return 1 if $GTK_INIT;
89 return 0 unless Gtk4::init_check();
90 $GTK_INIT = 1;
91 $GTK_DISPLAY = $ENV{DISPLAY};
92 return 1;
93 }
94  
95 sub available { _setup() ? 1 : 0 }
96  
97 use EV;
98 use EV::Glib; # integrates the GLib main loop into EV
99  
100 # JSON codec (XS preferred). CHARACTER mode (utf8(0)), not byte mode:
101 # Glib::Object::Introspection marshals `utf8`-typed params/returns as Perl
102 # CHARACTER strings (it upgrades an unflagged scalar as Latin-1 on the way
103 # in, and always returns a utf8-flagged character string on the way out --
104 # see call_async_javascript_function/JSC::Value::to_string below). _enc's
105 # output feeds straight into such a param, and _dec's input comes straight
106 # from such a return, so the codec must speak characters, not bytes -- byte
107 # mode here silently double-encodes non-ASCII args and fails to decode
108 # non-ASCII results ("malformed UTF-8"/"Wide character" errors).
109 my $JSON = do {
110 my $j = eval { require Cpanel::JSON::XS; Cpanel::JSON::XS->new } || do { require JSON::PP; JSON::PP->new };
111 $j->canonical(1)->allow_nonref(1)->utf8(0);
112 };
113 sub _enc { $JSON->encode($_[0]) }
114 sub _dec { $JSON->decode($_[0]) }
115  
116 # The element registry and every internal DOM call run in a dedicated,
117 # named JavaScript *isolated world* (its own global object and its own
118 # built-in prototypes, sharing only the DOM with the page). Page script
119 # cannot see or tamper with window.__evwk there, and -- crucially -- the
120 # JSON.stringify / Object.prototype the result-marshalling in _call_js
121 # relies on are the world's own natives, immune to a hostile page
122 # redefining JSON.stringify or polluting Object.prototype.toJSON. Only the
123 # user-facing script()/script_async() run in the page's main world (they
124 # exist to run the page's own JS), and the console proxy stays in the main
125 # world too (it must override the console the page's own code calls).
126 my $EVWK_WORLD = 'EVWebKit';
127  
128 # A dedicated world for user scripts requested with world => 'isolated'. It is
129 # DELIBERATELY distinct from $EVWK_WORLD: a caller's isolated script must not be
130 # able to read or corrupt the module's own element registry.
131 my $USER_WORLD = 'EVWebKitUser';
132  
133 # Friendly option value -> WebKit GObject-Introspection enum nick. Only `frames`
134 # actually renames; the rest pass through but are still validated so a typo
135 # croaks here instead of reaching WebKit as a bad nick.
136 my %USER_FRAMES = (all => 'all-frames', top => 'top-frame');
137 my %USER_AT = (start => 'start', end => 'end');
138 my %USER_LEVEL = (author => 'author', user => 'user');
139 my %USER_WORLD_OK = (main => 1, isolated => 1);
140  
141 # Re-injected (a fresh window.__evwk) at document-start on every navigation,
142 # so the id-space always restarts at 0 -- a handle from a previous page can
143 # therefore land on the SAME numeric id as a new page's element. `epoch` is
144 # a fresh per-document stamp so get() can tell the two apart: it throws
145 # 'stale element' both for that cross-navigation case (epoch mismatch) and
146 # for the original same-page "node removed" case (isConnected false). `e`
147 # is optional (get(i) alone still works) so this stays backward-tolerant.
148 #
149 # The registry must not grow without bound. It is keyed by id in a Map (NOT an
150 # array index), so entries can be dropped without renumbering a live handle:
151 # - put() DEDUPES via a WeakMap (node -> id), because the same node is
152 # registered over and over -- every wait_for poll re-runs find(), 20 times a
153 # second by default. Pushing each time meant a minute of polling appended
154 # 1200 entries for ONE node.
155 # - put() also sweeps detached nodes periodically. get() already refuses any
156 # node that is not isConnected, so a detached entry can never be used again
157 # -- it only pins the node in the renderer's JS heap, keeping the whole
158 # removed subtree alive for as long as the page lives. (A page that never
159 # navigates is exactly the long-lived single-page-app case this module is
160 # used for, and the id-space reset on navigation does not help there.)
161 # Neither map holds a node strongly beyond what get() would still accept.
162 my $BOOT = <<'JS';
163 window.__evwk = window.__evwk || {
164 h: new Map(), // id -> node (live handles)
165 r: new WeakMap(), // node -> id (dedup; weak, so it never pins a node)
166 n: 0, // next id
167 epoch: Date.now().toString(36) + Math.random().toString(36).slice(2),
168 put(node){
169 const seen = this.r.get(node);
170 if (seen !== undefined && this.h.get(seen) === node) return seen;
171 const id = this.n++;
172 this.h.set(id, node);
173 this.r.set(node, id);
174 if (this.h.size > 64 && (id & 63) === 0) {
175 for (const [k, v] of this.h) { if (!this.alive(v)) this.h.delete(k); }
176 }
177 return id;
178 },
179 // isConnected alone is not liveness for a node inside an iframe: remove the
180 // frame and the node is still connected to ITS OWN document, which is merely
181 // detached from the parent. The browsing context is what has gone, and
182 // defaultView is null once it has -- the same signal the web-process
183 // extension uses for zombie frames. Without this, a handle into a removed
184 // frame went on answering with the old content and reporting clicks as
185 // successful, which is the one wrong answer this API must not give.
186 alive(n){
187 if (!n || !n.isConnected) return false;
188 const d = n.ownerDocument;
189 return !!(d && d.defaultView);
190 },
191 get(i, e){
192 if (e !== undefined && e !== this.epoch) throw new Error('stale element');
193 const n = this.h.get(i);
194 if (!this.alive(n)) throw new Error('stale element');
195 return n;
196 }
197 };
198 JS
199  
200  
201 # Every option new() honours. A typo'd key must not be silently ignored: a
202 # mistyped proxy => would route DIRECT (deanonymization), and a mistyped
203 # data_dir => would silently fall back to an ephemeral session (no persistence).
204 # Keep in sync with the options read below and the CONSTRUCTOR POD.
205 # A digit string modulo 2**32, never numifying the whole value: every
206 # intermediate stays under 2**36 (the worst case is 4294967295*10+9), which is
207 # exact in an NV on any perl. See new()'s seed.
208 sub _reduce32 {
209 my $r = 0;
210 $r = ($r * 10 + $_) % 4294967296 for split //, $_[0];
211 return $r;
212 }
213  
214 my %KNOWN_NEW = map { $_ => 1 } qw(
215 timeout window display
216 on_load on_error on_close on_navigate on_console on_dialog on_policy
217 on_file_chooser on_download on_request on_response on_authenticate
218 data_dir cache_dir ephemeral cookie_jar jar_format
219 proxy user_agent devtools title chrome
220 fingerprint network_fingerprint seed popups fonts
221 );
222  
223 # fonts => a fontconfig file, or the directories to build one from. Returns
224 # undef, or { conf => $abs_file, bind => [ [$path, $read_only], ... ] }.
225 #
226 # The web process runs under bubblewrap and cannot see a path nobody mounted
227 # for it: setting FONTCONFIG_FILE alone changes nothing at all (measured --
228 # identical text metrics), because fontconfig inside the sandbox never opens
229 # the file. So every path the config names has to be handed to
230 # add_path_to_sandbox as well, which is why this returns the list rather than
231 # just the filename.
232 sub _fonts_arg {
233 my ($fonts, $tmp_ref) = @_;
234 return undef unless defined $fonts;
235  
236 my @dirs;
237 my $conf;
238 if (ref $fonts eq 'ARRAY' || ref $fonts eq 'HASH') {
239 my ($list, %generic);
240 if (ref $fonts eq 'HASH') {
241 if (my @bad = sort grep { !/\A(?:dirs|sans_serif|serif|monospace)\z/ } keys %$fonts) {
242 Carp::croak("EV::WebKit: unknown fonts key(s): @bad");
243 }
244 $list = $fonts->{dirs};
245 Carp::croak('EV::WebKit: fonts => { dirs => [...] } is required')
246 unless ref $list eq 'ARRAY';
247 for my $g (qw(sans_serif serif monospace)) {
248 next unless defined $fonts->{$g};
249 Carp::croak("EV::WebKit: fonts => { $g => } must be a family name")
250 if ref $fonts->{$g} || !length $fonts->{$g};
251 Carp::croak("EV::WebKit: a font family name must not contain markup")
252 if $fonts->{$g} =~ /[<>&]/;
253 (my $family = $g) =~ tr/_/-/;
254 $generic{$family} = $fonts->{$g};
255 }
256 }
257 else { $list = $fonts }
258  
259 Carp::croak('EV::WebKit: fonts needs at least one directory') unless @$list;
260 for my $d (@$list) {
261 Carp::croak('EV::WebKit: each fonts directory must be a plain path')
262 if !defined $d || ref $d || !length $d;
263 my $abs = rel2abs($d);
264 Carp::croak("EV::WebKit: fonts directory '$d' does not exist") unless -d $abs;
265 push @dirs, $abs;
266 }
267 # Its own cachedir, inside the same writable directory: fontconfig
268 # rebuilds the cache per font set, and pointing at the user's normal one
269 # would both fail (read-only in the sandbox) and mix the two.
270 $$tmp_ref = File::Temp::tempdir('evwk-fonts-XXXXXX', TMPDIR => 1, CLEANUP => 1);
271 $conf = "$$tmp_ref/fonts.conf";
272 my $cache = "$$tmp_ref/cache";
273 File::Path::make_path($cache);
274 open my $fh, '>', $conf
275 or Carp::croak("EV::WebKit: cannot write $conf: $!");
276 print $fh qq{<?xml version="1.0"?>\n},
277 qq{<!DOCTYPE fontconfig SYSTEM "fonts.dtd">\n<fontconfig>\n},
278 map({ " <dir>$_</dir>\n" } @dirs),
279 qq{ <cachedir>$cache</cachedir>\n};
280 # Without these the three generic families all resolve to whatever
281 # matches first, so sans-serif, serif and monospace measure IDENTICALLY
282 # -- which is both wrong on the page and a fingerprint of its own. The
283 # system rules that would normally supply them cannot be included:
284 # /etc/fonts/conf.d carries <dir> entries of its own, and pulling those
285 # in would put the host's fonts back.
286 for my $family (sort keys %generic) {
287 print $fh qq{ <match target="pattern"><test qual="any" name="family">},
288 qq{<string>$family</string></test>},
289 qq{<edit name="family" mode="prepend" binding="same">},
290 qq{<string>$generic{$family}</string></edit></match>\n};
291 }
292 print $fh qq{</fontconfig>\n};
293 close $fh or Carp::croak("EV::WebKit: cannot write $conf: $!");
294 }
295 elsif (!ref $fonts) {
296 Carp::croak('EV::WebKit: fonts => must not be empty') unless length $fonts;
297 $conf = rel2abs($fonts);
298 Carp::croak("EV::WebKit: fonts config '$fonts' is not a readable file")
299 unless -f $conf && -r _;
300 open my $fh, '<', $conf
301 or Carp::croak("EV::WebKit: cannot read $conf: $!");
302 my $text = do { local $/; <$fh> };
303 close $fh;
304 # Only absolute existing paths are bound. A <dir prefix="xdg">, or one
305 # naming a directory that is not there, is fontconfig's business, not
306 # ours -- binding it would fail where fontconfig merely skips it.
307 while ($text =~ m{<(dir|cachedir)\b[^>]*>\s*([^<]+?)\s*</\1>}g) {
308 my $p = $2;
309 push @dirs, $p if $p =~ m{^/} && -d $p;
310 }
311 }
312 else {
313 Carp::croak('EV::WebKit: fonts => must be a fontconfig file path, an arrayref of directories, or a hashref');
314 }
315  
316 my %seen;
317 my @bind = map { [ $_, 1 ] } grep { !$seen{$_}++ } @dirs;
318 # The config itself, and anything generated beside it, must be reachable
319 # too -- and the cache directory has to be writable, or fontconfig re-scans
320 # every font on every page load.
321 my ($conf_dir) = $conf =~ m{^(.*)/[^/]+$};
322 unshift @bind, [ $conf_dir, ($$tmp_ref && $conf_dir eq $$tmp_ref) ? 0 : 1 ]
323 if defined $conf_dir && length $conf_dir && !$seen{$conf_dir}++;
324 return { conf => $conf, bind => \@bind };
325 }
326  
327 sub new {
328 my $class = shift;
329 # Before %o = @_: an odd list warns "Odd number of elements in hash
330 # assignment" from inside this file and silently drops the trailing token,
331 # leaving whatever option it belonged to at its default.
332 Carp::croak('EV::WebKit: options must be name => value pairs') if @_ % 2;
333 my %o = @_;
334 _setup() or die "EV::WebKit: required typelibs unavailable\n";
335 if (my @bad = sort grep { !$KNOWN_NEW{$_} } keys %o) {
336 Carp::croak("EV::WebKit: unknown option(s): @bad");
337 }
338 # Checked here rather than at fire time, where a non-coderef surfaces only
339 # as a warn from the dispatch eval and the handler simply never runs.
340 for my $h (qw(on_error on_load on_close on_navigate on_console on_dialog
341 on_policy on_file_chooser on_download on_authenticate)) {
342 next unless defined $o{$h};
343 Carp::croak("EV::WebKit: $h must be a code reference") if ref $o{$h} ne 'CODE';
344 }
345 my $fp; # resolved fingerprint profile (or undef)
346 if (defined $o{fingerprint}) {
347 require EV::WebKit::Fingerprint;
348 Carp::croak('EV::WebKit: fingerprint requested but the web-process extension was not built at install '
349 . '(needs cc + glib/gobject); see EV::WebKit::fingerprint_available')
350 unless EV::WebKit::Fingerprint::available();
351 Carp::croak('EV::WebKit: fingerprint sets the User-Agent -- pass it via fingerprint => { ..., user_agent => ... } '
352 . 'instead of a separate user_agent option')
353 if defined $o{user_agent};
354 $fp = EV::WebKit::Fingerprint::resolve($o{fingerprint});
355 }
356 # Resolved before anything is built: it validates paths and can write a
357 # generated config, and a croak there should not leave a session behind.
358 my $font_tmp;
359 my $fonts = _fonts_arg($o{fonts}, \$font_tmp);
360 if (defined $o{seed}) {
361 Carp::croak('EV::WebKit: seed must be a non-negative integer')
362 unless !ref $o{seed} && $o{seed} =~ /\A\d+\z/;
363 Carp::croak('EV::WebKit: seed requires fingerprint => <profile>') unless $fp;
364 # Reduce to 32 bits HERE: the extension casts the GVariant double to
365 # guint32, and converting an out-of-range double is undefined in C -- x86
366 # wraps while ARM saturates, so an unreduced seed (a millisecond epoch, or
367 # hex(substr($digest,0,16))) would silently produce DIFFERENT noise per
368 # architecture. Reducing in Perl keeps that deterministic everywhere.
369 #
370 # (_reduce32 works digit by digit: `%` is exact only up to a UV, and a
371 # digest-derived seed is bigger than that on a 32-bit perl.)
372 $o{seed} = _reduce32($o{seed});
373 }
374 if ($o{network_fingerprint}) {
375 # 1 (derive from the profile) or a curl target like 'chrome131'. A real
376 # target always has a letter, which is what tells the two apart below --
377 # rejecting only references let `=> 2` pass as 1 and `=> 0.5` pass as a
378 # target name.
379 Carp::croak("EV::WebKit: network_fingerprint must be 1 or a curl-target string like 'chrome131'")
380 if ref $o{network_fingerprint}
381 || !length $o{network_fingerprint}
382 || ($o{network_fingerprint} ne '1' && $o{network_fingerprint} !~ /[A-Za-z]/);
383 Carp::croak('EV::WebKit: network_fingerprint requires fingerprint => <profile>')
384 unless $fp;
385 Carp::croak('EV::WebKit: network_fingerprint and an explicit proxy => are mutually exclusive')
386 if exists $o{proxy};
387 }
388 for my $h (qw(on_request on_response)) {
389 next unless defined $o{$h};
390 Carp::croak("EV::WebKit: $h must be a code reference")
391 unless ref $o{$h} eq 'CODE';
392 # Same exclusion as network_fingerprint, and for the same reason: the
393 # interception proxy IS this instance's proxy, so it cannot also route
394 # through one the caller chose.
395 Carp::croak("EV::WebKit: $h and an explicit proxy => are mutually exclusive")
396 if exists $o{proxy};
397 }
398 my $self = bless {
399 timeout => $o{timeout} // 30,
400 on_error => $o{on_error},
401 on_load => $o{on_load},
402 on_close => $o{on_close},
403 on_navigate => $o{on_navigate},
404 fingerprint => $fp, # resolved device profile (or undef); see the fingerprint => option
405 pending => undef, # pending nav [cb, timer, gen, target_uri, started_seen, committed_uri, doc_scheme_seen]
406 _superseded => {}, # uri => 1 -- identities of navs torn down mid-flight by _start_nav; see there and the load-changed/load-failed handlers
407 _ops => {}, # id => wrapped cb for every in-flight one-shot async op (_call_js/screenshot/pdf/cookie); quit() flushes these with 'browser closed' so none is silently dropped -- see _op_track
408 _pdf_queue => [], # serialized pdf() jobs [id, path, \%opt, cb] -- one PrintOperation runs at a time (see pdf/_pdf_pump)
409 _pdf_timers => {}, # id => watchdog for each pdf() job, armed at ENQUEUE so a job waiting behind a slow/stuck print is bounded too
410 }, $class;
411  
412 # Keep the viewport geometrically possible: window.innerWidth/Height must not
413 # exceed the spoofed screen (no real device has that). A mobile fingerprint
414 # sizes the window TO its screen; any other fingerprint with a screen CAPS the
415 # window to it (a windowed desktop can be smaller, never larger).
416 my ($w, $h);
417 if ($fp && $fp->{mobile} && $fp->{screen}) {
418 ($w, $h) = @{ $fp->{screen} }[0,1];
419 }
420 else {
421 ($w, $h) = @{ $o{window} || [1280, 1024] };
422 if ($fp && $fp->{screen}) {
423 my ($sw, $sh) = @{ $fp->{screen} }[0,1];
424 $w = $sw if $w > $sw;
425 $h = $sh if $h > $sh;
426 }
427 }
428 # bring-your-own-display: the caller provides an X display (e.g. run under
429 # `xvfb-run -a <script>`); this module never spawns or kills an X server.
430 # GTK is already connected to a display and cannot be moved to another, so a
431 # display => that disagrees with it can only be a mistake -- and silently
432 # honouring the request while using the old display is the worst outcome
433 # (the instance works, on the wrong screen, and even a nonexistent display
434 # "succeeds"). Say so rather than mutating $ENV{DISPLAY} process-wide for
435 # nothing.
436 Carp::croak("EV::WebKit: display => '$o{display}' but this process already "
437 . "connected GTK to '$GTK_DISPLAY' -- one display per process, and it "
438 . "cannot be changed once a browser exists")
439 if defined $o{display} && $GTK_INIT && defined $GTK_DISPLAY && $o{display} ne $GTK_DISPLAY;
440 $ENV{DISPLAY} = $o{display} if defined $o{display};
441 die "EV::WebKit: no X display. Run under one (e.g. `xvfb-run -a <script>`) "
442 . "or pass display => ':N'.\n" unless defined $ENV{DISPLAY} && length $ENV{DISPLAY};
443 $ENV{GDK_BACKEND} //= 'x11';
444 _init_gtk()
445 or die "EV::WebKit: cannot open X display '$ENV{DISPLAY}' -- it is set but "
446 . "not answering. Is the server running? (e.g. `xvfb-run -a <script>`)\n";
447  
448 # cookie_jar forces a non-ephemeral session: WebKit's own
449 # set_persistent_storage bails out immediately for an ephemeral session,
450 # so native cookie persistence requires a real (even if undef/default-dir)
451 # NetworkSession.
452 Carp::croak('EV::WebKit: data_dir => ... with ephemeral => 1 -- a persistent '
453 . 'session cannot be ephemeral. Drop one of them.')
454 if defined $o{data_dir} && ($o{ephemeral} // 0);
455 Carp::croak('EV::WebKit: cache_dir => ... needs data_dir => ... too -- a cache '
456 . 'directory with no data directory would leak cache to WebKit\'s '
457 . 'shared location and defeat the isolation.')
458 if defined $o{cache_dir} && !defined $o{data_dir};
459 # An empty-string path is never what the caller meant: rel2abs('') is the
460 # cwd, so the session would silently dump into whatever directory the process
461 # happens to be in, and the interpolated "$data_dir/cache" would become the
462 # filesystem-root '/cache'. Reject it, loudly, next to the other croaks.
463 for my $k (qw/data_dir cache_dir cookie_jar/) {
464 Carp::croak("EV::WebKit: $k => '' -- an empty path is not valid. Omit it, or give a real path.")
465 if defined $o{$k} && !length $o{$k};
466 }
467  
468 # cookie_jar OR data_dir forces a non-ephemeral session: WebKit's
469 # set_persistent_storage (cookie_jar) and its on-disk storage (data_dir)
470 # both bail out for an ephemeral session.
471 # `defined`, not truthiness, for BOTH: '0' is a valid relative path (and
472 # survives the empty-path croak above), but tested for truth it left the
473 # session ephemeral -- where set_persistent_storage silently does nothing.
474 my $ephemeral = (defined $o{cookie_jar} || defined $o{data_dir})
475 ? 0 : (defined $o{ephemeral} ? $o{ephemeral} : 1);
476  
477 # data_dir points the whole session -- cookies, localStorage, IndexedDB,
478 # cache -- at $data_dir, isolated from every other instance, and restored on
479 # the next construction with the same path. cache (regenerable) defaults to a
480 # subdirectory; cache_dir overrides it. rel2abs because a path relative to
481 # WebKit's cwd is a footgun (cwd drifts) -- same reason pdf() uses it.
482 #
483 # Resolve, VALIDATE, and CREATE the directories here rather than leaving it to
484 # WebKit. WebKit defers directory setup to the first navigation, inside its
485 # bubblewrap sandbox, where a bad path is not a catchable error but a process
486 # ABORT (a file where a directory should be) or a completely silent
487 # non-persistence (an unwritable parent -- set_cookie and localStorage still
488 # report success, and you only discover the loss when a "restored" session is
489 # empty). Doing it up front turns both into a clean croak out of new().
490 my ($data_abs, $cache_abs);
491 if (defined $o{data_dir}) {
492 $data_abs = rel2abs($o{data_dir});
493 $cache_abs = rel2abs($o{cache_dir} // "$data_abs/cache");
494 for my $d ([data_dir => $data_abs], [$o{cache_dir} ? 'cache_dir' : 'data_dir/cache' => $cache_abs]) {
495 my ($what, $path) = @$d;
496 Carp::croak("EV::WebKit: $what '$path' exists but is not a directory")
497 if -e $path && !-d _;
498 next if -d $path;
499 eval { File::Path::make_path($path); 1 }
500 or Carp::croak("EV::WebKit: cannot create $what '$path' "
501 . '(is a parent directory writable?): ' . _clean($@));
502 }
503 }
504 my $session = $self->{session} =
505 $ephemeral ? WebKit::NetworkSession->new_ephemeral
506 : defined $o{data_dir} ? WebKit::NetworkSession->new($data_abs, $cache_abs)
507 : WebKit::NetworkSession->new(undef, undef);
508  
509 # Cookie persistence is NOT automatic even for a non-ephemeral session --
510 # WebKit keeps cookies in memory until set_persistent_storage names a file.
511 # So a plain data_dir session persists localStorage/IndexedDB (those follow
512 # the session's data directory) but NOT cookies, unless we point the cookie
513 # store at a file too. Give data_dir its own default cookie file inside
514 # itself, so "data_dir persists the whole session" is actually true;
515 # cookie_jar, when given, overrides that location with the caller's specific
516 # (queryable) path -- that is how the two compose.
517 #
518 # Called immediately after session construction, before context/ucm/view
519 # exist and before any load -- confirmed sufficient. Only cookies with a
520 # real max_age/expiry are written; session cookies are excluded by design
521 # (RFC 6265) -- use save_cookies/load_cookies to snapshot those.
522 my $fmt = $o{jar_format} // 'sqlite';
523 # Validate BEFORE it reaches GI. An unknown enum nick makes GI croak, and
524 # the die-unwind frees a transient WebKitCookieManager whose unref inside
525 # libwebkitgtk SIGSEGVs -- uncatchable by eval, and with no message at all.
526 # 'txt' is the natural slip, since jar_format => 'text' writes cookies.txt.
527 Carp::croak("EV::WebKit: jar_format => '$fmt' is invalid (use 'sqlite' or 'text')")
528 unless $fmt eq 'sqlite' || $fmt eq 'text';
529 # the derived cookie file's extension follows the format, so a text jar is
530 # not misleadingly named cookies.sqlite.
531 my $jar = defined $o{cookie_jar} ? rel2abs($o{cookie_jar})
532 : defined $data_abs ? "$data_abs/cookies." . ($fmt eq 'text' ? 'txt' : 'sqlite')
533 : undef;
534 if (defined $jar) {
535 $session->get_cookie_manager->set_persistent_storage($jar, $fmt);
536 }
537 $self->set_proxy($o{proxy}) if exists $o{proxy};
538 # network_fingerprint and the two interception hooks are all served by the
539 # same in-process proxy: it is the only place that sees plaintext requests,
540 # since WebKit runs networking in a separate process and exposes no mutable
541 # request hook of its own.
542 if ($o{network_fingerprint} || $o{on_request} || $o{on_response}) {
543 my $why = $o{network_fingerprint} ? 'network_fingerprint'
544 : $o{on_request} ? 'on_request'
545 : 'on_response';
546 eval { require Proxy::Impersonate; 1 }
547 or Carp::croak("EV::WebKit: $why requested but Proxy::Impersonate is unavailable: $@");
548 # A Proxy::Impersonate without these hooks accepts the option and
549 # silently ignores it, so nothing would be intercepted -- a confusing
550 # no-op rather than an error. Refuse instead.
551 if ($o{on_request} || $o{on_response}) {
552 eval { Proxy::Impersonate->VERSION('0.01'); 1 }
553 or Carp::croak("EV::WebKit: $why requires Proxy::Impersonate 0.01 or newer "
554 . '(found ' . (Proxy::Impersonate->VERSION // '?') . ')');
555 }
556 # The preset NAME, which is what curl_target keys on. The hashref form
557 # carries it in {profile}, and resolve() drops it, so it has to come
558 # from the caller's own argument. Handing curl_target the ref itself
559 # looked up its stringified address: under network_fingerprint that
560 # croaked, and under on_request alone it missed silently and fell back
561 # to desktop Chrome -- a Safari identity above with a Chrome JA3/JA4
562 # below. Derived once here so both branches agree.
563 my $fp_name = ref $o{fingerprint} eq 'HASH'
564 ? $o{fingerprint}{profile}
565 : $o{fingerprint};
566 my $target;
567 if ($o{network_fingerprint}) {
568 $target = ($o{network_fingerprint} =~ /\D/)
569 ? $o{network_fingerprint} # explicit target override
570 : EV::WebKit::Fingerprint::curl_target($fp_name); # derive from the profile name
571 Carp::croak("EV::WebKit: no curl target for fingerprint '"
572 . (ref $o{fingerprint} ? '(custom)' : $o{fingerprint})
573 . "' -- pass network_fingerprint => '<curl-target>'")
574 unless $target;
575 }
576 else {
577 # on_request alone. The proxy re-originates through
578 # libcurl-impersonate whatever happens, so SOME target is presented
579 # -- there is no passthrough mode. Follow the fingerprint profile if
580 # there is one, else a current Chrome, and say so in the POD rather
581 # than changing the connection fingerprint silently.
582 $target = $fp_name ? EV::WebKit::Fingerprint::curl_target($fp_name) : undef;
583 $target ||= 'chrome131';
584 }
585 my $proxy = Proxy::Impersonate->new(
586 impersonate => $target,
587 listen => '127.0.0.1:0',
588 ($o{on_request} ? (on_request => $o{on_request}) : ()),
589 ($o{on_response} ? (on_response => $o{on_response}) : ()),
590 # identity headers only make sense alongside a resolved profile
591 ($fp ? (override_headers => EV::WebKit::Fingerprint::identity_headers($fp),
592 high_entropy_headers => EV::WebKit::Fingerprint::high_entropy_headers($fp)) : ()),
593 );
594 $self->{proxy} = $proxy;
595 $self->{network_fingerprint} = $target;
596 $session->set_tls_errors_policy('ignore'); # accept the proxy self-signed cert
597 $self->set_proxy('http://127.0.0.1:' . $proxy->port);
598 }
599 my $ucm = $self->{ucm} = WebKit::UserContentManager->new;
600 # a per-instance (not the default/shared) WebContext -- construct-only,
601 # and confirmed (live, WebKitGTK 2.52.4) to coexist fine alongside
602 # network-session/user-content-manager as construct props on WebView --
603 # so mock_scheme() below has a controllable context to register schemes on.
604 my $context = $self->{context} = WebKit::WebContext->new;
605 if ($fonts) {
606 # Before the first load, because the sandbox is assembled when the web
607 # process spawns and fontconfig reads its environment once, at startup.
608 eval { $context->add_path_to_sandbox(@$_); 1 } for @{ $fonts->{bind} };
609 # Process-wide, not per-view: fontconfig has no per-context input. Two
610 # browsers in one process with different font sets is not a thing this
611 # can express -- see the POD.
612 $ENV{FONTCONFIG_FILE} = $fonts->{conf};
613 }
614 # The extension directory must be set BEFORE the web process spawns, which
615 # is long before anyone asks for a frame -- so load it whichever feature
616 # wants it. It carries frame addressing as well as the fingerprint spoof,
617 # and with no initialization data it defines nothing, leaving a plain
618 # instance exactly as it was.
619 require EV::WebKit::Fingerprint; # for _so_dir; the profile path requires it too
620 if (EV::WebKit::Fingerprint::available()) {
621 $context->set_web_process_extensions_directory(EV::WebKit::Fingerprint::_so_dir());
622 }
623 # The extension needs the SAME registry bootstrap the user script installs,
624 # because it evaluates in a world of its own: a script world obtained in the
625 # web process is not the one a UI-process user script was injected into,
626 # even under the same name (checked -- window.__evwk is simply absent
627 # there). Hand it the source instead of keeping a second copy in C.
628 {
629 my %ud = (boot => Glib::Variant->new('s', $BOOT));
630 $context->set_web_process_extensions_initialization_user_data(
631 EV::WebKit::Fingerprint::gvariant($fp, $o{seed}, \%ud));
632 }
633 if ($fp) {
634 # align the Accept-Language header (and the Intl/ICU default locale) with
635 # the profile's navigator.languages, so the network layer does not
636 # contradict the spoofed JS languages.
637 $context->set_preferred_languages($fp->{languages}) if $fp->{languages};
638 }
639 my $view = $self->{view} = Glib::Object::new('WebKit::WebView',
640 'web-context' => $context, 'network-session' => $session, 'user-content-manager' => $ucm);
641  
642 my $ua = $fp ? $fp->{user_agent} : $o{user_agent};
643 $self->set_user_agent($ua) if defined $ua; # native: sets the header AND navigator.userAgent; validated setter (croaks on a UA WebKit would silently drop)
644 $view->get_settings->set('enable-developer-extras', 1) if $o{devtools};
645  
646 my $win = $self->{win} = Gtk4::Window->new;
647 $win->set_default_size($w, $h);
648 $win->set_child($view);
649 $win->set_title($o{title}) if defined $o{title};
650 $self->_build_chrome if $o{chrome}; # titlebar must precede present (realized-window warning)
651 $win->present;
652  
653 # The user closed the window (the titlebar X, alt-F4, the window manager).
654 # Without this the instance just kept running with no window: every in-flight
655 # callback dangled, the natives leaked, and the caller's EV::run went on
656 # spinning over nothing. It only bites the VISIBLE mode (chrome => 1 on a
657 # real display), which is why the whole headless test suite never saw it.
658 #
659 # Everything is done on a CLEAN TICK, not here: this fires inside GTK's
660 # dispatch frame, and the caller's on_close will want to EV::break (or
661 # quit()), neither of which is safe nested in a dispatch frame. Deferring
662 # also makes on_close the one SIGNAL-dispatched handler EV::break is safe
663 # from -- the others in that group all run nested. (The result callbacks,
664 # on_load, on_error and on_navigate are safe too; they never run nested.
665 # See the POD.)
666 #
667 # Returning TRUE stops GTK destroying the window itself. It must not: an
668 # in-flight op still holds the view, and having the window ripped out from
669 # under it is the whole reason quit() tears down in a defined order. quit()
670 # destroys the window a tick later, after resolving everything.
671 weaken(my $wclose = $self);
672 $win->signal_connect('close-request' => sub {
673 local $IN_DISPATCH = 1;
674 my $self = $wclose or return 0; # gone already: let GTK close it
675 # Guard on a flag set SYNCHRONOUSLY, right here -- not on {_dead}, which
676 # quit() only sets a tick later when the deferred teardown runs. Two
677 # close-requests before that tick (a double-click on the X, a window
678 # manager re-sending the delete, fast Alt-F4) would otherwise each defer
679 # their own closure and fire on_close twice, even though the window is
680 # correctly destroyed only once. on_close promises exactly once.
681 return 0 if $self->{_dead} || $self->{_closing};
682 $self->{_closing} = 1;
683 my $on_close = $self->{on_close};
684 $self->_defer_final(sub {
685 $self->quit; # resolve every in-flight callback, then destroy the window
686 # Guarded, like every other handler dispatch: a throwing on_close must
687 # not escape into EV's generic $EV::DIED with no context.
688 if ($on_close) {
689 unless (eval { $on_close->(); 1 }) {
690 warn "EV::WebKit: on_close callback died: $@";
691 }
692 }
693 });
694 return 1;
695 });
696  
697 # The signal handlers registered below are the only closures in new() that
698 # would otherwise capture $self STRONGLY, forming a $self -> {view} ->
699 # signal-connection -> closure -> $self cycle that plain refcounting can
700 # never break -- so a bare `undef $b` (no quit()) would leak the native
701 # window/view/session for the life of the process (quit() breaks it by
702 # deleting {view}, but DESTROY only runs once the cycle is already broken).
703 # Capture only a WEAK ref and guard on it first, exactly like the async
704 # completions and the chrome handlers do; while the instance is alive the
705 # caller's own reference keeps it valid, and once they drop it these
706 # handlers stop firing (the view is torn down in DESTROY -> quit).
707 weaken(my $wself = $self);
708 $view->signal_connect('load-changed' => sub {
709 my ($ev_view, $ev) = @_;
710 my $self = $wself or return;
711 # $ev_view (this call's own first arg, NOT the outer $view lexical)
712 # -- closing over $view here would make this permanently-retained
713 # signal-handler closure hold its own strong reference to the view
714 # it is itself attached to (view -> closure -> view), a cycle plain
715 # refcounting can never break; confirmed live via t/46-collectability.t.
716 # A bare per-call arg carries no such risk: it isn't part of the
717 # closure's captured environment, only of this one invocation.
718 if ($ev eq 'redirected') {
719 # a server-side redirect changes which uri is actually in
720 # flight for the CURRENT pending nav -- keep the tracked target
721 # in step (WebKit's own load-failed, below, reports the
722 # redirected-to uri as its failing_uri, not the originally
723 # requested one) so a subsequent real failure isn't mistaken
724 # for a stray signal belonging to some other nav.
725 my $p = $self->{pending};
726 $p->[3] = $ev_view->get_uri if $p && defined $p->[3];
727 }
728 elsif ($ev eq 'started' || $ev eq 'committed') {
729 # Mark the CURRENT pending nav as having seen its own
730 # load-changed lifecycle begin. This lets the load-failed
731 # handler (below) recognize a failure that arrives while the
732 # current pending has NOT yet started as necessarily belonging
733 # to some other, already-superseded nav -- see the started-since
734 # gate there, and _start_nav where this flag is initialized.
735 my $p = $self->{pending};
736 if ($p) {
737 $p->[4] = 1;
738 # Capture the pending's OWN committed uri (R11) -- see
739 # _finished_is_stray below for why this is only trustworthy
740 # from 'committed' (a real commit), not 'started' (merely
741 # optimistic/provisional, and exactly the kind of
742 # easily-superseded value that caused the finished-path bug
743 # in the first place). Harmless to also (re)write it here on
744 # a later 'committed' after a redirect -- get_uri() at that
745 # point is the post-redirect destination, which is what a
746 # subsequent 'finished' should be compared against anyway.
747 $p->[5] = $ev_view->get_uri if $ev eq 'committed';
748 }
749 # 'committed' is the moment WebKit switches to the new document, so
750 # the view's uri is now definitively the new page's. Report it
751 # however the navigation began -- note this sits OUTSIDE the
752 # if ($p) above, deliberately. on_load cannot do this job: it fires
753 # only for a navigation THIS API started (_finish_nav returns early
754 # when there is no {pending}), so a page that navigates itself --
755 # which is exactly what a human clicking a link in a visible window
756 # looks like -- changed the page and told nobody at all. Deferred
757 # like every other callback, and dead-gated: a navigate event after
758 # quit() is meaningless.
759 if ($ev eq 'committed' && $self->{on_navigate}) {
760 # Guarded like on_load: a throwing on_navigate must not escape
761 # into EV's generic handler with no context.
762 my $uri = $ev_view->get_uri;
763 $self->_defer(sub {
764 my $s = $wself or return;
765 return if $s->{_dead};
766 my $cb = $s->{on_navigate} or return;
767 unless (eval { $cb->($uri); 1 }) {
768 warn "EV::WebKit: on_navigate callback died: $@";
769 }
770 });
771 }
772 }
773 elsif ($ev eq 'finished') {
774 # R11: the success path used to resolve _finish_nav
775 # unconditionally, with NO identity check at all -- unlike
776 # load-failed's gates above. A SUPERSEDED nav's own belated
777 # 'finished' (WebKit still completes a request handed a response
778 # even after being superseded/cancelled -- confirmed live) would then
779 # resolve the CURRENT pending with a FALSE SUCCESS, and the real
780 # nav's own outcome would arrive to find {pending} already
781 # consumed. _finished_is_stray (shared with _update_chrome, so
782 # chrome's icon doesn't flip on a stray event either) implements
783 # the three gates documented there. The started-since one applies
784 # only to a nav with a known TARGET: a bfcache-restored
785 # back()/forward() carries none, and can legitimately jump straight
786 # to 'finished' with no preceding started/committed at all --
787 # gating a history nav on that absence would hang a real,
788 # successful navigation, which is worse than the bug.
789 if ($self->_finished_is_stray($ev_view->get_uri)) {
790 # Consumed: some tail signal for whatever this pending
791 # superseded has now been accounted for. Left in place, a
792 # stale entry could wrongly suppress a LATER, unrelated
793 # legitimate no-commit (bfcache-style) finished for a
794 # future pending -- _start_nav also resets this set on every
795 # new nav, as a second, independent backstop against that.
796 $self->{_superseded} = {};
797 }
798 else {
799 $self->_finish_nav(undef);
800 }
801 }
802 });
803 # A page that moves its OWN url during the load -- history.pushState /
804 # replaceState from an inline script, an SPA router settling its route,
805 # location.hash restoring an anchor -- changes the view's uri between
806 # 'committed' and 'finished' WITHOUT any new load-changed cycle. The
807 # committed-uri gate in _finished_is_stray then compares the pending's
808 # captured uri against a uri that has legitimately moved on, calls the
809 # navigation's OWN 'finished' stray, and go() runs out the full timeout on
810 # a page that loaded perfectly. Measured on pushState, replaceState and
811 # location.hash alike.
812 #
813 # So keep the capture current: once this pending has COMMITTED, the view's
814 # uri moving is that same document moving, and is exactly what a later
815 # 'finished' must be compared against.
816 #
817 # The gate is `defined $p->[5]` -- the pending has committed -- and nothing
818 # else. Not is_loading: the inline script runs while the load is still in
819 # flight, so is_loading is true exactly when this matters (measured), and
820 # gating on it fixes nothing. A pending that has not committed is untouched,
821 # which is the case that matters: its uri is still provisional, and trusting
822 # a provisional uri is what caused the finished-path bug this gate exists
823 # for. A superseding navigation gets a fresh pending with [5] undef, so it
824 # is untouched too.
825 $view->signal_connect('notify::uri' => sub {
826 my $self = $wself or return;
827 return if $self->{_dead} || !$self->{view};
828 my $p = $self->{pending} or return;
829 return unless defined $p->[5];
830 my $u = $self->{view}->get_uri;
831 $p->[5] = $u if defined $u && length $u;
832 });
833  
834 $view->signal_connect('load-failed' => sub {
835 my (undef, undef, $failing_uri, $gerr) = @_;
836 my $self = $wself or return;
837 my $p = $self->{pending};
838 # A load-failed is a STRAY signal for an already-superseded nav
839 # (not the current pending) -- and must be ignored rather than
840 # consume/mis-resolve the current pending (see _finish_nav) -- when
841 # ANY of three independent gates says so:
842 #
843 # - target-uri gate: the current pending tracks a target (go()
844 # only -- see _start_nav callers) and failing_uri differs from
845 # it. When a new go()/load_html()/etc. supersedes an in-flight
846 # one, WebKit cancels the old load rather than silently dropping
847 # it, and that cancellation surfaces here -- for the OLD uri --
848 # sometime after {pending} has already moved on to the new nav.
849 # Unconditional on started state: a mismatch is always stray.
850 #
851 # - started-since gate: the current pending has NOT yet seen its
852 # own load-changed started/committed (see above). WebKit always
853 # starts a load (emits 'started') before it can fail it, so a
854 # failure arriving for a not-yet-started pending cannot be that
855 # pending's own -- it must be the tail cancellation of whatever
856 # nav this one just superseded. This is what protects
857 # back()/forward()/reload()/load_html(), which have no
858 # predictable target uri to compare (a history entry's
859 # destination isn't known ahead of time, and load_html has none
860 # at all: $p->[3] stays undef for these, so the target-uri gate
861 # above is inert for them). Confirmed live: the stray
862 # cancellation for a just-superseded nav consistently arrives
863 # before the new pending's own first load-changed event.
864 #
865 # - superseded-uri gate (R11): failing_uri is the identity of a nav
866 # this pending itself superseded (see _start_nav/{_superseded}).
867 # This closes a gap the other two can miss once the current
868 # pending has ALREADY started (started-since gate now inert) but
869 # a stray tail for an EARLIER superseded nav still arrives late --
870 # e.g. a real network cancellation that takes longer to surface
871 # than the new pending's own near-instant start. Skipped when it
872 # would agree with the target-uri gate's own "known and matching"
873 # exemption (below), so it never re-flags a genuine same-uri
874 # failure as stray. A MATCH here is a pure read, never a write:
875 # WebKit fires load-changed:finished as the terminal event of
876 # EVERY load's lifecycle even after a load-failed for the same
877 # load (confirmed live -- a superseded nav's cancellation reliably
878 # produces BOTH) -- if this branch consumed/deleted the
879 # {_superseded} entry, the finished handler's OWN check would
880 # arrive moments later to find nothing left to compare against,
881 # and wrongly resolve the still-uncommitted current pending.
882 # _finished_is_stray itself never clears the set -- it is a pure
883 # read, because two independently-connected listeners consult it
884 # for the same event. The set is cleared in exactly two places:
885 # the 'finished' branch ABOVE (this is the separately-connected
886 # load-failed handler), and _start_nav.
887 #
888 # A pending with a KNOWN target whose failing_uri actually MATCHES
889 # it is never stray via any gate, regardless of started state --
890 # that is a genuine failure of the current pending's own nav.
891 if ($p && defined $failing_uri) {
892 # ...and it must ALSO have started. A load abandoned by a timeout
893 # stays in flight; retrying the SAME uri cancels it, and that
894 # cancellation's load-failed matches the retry's target exactly --
895 # so without this the exemption handed the retry an instant bogus
896 # failure while its own load was still running. WebKit always emits
897 # 'started' before it can fail a load (the axiom the started-since
898 # gate below already rests on), so a matching failure that arrives
899 # before the retry's own 'started' cannot be the retry's.
900 my $known_and_matching = defined $p->[3] && $failing_uri eq $p->[3] && $p->[4];
901 my $stray = !$known_and_matching && (
902 defined $p->[3] ? 1 # target known, didn't match -- always stray
903 : ( !$p->[4] # not started yet, or...
904 || $self->{_superseded}{$failing_uri} ) ); # ...a known superseded identity
905 return 1 if $stray;
906 }
907 my $why = ref $gerr ? $gerr->message : $gerr;
908 # An unanswered auth challenge is cancelled, and WebKit then reports the
909 # navigation as a plain "Load request cancelled" -- which reads like the
910 # caller cancelled it. Name the actual cause. The host is compared as a
911 # whole authority, never as a substring: subresources and iframes raise
912 # challenges too, and 'b.example/?u=a.example' contains 'a.example'.
913 # _start_nav clears the note, so it can only annotate a failure of the
914 # navigation the challenge belonged to.
915 if (my $c = $self->{_auth_challenge}) {
916 my ($fh) = $failing_uri =~ m{\A[a-z][a-z0-9+.-]*://(?:[^/?\#\@]*\@)?([^/:?\#]+)}i;
917 if (defined $fh && defined $c->{host} && lc $fh eq lc $c->{host}) {
918 delete $self->{_auth_challenge};
919 $why .= " (HTTP authentication was required and $c->{why})";
920 }
921 }
922 $self->_finish_nav("load failed: $failing_uri: $why");
923 return 1; # handled
924 });
925  
926 # The renderer died (crashed, hit the memory limit, or was terminated).
927 # WebKit says so at once -- but it sends no load-failed for the page that
928 # was loading, so without this a navigation in flight simply waits out the
929 # WHOLE timeout (30s by default) and then reports a misleading 'timeout',
930 # for something that became impossible the instant this fired. Route it
931 # through the same path as any other nav failure: _finish_nav resolves the
932 # pending navigation if there is one, and otherwise reports it to on_error,
933 # so a crash is never silent. (WebKit relaunches the web process on the next
934 # load, so the instance stays usable.)
935 $view->signal_connect('web-process-terminated' => sub {
936 my (undef, $reason) = @_; # nick: crashed / exceeded-memory-limit / terminated-by-api
937 my $self = $wself or return;
938 return if $self->{_dead};
939 $self->_finish_nav('web process terminated: ' . ($reason // 'unknown'));
940 });
941  
942 $self->_install_boot;
943  
944 $self->{on_console} = $o{on_console};
945 $self->_install_console if $self->{on_console};
946  
947 $self->{on_dialog} = $o{on_dialog};
948 $view->signal_connect('script-dialog' => sub {
949 my (undef, $d) = @_;
950 local $IN_DISPATCH = 1; # on_dialog runs nested in WebKit's dispatch frame -- see quit
951 my $self = $wself or return 1; # $self gone (teardown): suppress the native dialog, nothing to deliver to
952 return 1 if $self->{_dead}; # torn down: suppress the native dialog, nothing to deliver to
953 my $dlg = EV::WebKit::Dialog->_new($d);
954 # A die in on_dialog MUST NOT abort this handler before its `return 1`:
955 # that return is what suppresses WebKit's own blocking native dialog, so
956 # skipping it leaves the page's alert/confirm/prompt unresolved and
957 # wedges the WebView (and, since GI shares one dispatch, can starve
958 # dialog delivery to sibling instances too). Catch it, still resolve the
959 # dialog (dismiss) so the page can proceed, and always return handled.
960 if ($self->{on_dialog}) {
961 unless (eval { $self->{on_dialog}->($dlg); 1 }) {
962 my $err = $@;
963 eval { $dlg->dismiss }; # best-effort: give the page a definite answer
964 warn "EV::WebKit: on_dialog callback died: $err";
965 }
966 }
967 else { $dlg->dismiss }
968 return 1; # handled -- suppress WebKit's own blocking native dialog
969 });
970  
971 $self->{on_policy} = $o{on_policy};
972 $self->{popups} = $o{popups} // 'follow';
973 Carp::croak("EV::WebKit: popups must be 'follow' or 'block'")
974 unless $self->{popups} eq 'follow' || $self->{popups} eq 'block';
975 $view->signal_connect('decide-policy' => sub {
976 my (undef, $decision, $type_nick) = @_; # type_nick: navigation-action/new-window-action/response
977 local $IN_DISPATCH = 1; # on_policy runs nested in WebKit's dispatch frame -- see quit
978 my $self = $wself or return 0; # $self gone: WebKit applies its own default (allow)
979 return 0 if $self->{_dead}; # torn down: let WebKit apply its own default
980 # A target=_blank navigation is ALLOWED by default and then silently
981 # dropped: WebKit goes on to ask for a window through 'create', which a
982 # one-view browser does not answer, so the click does nothing at all --
983 # no navigation, no error, no event. Follow it in this view instead, on
984 # a clean tick, since starting a navigation inside WebKit's own dispatch
985 # frame is the wedge $IN_DISPATCH exists for. popups => 'block' keeps
986 # the drop; an on_policy handler owns the decision itself and is left
987 # alone. window.open does NOT arrive here -- see the 'create' handler.
988 if (($type_nick // '') eq 'new-window-action'
989 && $self->{popups} eq 'follow' && !$self->{on_policy}) {
990 my $nu = eval { $decision->get_navigation_action->get_request->get_uri };
991 if (defined $nu && length $nu) {
992 $decision->ignore;
993 weaken(my $ws = $self);
994 $self->_defer(sub { my ($u) = @_; my $b = $ws or return; $b->go($u) }, $nu);
995 return 1;
996 }
997 }
998 return 0 unless $self->{on_policy}; # not handled -- WebKit applies its own default (allow)
999 # WebKitNavigationPolicyDecision (navigation-action/new-window-action) only
1000 # exposes get_navigation_action; WebKitResponsePolicyDecision (response) only
1001 # exposes get_request directly -- try the navigation path first, fall back
1002 # to the response path (each ->can/eval-guarded since the two are siblings,
1003 # not a subtype chain, so the "wrong" accessor is simply absent).
1004 my $uri = eval { $decision->get_navigation_action->get_request->get_uri }
1005 // eval { $decision->get_request->get_uri };
1006 my $info = EV::WebKit::Policy->_new($decision, $type_nick, $uri);
1007 # A throw here would escape into GI's dispatch, which merely prints it
1008 # and ignores it -- so neither allow nor block would run and WebKit
1009 # would apply its OWN default, which is allow. on_policy is a gate: a
1010 # page that can make the handler die (a uri that breaks its parsing)
1011 # would then walk straight through it. Fail CLOSED, loudly. A handler
1012 # that decided BEFORE it died keeps its decision.
1013 unless (eval { $self->{on_policy}->($info); 1 }) {
1014 warn "EV::WebKit: on_policy callback died (blocking the navigation): $@";
1015 $info->block unless $info->{done};
1016 return 1;
1017 }
1018 $info->allow unless $info->{done}; # default allow if handler didn't decide
1019 return 1; # handled
1020 });
1021  
1022 # window.open() is not a policy decision in WebKitGTK: decide-policy never
1023 # fires for it at all (measured), and WebKit asks for a window through
1024 # 'create' instead. A one-view browser that answers nothing there leaves the
1025 # call returning null with no navigation, no error and no event -- so
1026 # popups => 'follow' has to be honoured here as well as in decide-policy,
1027 # which only ever saw target=_blank. on_policy is deliberately NOT consulted:
1028 # there is no decision object to give it, and inventing one would document a
1029 # policy hook that cannot allow, ignore or download.
1030 $view->signal_connect(create => sub {
1031 my (undef, $nav) = @_;
1032 local $IN_DISPATCH = 1;
1033 my $self = $wself or return undef;
1034 return undef if $self->{_dead} || $self->{popups} ne 'follow';
1035 my $nu = eval { $nav->get_request->get_uri };
1036 return undef unless defined $nu && length $nu;
1037 weaken(my $ws = $self);
1038 $self->_defer(sub { my ($u) = @_; my $b = $ws or return; $b->go($u) }, $nu);
1039 return undef; # no second view: the navigation happens in this one
1040 });
1041  
1042 # HTTP (and proxy) authentication. WITHOUT this connected at all, a 401
1043 # challenge is answered by nobody: WebKit waits, the navigation resolves
1044 # 'timeout' after the full instance timeout, and status() is undef -- so the
1045 # caller cannot even tell a 401 from an unreachable host. Cancelling by
1046 # default turns that into an immediate, legible failure (the server's own
1047 # 401 body, with status 401), and a handler can supply credentials instead.
1048 $self->{on_authenticate} = $o{on_authenticate};
1049 $view->signal_connect(authenticate => sub {
1050 my (undef, $req) = @_;
1051 local $IN_DISPATCH = 1; # runs nested in WebKit's dispatch frame -- see quit
1052 my $self = $wself or return 0; # gone: let WebKit do its default
1053 return 0 if $self->{_dead};
1054 my $host = eval { $req->get_host };
1055 # However the challenge goes unanswered, record WHY: WebKit reports all
1056 # three the same way, as a bare "Load request cancelled".
1057 my $note = sub { $self->{_auth_challenge} = { host => $host, why => $_[0] } if defined $host };
1058 my $cb = $self->{on_authenticate};
1059 unless ($cb) {
1060 $note->('no on_authenticate handler answered it');
1061 eval { $req->cancel };
1062 return 1;
1063 }
1064 my $auth = EV::WebKit::Auth->_new($req);
1065 # Fail CLOSED, like on_policy and on_file_chooser: a handler that dies
1066 # must not leave the page waiting on a challenge nobody answered.
1067 unless (eval { $cb->($auth); 1 }) {
1068 warn "EV::WebKit: on_authenticate callback died (cancelling the request): $@";
1069 unless ($auth->{done}) { $note->('the on_authenticate handler died'); eval { $req->cancel } }
1070 return 1;
1071 }
1072 if (!$auth->{done}) { $note->('the on_authenticate handler answered nothing'); eval { $req->cancel } }
1073 elsif ($auth->{done} eq 'cancel') { $note->('the on_authenticate handler cancelled it') }
1074 return 1;
1075 });
1076  
1077 # File upload. Without a handler this stays UNhandled (return 0) so WebKit
1078 # runs its own native GTK file chooser exactly as before -- connecting the
1079 # signal must not change what an interactive user sees. With a handler, the
1080 # page's <input type=file> can be driven headlessly, which is otherwise
1081 # impossible: the value of a file input cannot be set from JavaScript.
1082 $self->{on_file_chooser} = $o{on_file_chooser};
1083 $view->signal_connect('run-file-chooser' => sub {
1084 my (undef, $req) = @_;
1085 local $IN_DISPATCH = 1; # runs nested in WebKit's dispatch frame -- see quit
1086 my $self = $wself or return 0; # gone: let WebKit do its default
1087 return 0 if $self->{_dead};
1088 my $cb = $self->{on_file_chooser} or return 0; # unhandled -> native dialog
1089 my $fc = EV::WebKit::FileChooser->_new($req);
1090 # Fail CLOSED, like on_policy: a handler that dies must not leave the
1091 # page waiting on a chooser that never resolves. Cancel and report
1092 # handled, so the upload is refused rather than hanging the form.
1093 unless (eval { $cb->($fc); 1 }) {
1094 warn "EV::WebKit: on_file_chooser callback died (cancelling the chooser): $@";
1095 eval { $req->cancel } unless $fc->{done};
1096 return 1;
1097 }
1098 # A handler that decided nothing gets the same treatment: an unanswered
1099 # request is a hung page, so make the refusal explicit.
1100 eval { $req->cancel } unless $fc->{done};
1101 return 1;
1102 });
1103  
1104 # Downloads. WebKit asks for a destination via the download's own
1105 # decide-destination; nothing is written until we answer, so a download with
1106 # no handler is cancelled rather than landing somewhere unasked.
1107 $self->{on_download} = $o{on_download};
1108 $session->signal_connect('download-started' => sub {
1109 my (undef, $dl) = @_;
1110 local $IN_DISPATCH = 1;
1111 my $self = $wself or return;
1112 return if $self->{_dead};
1113 my $d = EV::WebKit::Download->_new($self, $dl);
1114 # Keep the wrapper alive for the download's lifetime: the signal
1115 # closures below are the only thing referencing it, and its per-download
1116 # callbacks live on it. Dropped in _finish.
1117 $self->{_downloads}{$d->{seq}} = $d;
1118 # Indexed by the native's identity, which is how download() finds this
1119 # wrapper -- see there for why the uri cannot be the key.
1120 $self->{_dl_native}{ $d->{native} } = $d;
1121 # Claim the destination/callback parked by download(), if this is one of
1122 # ours. A page-initiated download matches nothing and falls through to
1123 # on_download below, exactly as before.
1124 if (my $want = delete $self->{_dl_want}{ $d->{native} }) {
1125 # Callback FIRST: the parked entry is already gone, so until it is on
1126 # the wrapper it is reachable from nowhere, and anything that throws
1127 # in between strands it. The eval is belt-and-braces (download() has
1128 # already normalised the path) -- a throw escaping into GLib here
1129 # would also leave decide-destination unconnected, letting WebKit
1130 # choose the destination itself.
1131 $d->on_finish($want->{cb}) if $want->{cb};
1132 unless (eval { $d->save_to($want->{dest}); 1 }) {
1133 my $e = _clean($@) || 'could not set the download destination';
1134 warn "EV::WebKit: $e";
1135 eval { $dl->cancel };
1136 $d->_finish(undef, $e);
1137 return;
1138 }
1139 }
1140 # Handler ids kept: these closures capture $d, and $d holds the native as
1141 # {dl} -- a cycle refcounting cannot break. Broken in _unhook.
1142 push @{ $d->{sig} }, $dl->signal_connect('decide-destination' => sub {
1143 my (undef, $suggested) = @_;
1144 # The ONE download signal that calls user code synchronously (WebKit
1145 # wants the answer before writing anything), so it carries the guard
1146 # its siblings do. finished/failed reach user code only via _defer,
1147 # on a clean tick, and do not need it.
1148 local $IN_DISPATCH = 1;
1149 my $s = $wself or return 0;
1150 $d->{suggested} = $suggested;
1151 # dest may have been chosen up-front by on_download (below); if not,
1152 # ask the handler now that the suggested name is known.
1153 unless (defined $d->{dest}) {
1154 my $cb = $s->{on_download};
1155 if ($cb) {
1156 unless (eval { $cb->($d); 1 }) {
1157 warn "EV::WebKit: on_download callback died (cancelling the download): $@";
1158 }
1159 }
1160 }
1161 unless (defined $d->{dest}) {
1162 # Nobody named a destination. Cancelling is the only safe
1163 # answer: WebKit's own default would write into the user's
1164 # Downloads directory, which an automation run must not do
1165 # behind the caller's back.
1166 eval { $dl->cancel };
1167 $d->_finish(undef, 'no destination set (call save_to in on_download)');
1168 return 1;
1169 }
1170 $dl->set_allow_overwrite(1) if $d->{overwrite};
1171 $dl->set_destination($d->{dest});
1172 return 1; # handled -- we set it
1173 });
1174 push @{ $d->{sig} }, $dl->signal_connect(finished => sub {
1175 my $s = $wself or return;
1176 # 'finished' also fires after a cancel; _finish dedupes, so the
1177 # cancel path's error is the one that reaches the caller.
1178 $d->_finish($d->{dest}, undef);
1179 });
1180 push @{ $d->{sig} }, $dl->signal_connect(failed => sub {
1181 my (undef, $gerr) = @_;
1182 my $s = $wself or return;
1183 my $msg = eval { $gerr->message } || 'download failed';
1184 $d->_finish(undef, $msg);
1185 });
1186 return;
1187 });
1188  
1189 return $self;
1190 }
1191  
1192 # call from new(): inject boot script once the ucm exists.
1193 sub _install_boot {
1194 my ($self) = @_;
1195 # Inject the registry into the dedicated isolated world (NOT the page's
1196 # main world) so page script can neither read nor overwrite it, and its
1197 # marshalling natives are beyond the page's reach. See $EVWK_WORLD.
1198 my $us = WebKit::UserScript->new_for_world($BOOT, 'all-frames', 'start', $EVWK_WORLD, undef, undef);
1199 $self->{ucm}->add_script($us);
1200 }
1201  
1202 # Install the console proxy: a user script that wraps console.log/warn/error/info
1203 # in the page's MAIN world (it has to override the console the page's own code
1204 # calls) and posts each line to a script-message handler.
1205 #
1206 # Installed ON DEMAND -- from new() when on_console was given, and from the
1207 # on_console accessor otherwise. Until something actually wants console output
1208 # there is no reason to touch the page at all. Idempotent.
1209 #
1210 # NOTE: user scripts are injected at document-start, so enabling on_console after
1211 # a page has loaded takes effect from the NEXT navigation.
1212 sub _install_console {
1213 my $self = shift;
1214 return if $self->{_console_installed}++;
1215 my $ucm = $self->{ucm} or return;
1216 weaken(my $wself = $self);
1217 $ucm->register_script_message_handler('evwk', undef);
1218 $ucm->signal_connect('script-message-received' => sub {
1219 my (undef, $val) = @_;
1220 local $IN_DISPATCH = 1; # on_console runs nested in WebKit's dispatch frame -- see quit
1221 my $self = $wself or return;
1222 return if $self->{_dead}; # torn down: the page is gone, do not call back into user code
1223 my $text = eval { $val->to_string };
1224 return unless defined $text && $self->{on_console};
1225 # A throw here would escape into GI's dispatch (which merely prints and
1226 # ignores it), so guard it as on_dialog/on_policy do: a console line is
1227 # never worth destabilising the page over.
1228 unless (eval { $self->{on_console}->($text); 1 }) {
1229 warn "EV::WebKit: on_console callback died: $@";
1230 }
1231 });
1232 my $proxy = <<'JS';
1233 (function(){ try {
1234 const post = (t)=>window.webkit.messageHandlers.evwk.postMessage(String(t));
1235 ['log','warn','error','info'].forEach(k=>{ const o=console[k];
1236 console[k]=function(){ try{post(k+': '+Array.from(arguments).join(' '))}catch(e){}; return o.apply(console,arguments); }; });
1237 } catch(e){} })();
1238 JS
1239 $ucm->add_script(WebKit::UserScript->new($proxy, 'all-frames', 'start', undef, undef));
1240 return;
1241 }
1242  
1243 # Inject caller-supplied JavaScript. Returns an EV::WebKit::UserContent handle
1244 # whose ->remove takes just this script out. Options: at 'start'|'end' (default
1245 # end -- the DOM exists), world 'main'|'isolated' (default main), frames
1246 # 'all'|'top' (default all), allow/deny arrayrefs of URL-pattern globs. Takes
1247 # effect from the NEXT navigation (WebKit injects user content at load time).
1248 sub add_user_script {
1249 my ($self, $source) = (shift, shift);
1250 Carp::croak('add_user_script: options must be name => value pairs') if @_ % 2;
1251 $self->_add_user_content('script', $source, @_);
1252 }
1253  
1254 # Inject caller-supplied CSS. Like add_user_script but for stylesheets: no world
1255 # option (a world does not change a stylesheet's effect on the document, so it is
1256 # not surfaced -- we use UserStyleSheet->new, not ->new_for_world); adds a level
1257 # 'author'|'user' (default author; 'user' beats page CSS -- use it to hide elements).
1258 sub add_user_style {
1259 my ($self, $source) = (shift, shift);
1260 Carp::croak('add_user_style: options must be name => value pairs') if @_ % 2;
1261 $self->_add_user_content('style', $source, @_);
1262 }
1263  
1264 sub _add_user_content {
1265 my ($self, $kind, $source, %opt) = @_;
1266 Carp::croak("add_user_$kind: source is required") unless defined $source;
1267 Carp::croak("add_user_$kind: source must be a string, not a " . ref($source) . " ref") if ref $source;
1268 # WebKit stores the source as a NUL-terminated C string, so an embedded NUL
1269 # silently truncates the injected content. A NUL in JS/CSS is never
1270 # intentional. allow/deny below are checked for the same thing, where a
1271 # truncated pattern stops matching rather than matching too much.
1272 Carp::croak("add_user_$kind: source contains a NUL byte (it would silently truncate the injected content)")
1273 if index($source, "\0") >= 0;
1274 # Reject unknown option keys: a typo (wrld => / dney =>) would otherwise be
1275 # silently dropped, falling back to a MORE PERMISSIVE default (main world, no
1276 # allow/deny) -- a silent, security-relevant misfire for an injection API.
1277 # Valid keys are kind-specific.
1278 my %known = (frames => 1, allow => 1, deny => 1,
1279 $kind eq 'script' ? (at => 1, world => 1) : (level => 1));
1280 if (my @bad = sort grep { !$known{$_} } keys %opt) {
1281 Carp::croak("add_user_$kind: unknown option(s): @bad");
1282 }
1283 Carp::croak("add_user_$kind: browser closed") if $self->{_dead} || !$self->{ucm};
1284  
1285 my $frames = $USER_FRAMES{ $opt{frames} // 'all' }
1286 // Carp::croak("add_user_$kind: frames => '$opt{frames}' is invalid (use 'all' or 'top')");
1287  
1288 # allow/deny pass straight to WebKit as URL-pattern globs. Validate strictly:
1289 # an undef entry becomes a NULL that truncates the GStrv WebKit receives
1290 # (silently dropping later patterns -- a deny-list bypass), and an EMPTY list
1291 # is read by WebKit as no-constraint (match EVERY url), the opposite of the
1292 # likely intent. So require an arrayref, non-empty, of defined plain strings.
1293 # Omit the key entirely for "every url".
1294 for my $k (qw/allow deny/) {
1295 next unless defined $opt{$k};
1296 Carp::croak("add_user_$kind: $k => ... must be an arrayref of URL-pattern strings")
1297 unless ref $opt{$k} eq 'ARRAY';
1298 @{ $opt{$k} } or Carp::croak("add_user_$kind: $k => [] is empty; omit $k to match every url");
1299 # A zero-length string is never a valid WebKit URL pattern (it just never
1300 # matches -- silently), so reject it alongside undef/refs. (We cannot
1301 # validate the full pattern grammar; an otherwise-malformed pattern is
1302 # WebKit's to reject and simply will not match -- see the POD.)
1303 # ...and no embedded NUL. WebKit stores each pattern as a C string, so a
1304 # NUL truncates it: "mk://blocked\0zz/*" became "mk://blocked", which
1305 # matches nothing, and the script it was meant to deny RAN on the denied
1306 # url -- measured. Same class as the source check above, and the worse
1307 # direction, since deny is a security boundary.
1308 for (@{ $opt{$k} }) {
1309 defined && !ref && length
1310 or Carp::croak("add_user_$kind: $k entries must be non-empty strings");
1311 index($_, "\0") >= 0
1312 and Carp::croak("add_user_$kind: $k entry contains a NUL byte "
1313 . "(it would silently truncate the pattern, so it would stop matching)");
1314 }
1315 }
1316 my ($allow, $deny) = @opt{qw/allow deny/};
1317  
1318 my $native;
1319 if ($kind eq 'script') {
1320 my $at = $USER_AT{ $opt{at} // 'end' }
1321 // Carp::croak("add_user_script: at => '$opt{at}' is invalid (use 'start' or 'end')");
1322 my $world = $opt{world} // 'main';
1323 Carp::croak("add_user_script: world => '$world' is invalid (use 'main' or 'isolated')")
1324 unless $USER_WORLD_OK{$world};
1325 $native = $world eq 'isolated'
1326 ? WebKit::UserScript->new_for_world($source, $frames, $at, $USER_WORLD, $allow, $deny)
1327 : WebKit::UserScript->new($source, $frames, $at, $allow, $deny);
1328 $self->{ucm}->add_script($native);
1329 }
1330 else { # style
1331 my $level = $USER_LEVEL{ $opt{level} // 'author' }
1332 // Carp::croak("add_user_style: level => '$opt{level}' is invalid (use 'author' or 'user')");
1333 $native = WebKit::UserStyleSheet->new($source, $frames, $level, $allow, $deny);
1334 $self->{ucm}->add_style_sheet($native);
1335 }
1336  
1337 my $id = ++$self->{_user_seq};
1338 $self->{"_user_${kind}s"}{$id} = $native;
1339 return EV::WebKit::UserContent->_new($self, $id, $kind);
1340 }
1341  
1342 # Remove every user script / stylesheet THIS caller added, and only those. Must
1343 # NOT use WebKit's remove_all_scripts/remove_all_style_sheets: those also remove
1344 # the module's own injected BOOT (the $EVWK_WORLD registry find()/html() need)
1345 # and console proxy. Loop per-item removal over our registry instead.
1346 sub remove_all_user_scripts { my $self = shift; $self->_remove_all_user('script'); return $self }
1347 sub remove_all_user_styles { my $self = shift; $self->_remove_all_user('style'); return $self }
1348  
1349 sub _remove_all_user {
1350 my ($self, $kind) = @_;
1351 return if $self->{_dead} || !$self->{ucm};
1352 my $reg = $self->{"_user_${kind}s"} or return;
1353 my $m = $kind eq 'style' ? 'remove_style_sheet' : 'remove_script';
1354 $self->{ucm}->$m($_) for values %$reg;
1355 %$reg = ();
1356 return;
1357 }
1358  
1359 # Get/set accessors for the event handlers. Without these the constructor is the
1360 # only way to set one, so anything that wants to observe a browser has to BE the
1361 # code that created it -- which is exactly what a layer built on top (see
1362 # EV::WebKit::Control) must not require. With them, such a layer can CHAIN:
1363 #
1364 # my $prev = $b->on_console;
1365 # $b->on_console(sub { $prev->(@_) if $prev; ...also mine... });
1366 #
1367 # through the public API, instead of reaching into the object.
1368 for my $h (qw/on_load on_error on_close on_navigate on_console on_dialog on_policy
1369 on_file_chooser on_download on_authenticate/) {
1370 no strict 'refs';
1371 *{__PACKAGE__ . "::$h"} = sub {
1372 my $self = shift;
1373 return $self->{$h} unless @_;
1374 my $cb = shift;
1375 Carp::croak("$h: expected a code reference") if defined $cb && ref $cb ne 'CODE';
1376 $self->{$h} = $cb;
1377 # The console proxy touches the page, so it is only injected once
1378 # something actually wants console output. Enabling it late is legal --
1379 # from the next navigation (user scripts run at document start).
1380 $self->_install_console if $h eq 'on_console' && $cb && !$self->{_dead};
1381 return $self;
1382 };
1383 }
1384  
1385 # chrome => 1: minimal browser chrome -- a GNOME HeaderBar titlebar with
1386 # back/forward/reload buttons and an address entry. Orthogonal to automation:
1387 # the WebView is unchanged and stays fully scriptable.
1388 sub _build_chrome {
1389 my ($self) = @_;
1390 my $hb = Gtk4::HeaderBar->new;
1391 my %btn;
1392 for (['back', 'go-previous-symbolic', 'Back'],
1393 ['forward', 'go-next-symbolic', 'Forward'],
1394 ['reload', 'view-refresh-symbolic', 'Reload']) {
1395 my ($k, $icon, $tip) = @$_;
1396 $btn{$k} = Gtk4::Button->new_from_icon_name($icon);
1397 $btn{$k}->set_tooltip_text($tip);
1398 $hb->pack_start($btn{$k});
1399 }
1400 my $entry = Gtk4::Entry->new;
1401 $entry->set_hexpand(1);
1402 $hb->set_title_widget($entry);
1403 $self->{win}->set_titlebar($hb);
1404 my $c = $self->{chrome} = { hb => $hb, entry => $entry, %btn, loading => 0, settle => {} };
1405 $btn{back}->set_sensitive(0);
1406 $btn{forward}->set_sensitive(0);
1407  
1408 # These closures capture $self and/or $c -- and $c itself cross-references
1409 # these very widgets (e.g. $c->{reload} == $btn{reload}), so the reload
1410 # handler alone forms a self-contained Perl reference cycle (button ->
1411 # its own clicked-closure -> $c -> same button) that quit()'s `delete
1412 # $self->{chrome}` cannot touch (a closure's captured lexical is its own
1413 # independent reference, invisible from outside the closure) and that
1414 # ordinary refcounting can never collect. Weaken every such captured
1415 # reference (classic gperl `my $x = $wx or return;` pattern) so these
1416 # closures can neither hold $self alive forever nor sustain a cycle among
1417 # themselves.
1418 weaken(my $wself = $self);
1419 weaken(my $wc = $c);
1420 weaken(my $wentry = $entry);
1421  
1422 $entry->signal_connect(activate => sub {
1423 my $self = $wself or return;
1424 my $entry = $wentry or return;
1425 my $url = $entry->get_text;
1426 return unless defined $url && length $url;
1427 $url = "https://$url" unless $url =~ m{^[a-z][a-z0-9+.-]*://}i;
1428 $self->go($url);
1429 });
1430 $btn{back}->signal_connect(clicked => sub { my $self = $wself or return; $self->back });
1431 $btn{forward}->signal_connect(clicked => sub { my $self = $wself or return; $self->forward });
1432 $btn{reload}->signal_connect(clicked => sub {
1433 my $self = $wself or return;
1434 my $c = $wc or return;
1435 $c->{loading} ? $self->stop : $self->reload;
1436 });
1437  
1438 # chrome-only updater; the core nav handler is connected separately in new()
1439 $self->{view}->signal_connect('load-changed' => sub {
1440 my (undef, $ev) = @_;
1441 my $self = $wself or return;
1442 $self->_update_chrome($ev);
1443 });
1444 # The address bar must also follow a SINGLE-PAGE-APP navigation. A
1445 # history.pushState (how Reddit, GitHub, most modern sites change the URL on
1446 # a click) fires NO load-changed cycle -- so the load-changed handler above
1447 # never runs, and the bar (plus back/forward sensitivity and the window
1448 # title) would show the old URL while the page has moved on. The view's uri
1449 # property DOES change on pushState, so refresh from notify::uri too.
1450 # Harmless on a normal load (it just calls _refresh_chrome, which is
1451 # idempotent). Weakened like every other chrome handler -- the view holds
1452 # this closure, and a strong $self would be an uncollectable cycle.
1453 $self->{view}->signal_connect('notify::uri' => sub {
1454 my $self = $wself or return;
1455 $self->_refresh_chrome unless $self->{_dead};
1456 });
1457 # ...and the same for the title (the window caption), which likewise does not
1458 # exist yet at load-changed:finished -- it arrives from the web process
1459 # shortly after, and this is what says exactly when.
1460 $self->{view}->signal_connect('notify::title' => sub {
1461 my $self = $wself or return;
1462 $self->_refresh_chrome unless $self->{_dead};
1463 });
1464 return;
1465 }
1466  
1467 sub _update_chrome {
1468 my ($self, $ev) = @_;
1469 my $c = $self->{chrome} or return;
1470 # R11 (cosmetic): a stray 'finished' for an already-superseded nav must
1471 # not flip the reload/stop icon to not-loading either -- the real nav is
1472 # still genuinely in flight. Shares the exact same verdict as the core
1473 # load-changed handler in new() via _finished_is_stray (a pure read, safe
1474 # to call from here too even though this handler fires FIRST -- see
1475 # _build_chrome, where this is connected before the core handler).
1476 return if $ev eq 'finished' && $self->_finished_is_stray($self->{view}->get_uri);
1477 if ($ev eq 'started') {
1478 $c->{loading} = 1;
1479 $c->{reload}->set_icon_name('process-stop-symbolic');
1480 }
1481 elsif ($ev eq 'finished') {
1482 $c->{loading} = 0;
1483 $c->{reload}->set_icon_name('view-refresh-symbolic');
1484 # No re-refresh timer for the late-arriving title here: notify::title
1485 # (connected in _build_chrome) delivers it exactly when it lands.
1486 }
1487 $self->_refresh_chrome;
1488 }
1489  
1490 sub _refresh_chrome {
1491 my ($self) = @_;
1492 return if $self->{_dead} || !$self->{view};
1493 my $c = $self->{chrome} or return;
1494 my $uri = $self->uri;
1495 $c->{entry}->set_text($uri // '') unless $c->{entry}->has_focus; # never clobber typing
1496 my $title = $self->title;
1497 $self->{win}->set_title($title) if defined $title && length $title;
1498 $c->{back}->set_sensitive($self->can_go_back);
1499 $c->{forward}->set_sensitive($self->can_go_forward);
1500 return;
1501 }
1502  
1503 sub _clean { my $e = shift // ''; $e =~ s/ at \S+ line \d+\.?\s*$//; $e }
1504  
1505 # --- frame addressing over the web-process extension ------------------------
1506 # The UI process can only run script in the main frame, and the same-origin
1507 # policy stops that script reaching a cross-origin child. The extension has no
1508 # such wall (see the "Addressing an iframe" POD), so anything frame-scoped goes
1509 # through it as a WebKitUserMessage instead.
1510  
1511 sub _page_msg {
1512 my ($self, $name, $params, $cb) = @_;
1513 if ($self->{_dead} || !$self->{view}) { $self->_defer_final($cb, undef, 'browser closed'); return }
1514 # Without the extension there is nothing on the far end to answer, and the
1515 # failure would otherwise read as a timeout rather than a missing build.
1516 if (!EV::WebKit::Fingerprint::available()) {
1517 $self->_defer_final($cb, undef,
1518 'frame addressing needs the web-process extension, which is not built here'
1519 . ' (see EV::WebKit::Fingerprint)');
1520 return;
1521 }
1522 my $msg = eval { WebKit::UserMessage->new($name, $params) };
1523 if (!$msg) { $self->_defer_final($cb, undef, 'frames: cannot build a page message: ' . _clean($@)); return }
1524 $cb = $self->_op_track($cb);
1525 # Bounded like every other async op (see the timeout constructor option):
1526 # a web process that never answers must not leave the caller waiting until
1527 # quit. Cancellable + timer, same shape and same $done guard as _call_js.
1528 my $cancel = Glib::IO::Cancellable->new;
1529 my $timer = EV::timer($self->{timeout}, 0, sub { $cancel->cancel });
1530 weaken(my $wself = $self); # same GI retention reasoning as _call_js
1531 my $done = 0;
1532 $self->{view}->send_message_to_page($msg, $cancel, sub {
1533 my (undef, $res) = @_;
1534 return if $done; $done = 1; $timer->stop;
1535 # Release the captures -- GI never lets go of this closure, so what it
1536 # still holds is held for the life of the process. See _call_js.
1537 my ($lcb, $lcancel) = ($cb, $cancel);
1538 undef $cb; undef $cancel; undef $timer;
1539 my $self = $wself or return;
1540 my $reply = eval { $self->{view} && $self->{view}->send_message_to_page_finish($res) };
1541 if (!$reply) {
1542 return $self->_defer($lcb, undef, 'timeout') if $lcancel->is_cancelled;
1543 return $self->_defer($lcb, undef, 'frames: the web process did not answer: ' . _clean($@));
1544 }
1545 $self->_defer($lcb, $reply->get_parameters, undef);
1546 });
1547 return;
1548 }
1549  
1550 # Every frame the web process currently knows about, outermost first is NOT
1551 # guaranteed -- ids are opaque and page-scoped, so resolve through here rather
1552 # than holding one across a navigation.
1553 sub frames {
1554 my ($self, $cb) = @_;
1555 Carp::croak('frames: callback must be a code reference') if ref $cb ne 'CODE';
1556 $self->_page_msg('evwk.frames', undef, sub {
1557 my ($p, $err) = @_;
1558 return $cb->(undef, $err) if $err;
1559 return $cb->(undef, 'frames: unexpected reply from the web process') unless $p;
1560 my @out;
1561 for my $n (0 .. $p->n_children - 1) {
1562 my $c = $p->get_child_value($n);
1563 push @out, { id => $c->get_child_value(0)->get_uint64,
1564 url => $c->get_child_value(1)->get_string,
1565 main => ($c->get_child_value(2)->get_boolean ? 1 : 0) };
1566 }
1567 $cb->(\@out, undef);
1568 });
1569 return $self;
1570 }
1571  
1572 # Turn a frame spec into an id. { url => } is the form a caller can write down
1573 # -- a frame has no name in this API -- and { id => } takes one straight from
1574 # frames(), which is the only way to tell two frames with the SAME url apart.
1575 sub _resolve_frame {
1576 my ($self, $spec, $what, $cb) = @_;
1577 # An id needs no lookup: if it has gone stale the eval reports it as gone,
1578 # which is the same answer a lookup would have produced one round trip later.
1579 return $cb->($spec->{id}, undef) if defined $spec->{id};
1580 my $want = $spec->{url};
1581 $self->frames(sub {
1582 my ($list, $err) = @_;
1583 return $cb->(undef, $err) if $err;
1584 my @hit = grep { ref $want eq 'Regexp' ? $_->{url} =~ $want : $_->{url} eq $want }
1585 grep { !$_->{main} } @$list;
1586 return $cb->(undef, "$what: no frame matched url") unless @hit;
1587 return $cb->(undef, "$what: " . scalar(@hit) . ' frames matched url; it must identify one')
1588 if @hit > 1;
1589 $cb->($hit[0]{id}, undef);
1590 });
1591 }
1592  
1593 # The frame-side twin of _call_js: same prologue, same JSON contract, same
1594 # surrogate repair -- but synchronous, since the reply crosses a process
1595 # boundary as a plain string and cannot await a promise on the far side.
1596 sub _call_js_frame {
1597 my ($self, $frame_id, $code, $args, $cb) = @_;
1598 # A callback-less call is legal all through this API ($el->click with
1599 # nothing to do afterwards), and _defer's own undef guard does not cover
1600 # the completion below, which calls $cb directly.
1601 $cb ||= sub {};
1602 my $body = eval {
1603 'const A = ' . _enc($args // {}) . ";\n"
1604 . 'const __wf = (s) => s.toWellFormed ? s.toWellFormed()'
1605 # The replacement is a JAVASCRIPT escape, not a literal U+FFFD: this file
1606 # has no `use utf8`, so a literal would be three Latin-1 characters here and
1607 # six bytes by the time the web process saw it (_call_js does the same).
1608 . ' : s.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD");' . "\n"
1609 . 'const __r = (() => { ' . $code . " })();\n"
1610 . 'return JSON.stringify(__r === undefined ? null : __r,'
1611 . ' (k, v) => typeof v === "string" ? __wf(v) : v);';
1612 };
1613 if ($@) { $self->_defer_final($cb, undef, 'encode error: ' . _clean($@)); return }
1614 my $params = eval { Glib::Variant->new_tuple([ Glib::Variant->new_uint64($frame_id),
1615 Glib::Variant->new_string($body) ]) };
1616 if (!$params) { $self->_defer_final($cb, undef, 'frame call: ' . _clean($@)); return }
1617 $self->_page_msg('evwk.eval', $params, sub {
1618 my ($p, $err) = @_;
1619 return $cb->(undef, $err) if $err;
1620 return $cb->(undef, 'frame call: unexpected reply') unless $p && $p->n_children == 2;
1621 my $ok = $p->get_child_value(0)->get_boolean;
1622 my $out = $p->get_child_value(1)->get_string;
1623 return $cb->(undef, _clean($out)) unless $ok;
1624 my $val = eval { _dec($out) };
1625 return $cb->(undef, 'frame call: undecodable result: ' . _clean($@)) if $@;
1626 $cb->($val, undef);
1627 });
1628 return;
1629 }
1630  
1631 sub _call_js {
1632 my ($self, $code, $args, $cb, $main_world) = @_;
1633 # Default (falsy/omitted) -> the isolated $EVWK_WORLD: find/find_all,
1634 # html, every Element atom and wait_for's polling all reach the registry
1635 # and marshal via the world's own natives. Only script()/script_async()
1636 # pass a true $main_world to run in the page's own world. This defaults
1637 # to the SECURE world, so a caller that forgets the flag fails safe (and
1638 # loudly -- a script test that needs page globals would break at once).
1639 my $world = $main_world ? undef : $EVWK_WORLD;
1640 if ($self->{_dead} || !$self->{view}) { $self->_defer_final($cb, undef, 'browser closed'); return }
1641 $cb = $self->_op_track($cb); # so quit() mid-flight resolves this callback with 'browser closed' instead of dropping it
1642 # The replacer repairs lone UTF-16 surrogates. JavaScript strings are not
1643 # required to be well-formed unicode, and JSON.stringify faithfully emits an
1644 # unpaired \uD800-\uDFFF -- which a strict JSON decoder (rightly) refuses. So
1645 # ONE stray half-character anywhere in the document made html() fail
1646 # outright, and any element whose text contained one was unreadable, while
1647 # WebKit's own native title() handled the same data by substituting U+FFFD.
1648 # Do what WebKit does. (toWellFormed is ES2024 and present in this engine;
1649 # the manual fallback keeps an older one working.)
1650 my $body = eval {
1651 'const A = ' . _enc($args // {}) . ";\n"
1652 . 'const __wf = (s) => s.toWellFormed ? s.toWellFormed()'
1653 . ' : s.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD");' . "\n"
1654 . 'const __r = await (async () => { ' . $code . " })();\n"
1655 . 'return JSON.stringify(__r === undefined ? null : __r,'
1656 . ' (k, v) => typeof v === "string" ? __wf(v) : v);';
1657 };
1658 if ($@) { $self->_defer_final($cb, undef, 'encode error: ' . _clean($@)); return }
1659 my $cancel = Glib::IO::Cancellable->new;
1660 # kept alive only by the completion closure below capturing it -- otherwise GC'd once this sub returns (EV timer-lifetime gotcha).
1661 my $timer = EV::timer($self->{timeout}, 0, sub { $cancel->cancel });
1662 my $done = 0;
1663 # Glib::Object::Introspection's GAsyncReadyCallback marshalling does not
1664 # release its hold on this closure after it fires (confirmed in isolation
1665 # with a bare WebKit::WebView, independent of EV::WebKit's own object
1666 # graph) -- this closure's captured $self (a private copy made by the
1667 # `my ($self,...) = @_;` above, independent of the CALLER's own variable)
1668 # is therefore an unreachable, unbreakable-from-outside strong reference
1669 # that neither dropping the caller's reference nor quit() can ever touch.
1670 # Capture only a WEAK reference so this closure can't keep the browser
1671 # alive by itself; $cb (the user's own callback) is intentionally left
1672 # strong since nothing else owns it.
1673 weaken(my $wself = $self);
1674 $self->{view}->call_async_javascript_function(
1675 $body, -1, undef, $world, undef, $cancel, sub {
1676 # DO NOT REMOVE THE $done GUARD. This completion can be invoked more
1677 # than once (a cancellation racing a real completion), and the
1678 # _finish below must be called AT MOST ONCE per GAsyncResult --
1679 # calling it twice corrupts the heap ("free(): corrupted unsorted
1680 # chunks"). Nothing in the test suite can catch its removal: $cb is
1681 # _op_track'd, so a second delivery is deduped there and every
1682 # assertion still passes -- the only symptom is the corruption, and
1683 # only in some runs. Verified by mutation testing, which is the only
1684 # reason this is known.
1685 return if $done; $done = 1; $timer->stop;
1686 # RELEASE THE CAPTURES. GI never lets go of this closure, so
1687 # whatever it still holds is held for the life of the process --
1688 # which is why $self is weak above. $cb, $cancel and $timer were
1689 # not, so every call leaked the user's whole callback graph, a
1690 # Cancellable and an EV timer: measured at ~3.3 KB per call, and
1691 # unbounded in wait_for/wait_for_js, whose poll issues one of these
1692 # PER TICK. Move them into lexicals that die with this invocation
1693 # and clear the captured ones -- the same "empty what the retained
1694 # closure holds" discipline as _release_natives_later below.
1695 # $timer is already stopped, and the only other holder of $cancel is
1696 # that timer's own closure, so clearing both frees it.
1697 my ($lcb, $lcancel) = ($cb, $cancel);
1698 undef $cb; undef $cancel; undef $timer;
1699 my $self = $wself or return; # browser already torn down -- nothing to deliver to
1700 my $jsc = eval { $self->{view}->call_async_javascript_function_finish($_[1]) };
1701 if (my $e = $@) {
1702 $self->_defer($lcb, undef, $lcancel->is_cancelled ? 'timeout' : _clean($e));
1703 return;
1704 }
1705 my $val = eval { _dec($jsc->to_string) };
1706 return $self->_defer($lcb, undef, "marshal error: "._clean($@)) if $@;
1707 $self->_defer($lcb, $val, undef);
1708 });
1709 return;
1710 }
1711  
1712 # script/script_async run the user's own JS in the page's MAIN world (final
1713 # arg true) so it sees the page's globals/libraries; find/atoms stay isolated.
1714 sub script {
1715 my ($s,$js,$cb) = @_;
1716 Carp::croak('script: callback must be a code reference') if defined $cb && ref $cb ne 'CODE';
1717 _need_js(script => $js);
1718 $s->_call_js($js, {}, $cb, 1);
1719 return $s;
1720 }
1721  
1722 # script/script_async's snippet guard. Deliberately NOT shared with
1723 # find_js/find_all_js, which keep their own inline check: those also reject an
1724 # EMPTY snippet, because a snippet that is supposed to RETURN an element cannot
1725 # be empty, while running empty JS is merely a no-op. A ref here is nearly
1726 # always the callback with the snippet omitted -- which binds to $js
1727 # positionally and leaves $cb undef, so nothing ever answers.
1728 sub _need_js {
1729 my ($what, $js) = @_;
1730 Carp::croak("$what: a JavaScript snippet is required") unless defined $js;
1731 Carp::croak("$what: the JavaScript must be a plain string, not a " . ref($js) . ' reference'
1732 . (ref $js eq 'CODE' ? ' (did you omit the snippet and pass only a callback?)' : ''))
1733 if ref $js;
1734 return;
1735 }
1736 sub script_async {
1737 my ($s,$body,$a,$cb) = @_;
1738 ($a, $cb) = ({}, $a) if !defined $cb && ref $a eq 'CODE';
1739 Carp::croak('script_async: callback must be a code reference') if defined $cb && ref $cb ne 'CODE';
1740 _need_js(script_async => $body);
1741 $s->_call_js($body, $a, $cb, 1);
1742 return $s;
1743 }
1744  
1745 # Send a key to whatever currently has focus (else document.body). For keyboard
1746 # HANDLERS -- Escape closing a modal, Enter submitting a form that listens for
1747 # it, arrow keys driving a widget.
1748 #
1749 # It does NOT type: a synthetic KeyboardEvent has isTrusted false, and no engine
1750 # performs the default text-insertion for one, so press('a') leaves an input's
1751 # value untouched. Element->type is what edits a field. Saying so here because
1752 # the opposite assumption is the obvious one, and it fails silently.
1753 # Named keys: the keyCode a listener is likely to check. event.code for these is
1754 # the name itself.
1755 my %KEYCODE = (
1756 Enter => 13, Escape => 27, Tab => 9, Backspace => 8, Delete => 46,
1757 ArrowUp => 38, ArrowDown => 40, ArrowLeft => 37, ArrowRight => 39,
1758 Home => 36, End => 35, PageUp => 33, PageDown => 34,
1759 );
1760 # Punctuation, as one table of [code, keyCode] so the two cannot disagree.
1761 # Neither is derivable from the character: event.code names the PHYSICAL key,
1762 # and keyCode is the legacy US-layout OEM value. Deriving keyCode from the
1763 # ordinal is not merely wrong but ALIASES other keys -- ord('.') is 46, which is
1764 # Delete, and ord("'") is 39, ArrowRight.
1765 my %CHAR = (
1766 ' ' => ['Space', 32], '-' => ['Minus', 189], '=' => ['Equal', 187],
1767 '[' => ['BracketLeft', 219], ']' => ['BracketRight',221], '\\'=> ['Backslash', 220],
1768 ';' => ['Semicolon', 186], "'" => ['Quote', 222], '`' => ['Backquote', 192],
1769 ',' => ['Comma', 188], '.' => ['Period', 190], '/' => ['Slash', 191],
1770 );
1771 # ($code, $keyCode) for a key name.
1772 sub _key_ids {
1773 my $k = shift;
1774 return ($k, $KEYCODE{$k}) if exists $KEYCODE{$k};
1775 return @{ $CHAR{$k} } if exists $CHAR{$k};
1776 return ('Key' . uc $k, ord uc $k) if $k =~ /\A[A-Za-z]\z/; # KeyA .. KeyZ, 65-90
1777 return ('Digit' . $k, ord $k) if $k =~ /\A[0-9]\z/; # Digit0 .. Digit9, 48-57
1778 return ($k, 0) if length($k) > 1; # an unlisted named key (F5, Insert)
1779 # A shifted or non-ASCII character names no physical key by itself -- which
1780 # one produced it depends on the layout. Report what a browser reports for a
1781 # key it cannot identify, rather than inventing a value that aliases another.
1782 return ('', 0);
1783 }
1784 sub press {
1785 my ($self, $key, %o) = (shift, shift);
1786 # The trailing argument is the callback if it IS one, or if the count says
1787 # one is there. Either test alone is wrong:
1788 # ref-only -- a mistyped callback stays in the option list and is
1789 # reported as a malformed option list rather than as the bad
1790 # CALLBACK it is (t/53's croaker sweep asserts the callback
1791 # message, and fails without this half);
1792 # parity-only -- a stray positional modifier with a VALID name ("shift"
1793 # with its value dropped) makes the count even, so an
1794 # appended callback is not popped, lands in %o as that key's
1795 # value, no croak fires, and nothing ever answers. Over the
1796 # control socket that is a hung client.
1797 # Whatever is left after the pop must still pair up, or it is a malformed
1798 # option list and says so instead of warning from in here.
1799 my $cb = (@_ && (ref $_[-1] eq 'CODE' || @_ % 2)) ? pop : undef;
1800 Carp::croak('press: callback must be a code reference')
1801 if defined $cb && ref $cb ne 'CODE';
1802 Carp::croak('press: options must be name => value pairs') if @_ % 2;
1803 %o = @_;
1804 Carp::croak('press: a key name is required') if !defined $key || ref $key || !length $key;
1805 # Stringify before the JSON bridge: an integer crosses as a JSON number, and
1806 # A.key.length below is then undefined, so press(5) sent no keypress.
1807 $key = "$key";
1808 if (my @bad = sort grep { !/^(?:shift|ctrl|alt|meta)$/ } keys %o) {
1809 Carp::croak("press: unknown option(s): @bad (expected shift/ctrl/alt/meta)");
1810 }
1811 my ($code_name, $code) = _key_ids($key);
1812 $self->_call_js(
1813 'const el = document.activeElement || document.body;'
1814 # A KeyboardEvent is a UIEvent and a real one carries the window. Built in
1815 # the isolated world, but WebKit maps it to the page's own on the way.
1816 . 'const init = { key: A.key, code: A.code_name, view: window,'
1817 . ' keyCode: A.code, which: A.code, bubbles: true, cancelable: true,'
1818 . ' shiftKey: !!A.shift, ctrlKey: !!A.ctrl, altKey: !!A.alt, metaKey: !!A.meta };'
1819 . 'const down = new KeyboardEvent("keydown", init);'
1820 . 'const notCancelled = el.dispatchEvent(down);'
1821 # a real browser skips keypress when keydown was prevented, and only sends
1822 # it for character-producing keys at all
1823 # Enter produces a character ("\r") and every engine fires keypress for it,
1824 # which is what makes the legacy onkeypress-checks-13 form handler work.
1825 . 'if (notCancelled && (A.key.length === 1 || A.key === "Enter"))'
1826 . ' el.dispatchEvent(new KeyboardEvent("keypress", init));'
1827 # keyup goes wherever focus is NOW: a keydown handler that moves focus is
1828 # ordinary, and a browser delivers the keyup to the newly focused element.
1829 . 'const up = document.activeElement || document.body;'
1830 . 'up.dispatchEvent(new KeyboardEvent("keyup", init));'
1831 . 'return notCancelled;',
1832 { key => $key, code => $code, code_name => $code_name,
1833 shift => ($o{shift} ? 1 : 0), ctrl => ($o{ctrl} ? 1 : 0),
1834 alt => ($o{alt} ? 1 : 0), meta => ($o{meta} ? 1 : 0) },
1835 $cb);
1836 return $self;
1837 }
1838  
1839 # Scroll the page. Absolute by default; to => 'bottom' for the common
1840 # infinite-scroll case, which needs the document height rather than a guess.
1841 use constant RESIZE_SETTLE => 0.1; # floor before a stable reading counts -- guards against settling on the PRE-resize size, which is possible in principle (two polls before GTK applies anything) though not reproduced here
1842  
1843 # Resize the window (and so the viewport) after construction. window => is
1844 # construct-only, and rebuilding a whole instance to render at 375px wide is a
1845 # poor trade for one GTK call. The resize is asynchronous -- GTK has to round
1846 # trip through the display server -- so this resolves only once the page can
1847 # actually see the new size, and reports what it ACTUALLY got: a window manager
1848 # is free to clamp or ignore the request, and a caller that assumed otherwise
1849 # would screenshot at the old size.
1850 sub resize {
1851 my ($self, $w, $h, $cb) = @_;
1852 Carp::croak('resize: callback must be a code reference') if defined $cb && ref $cb ne 'CODE';
1853 for my $d ([width => $w], [height => $h]) {
1854 Carp::croak("resize: $d->[0] must be a positive integer")
1855 unless defined $d->[1] && !ref $d->[1]
1856 && Scalar::Util::looks_like_number($d->[1]) && $d->[1] >= 1;
1857 }
1858 ($w, $h) = (int $w, int $h);
1859 # A callback-less call is legal all through this API, and the completion
1860 # below calls $cb directly -- without this, _poll_until's timer turned the
1861 # undef dereference into an $EV::DIED warning on every settle.
1862 $cb ||= sub {};
1863 if ($self->{_dead} || !$self->{win}) { $self->_defer_final($cb, undef, 'browser closed'); return $self }
1864 $self->{win}->set_default_size($w, $h);
1865 weaken(my $wself = $self);
1866 my ($t0, $last) = (EV::now);
1867 return $self->_poll_until(
1868 timeout => $self->{timeout},
1869 interval => 0.02,
1870 cb => sub {
1871 my ($got, $err) = @_;
1872 return $cb->($got, undef) unless defined $err;
1873 # ONLY a timeout is an outcome rather than a failure: it means the
1874 # viewport never held still, and the caller still wants the numbers.
1875 # Every other error -- 'browser closed' above all -- is real and must
1876 # be passed through. Collapsing the two reported a phantom success
1877 # with no size at all when quit() flushed a resize in flight.
1878 return $cb->(undef, $err) if $err ne 'timeout';
1879 my $self = $wself or return $cb->(undef, 'browser closed');
1880 $self->_call_js('return { width: window.innerWidth, height: window.innerHeight };', {}, $cb);
1881 },
1882 # Settle on the viewport HOLDING STILL, not on it reaching the requested
1883 # numbers, which it often cannot: chrome => 1 spends part of the window
1884 # on a header bar, and GTK4's own client-side decorations take a few
1885 # pixels more, so asking for 400x320 with chrome yields a 390x264
1886 # viewport (measured). Requiring an exact match there would poll until
1887 # the timeout every single time.
1888 probe => sub {
1889 my ($done) = @_;
1890 my $self = $wself or return;
1891 $self->_call_js('return { width: window.innerWidth, height: window.innerHeight };', {}, sub {
1892 my ($r, $err) = @_;
1893 return $done->(0, undef, $err) if $err;
1894 return $done->(0, undef, undef) unless ref $r eq 'HASH';
1895 my $now = "$r->{width}x$r->{height}";
1896 my $still = defined $last && $last eq $now && EV::now - $t0 >= RESIZE_SETTLE;
1897 $last = $now;
1898 $done->($still ? 1 : 0, $r, undef);
1899 });
1900 },
1901 );
1902 }
1903  
1904 # Page zoom, as a multiplier. Synchronous both ways, like the other view
1905 # properties (settings, user_agent): WebKit applies it to the view directly.
1906 sub zoom {
1907 my ($self, $level) = @_;
1908 return @_ > 1 ? $self : undef if $self->{_dead} || !$self->{view};
1909 return $self->{view}->get_zoom_level if @_ == 1;
1910 Carp::croak('zoom: level must be a positive number')
1911 unless defined $level && !ref $level
1912 && Scalar::Util::looks_like_number($level) && $level > 0;
1913 $self->{view}->set_zoom_level($level + 0);
1914 return $self;
1915 }
1916  
1917 sub scroll {
1918 my $self = shift;
1919 # A TRAILING callback, the way every other async method here spells it.
1920 # Without this, scroll(y => 10, $cb) -- the natural spelling -- put the
1921 # coderef into %o as a KEY: "Odd number of elements in hash assignment"
1922 # from inside this file, and then the caller blamed for an unknown option
1923 # named after their own callback. The named `cb => ...` form still works;
1924 # this is the one method that takes a callback either way.
1925 # ref-OR-parity, as press uses -- but scroll is the one method whose
1926 # callback is also a NAMED option, so a legitimate `cb => $cb` genuinely
1927 # ends in a coderef. Only a coderef that is NOT the value of cb/callback is
1928 # the positional form. Parity alone was not enough: `by` is read as a bare
1929 # truthy flag and never validated, so scroll(by => $cb) is an even list --
1930 # no pop, the coderef becomes by's VALUE, $cb stays undef, every check
1931 # passes, and the callback is never called.
1932 my $named_tail = @_ >= 2 && defined $_[-2] && !ref $_[-2]
1933 && ($_[-2] eq 'cb' || $_[-2] eq 'callback');
1934 my $cb = (@_ && !$named_tail && (ref $_[-1] eq 'CODE' || @_ % 2)) ? pop : undef;
1935 Carp::croak('scroll: options must be name => value pairs') if @_ % 2;
1936 my %o = @_;
1937 for my $k (qw(cb callback)) {
1938 next unless exists $o{$k};
1939 my $named = delete $o{$k};
1940 Carp::croak("scroll: pass the callback once -- either as a trailing argument or as $k => ..., not both")
1941 if defined $cb;
1942 $cb = $named;
1943 }
1944 # The same croak every other async method makes: a non-CODE callback is
1945 # truthy, so it reaches _call_js and dies inside the deferred completion,
1946 # where $EV::DIED swallows it and the caller's EV::run simply hangs.
1947 Carp::croak('scroll: cb must be a code reference') if defined $cb && ref $cb ne 'CODE';
1948 if (my @bad = sort grep { !/^(?:x|y|by|to)$/ } keys %o) {
1949 Carp::croak("scroll: unknown option(s): @bad (expected x/y/by/to)");
1950 }
1951 Carp::croak("scroll: to must be 'top' or 'bottom'")
1952 if defined $o{to} && $o{to} !~ /^(?:top|bottom)$/;
1953 # Numify, so the offsets cross as JSON NUMBERS: a string makes `x += A.x`
1954 # below a CONCATENATION, and scroll(by => 1, y => '50') from 100 scrolled to
1955 # 10050. Right by accident from the origin, so it shows up on the second
1956 # relative scroll -- and an offset out of a config file or @ARGV is a string.
1957 for my $k (qw(x y)) {
1958 next unless defined $o{$k};
1959 Carp::croak("scroll: $k must be a number") unless Scalar::Util::looks_like_number($o{$k});
1960 $o{$k} += 0;
1961 }
1962 $self->_call_js(
1963 'const d = document.documentElement, b = document.body;'
1964 . 'const maxY = Math.max(d.scrollHeight, b ? b.scrollHeight : 0) - window.innerHeight;'
1965 . 'let x = window.scrollX, y = window.scrollY;'
1966 . 'if (A.to === "top") { x = 0; y = 0; }'
1967 . 'else if (A.to === "bottom") { y = maxY > 0 ? maxY : 0; }'
1968 . 'else if (A.by) { x += (A.x || 0); y += (A.y || 0); }'
1969 . 'else { if (A.x !== null) x = A.x; if (A.y !== null) y = A.y; }'
1970 # behavior:"instant" is what makes the position this returns true. Under a
1971 # page's own CSS `scroll-behavior: smooth` the scroll is an ANIMATION, so
1972 # the read-back below sees the offset it started from.
1973 . 'window.scrollTo({ left: x, top: y, behavior: "instant" });'
1974 . 'return { x: window.scrollX, y: window.scrollY };',
1975 { x => $o{x}, y => $o{y}, by => ($o{by} ? 1 : 0), to => $o{to} },
1976 $cb);
1977 return $self;
1978 }
1979  
1980 # The positional-binding trap the Element atoms already guard (see
1981 # EV::WebKit::Element::_need_name). find(sub{...}) bound the callback to $sel
1982 # and left $cb undef, so the encode error went to a no-op and the caller was
1983 # never called at all; find(undef) marshalled a JSON null, which querySelector
1984 # coerces to the type selector "null" -- indistinguishable from "not there".
1985 sub _need_selector {
1986 my ($what, $sel) = @_;
1987 Carp::croak("$what: a selector is required") unless defined $sel;
1988 Carp::croak("$what: the selector must be a plain string, not a " . ref($sel) . ' reference'
1989 . (ref $sel eq 'CODE' ? ' (did you omit the selector and pass only a callback?)' : ''))
1990 if ref $sel;
1991 Carp::croak("$what: the selector must not be empty") unless length $sel;
1992 return;
1993 }
1994  
1995 # Walk into a same-origin iframe chain and hand back its document. Cross-origin
1996 # is a hard stop: contentDocument is null there and nothing in the UI process
1997 # can reach past it, so say which frame and why rather than reporting "not
1998 # found" for an element that is simply out of reach.
1999 my $FRAME_JS = <<'JS';
2000 let d = document;
2001 for (const fs of A.frames) {
2002 const f = d.querySelector(fs);
2003 if (!f) throw new Error('frame not found: ' + fs);
2004 const c = f.contentDocument;
2005 if (!c) throw new Error('frame not reachable, cross-origin: ' + fs);
2006 d = c;
2007 }
2008 JS
2009  
2010 # frame => '#id' or frame => ['#outer', '#inner'] for a nested chain, or
2011 # frame => { url => $str_or_qr } for one addressed by URL. The selector forms
2012 # return an arrayref and are walked by page script; the hash form is returned
2013 # as-is and resolved in the web process, and is the only one that reaches a
2014 # cross-origin frame.
2015 sub _frames_arg {
2016 my ($what, $frame) = @_;
2017 return [] unless defined $frame;
2018 if (ref $frame eq 'HASH') {
2019 if (my @bad = sort grep { $_ ne 'url' && $_ ne 'id' } keys %$frame) {
2020 Carp::croak("$what: unknown frame key(s): @bad");
2021 }
2022 Carp::croak("$what: frame => needs exactly one of url or id")
2023 unless 1 == grep { defined $frame->{$_} } qw(url id);
2024 if (defined(my $i = $frame->{id})) {
2025 Carp::croak("$what: a frame id must be a plain integer")
2026 if ref $i || $i !~ /\A[0-9]+\z/;
2027 return $frame;
2028 }
2029 my $u = $frame->{url};
2030 Carp::croak("$what: the frame url must be a string or a Regexp")
2031 if ref $u && ref $u ne 'Regexp';
2032 Carp::croak("$what: the frame url must not be empty") if !ref $u && !length $u;
2033 return $frame;
2034 }
2035 my @f = ref $frame eq 'ARRAY' ? @$frame : ($frame);
2036 for my $one (@f) {
2037 Carp::croak("$what: each frame must be a plain selector string")
2038 if !defined $one || ref $one;
2039 Carp::croak("$what: a frame selector must not be empty") unless length $one;
2040 }
2041 return \@f;
2042 }
2043  
2044 # find()/find_all() have two paths -- page script for the main frame and a
2045 # same-origin chain, the web process for a frame addressed by URL. Only the
2046 # frame the resulting handle belongs to differs, so the completion is shared:
2047 # same distrust of the page's shape, same errors, one place to change.
2048 sub _find_result {
2049 my ($wself, $fid, $cb, $r, $err) = @_;
2050 return $cb->(undef, $err) if $err;
2051 return $cb->(undef, undef) unless defined $r;
2052 return $cb->(undef, 'find: unexpected result from page (registry tampered?)')
2053 unless ref $r eq 'HASH' && defined $r->{evwk_id};
2054 my $self = $wself or return $cb->(undef, 'browser closed');
2055 $cb->(EV::WebKit::Element->_new($self, $r->{evwk_id}, $r->{evwk_epoch}, $fid), undef);
2056 }
2057  
2058 sub _find_all_result {
2059 my ($wself, $fid, $cb, $r, $err) = @_;
2060 return $cb->(undef, $err) if $err;
2061 return $cb->(undef, 'find_all: unexpected result from page (registry tampered?)')
2062 unless ref $r eq 'ARRAY' && !grep { ref $_ ne 'HASH' || !defined $_->{evwk_id} } @$r;
2063 my $self = $wself or return $cb->(undef, 'browser closed');
2064 $cb->([ map { EV::WebKit::Element->_new($self, $_->{evwk_id}, $_->{evwk_epoch}, $fid) } @$r ], undef);
2065 }
2066  
2067 # find_js/find_all_js: the escape hatch from JavaScript back to a handle.
2068 #
2069 # CSS is the only vocabulary find() has, which shuts out XPath, "the row whose
2070 # cell says Invoice 42", nth-of-match, and -- the one with no workaround at all
2071 # -- anything inside a shadow root, since querySelector does not cross one.
2072 # All four are a couple of lines of JavaScript, and the only thing missing was a
2073 # way to turn the node that JavaScript found into an EV::WebKit::Element. The
2074 # snippet runs in the SAME isolated world as the registry (unlike script(),
2075 # which runs in the page's world and cannot see window.__evwk at all), so the
2076 # node it returns can be put straight into the registry.
2077 my $FIND_JS_ONE = <<'JS';
2078 const __n = (() => { %s })();
2079 if (__n === null || __n === undefined) return null;
2080 if (!(__n instanceof Node)) throw new Error('find_js: the snippet must return a DOM node or null, got ' + typeof __n);
2081 return { evwk_id: window.__evwk.put(__n), evwk_epoch: window.__evwk.epoch };
2082 JS
2083 my $FIND_JS_ALL = <<'JS';
2084 const __l = (() => { %s })();
2085 if (__l === null || __l === undefined) return [];
2086 const __a = Array.isArray(__l) ? __l : (__l && typeof __l.length === 'number' ? Array.from(__l) : null);
2087 if (!__a) throw new Error('find_all_js: the snippet must return an array or NodeList of DOM nodes');
2088 if (__a.some(n => !(n instanceof Node))) throw new Error('find_all_js: every entry must be a DOM node');
2089 return __a.map(n => ({ evwk_id: window.__evwk.put(n), evwk_epoch: window.__evwk.epoch }));
2090 JS
2091  
2092 # The two differ only in which snippet they wrap and which completion they use,
2093 # so the argument handling -- identical to find()'s, parity and all -- lives once.
2094 sub _find_js {
2095 my ($self, $what, $tmpl, $done, $js, @rest) = @_;
2096 my $cb;
2097 if (@rest % 2) {
2098 $cb = pop @rest;
2099 Carp::croak("$what: callback must be a code reference")
2100 if defined $cb && ref $cb ne 'CODE';
2101 }
2102 my %o = @rest;
2103 if (my @bad = sort grep { $_ ne 'frame' && $_ ne 'args' } keys %o) {
2104 Carp::croak("$what: unknown option(s): @bad");
2105 }
2106 Carp::croak("$what: a JavaScript snippet is required") if !defined $js || ref $js;
2107 Carp::croak("$what: the snippet must not be empty") unless length $js;
2108 Carp::croak("$what: args must be a hash reference")
2109 if defined $o{args} && ref $o{args} ne 'HASH';
2110 my $frames = _frames_arg($what => $o{frame});
2111 $cb ||= sub {};
2112 my $body = sprintf $tmpl, $js;
2113 weaken(my $wself = $self);
2114 if (ref $frames eq 'HASH') {
2115 $self->_resolve_frame($frames, $what, sub {
2116 my ($fid, $err) = @_;
2117 return $cb->(undef, $err) if $err;
2118 my $self = $wself or return $cb->(undef, 'browser closed');
2119 $self->_call_js_frame($fid, $body, $o{args} // {},
2120 sub { $done->($wself, $fid, $cb, @_) });
2121 });
2122 return $self;
2123 }
2124 # The selector forms of frame => reach their document by walking
2125 # contentDocument, which a snippet can do for itself; supporting them here
2126 # too would mean rewriting the snippet's idea of `document`, which it does
2127 # not have. So the selector chain is refused rather than silently ignored.
2128 Carp::croak("$what: frame => only takes the { url => ... } or { id => ... } form here"
2129 . ' (a selector chain is a walk the snippet can do itself)')
2130 if @$frames;
2131 $self->_call_js($body, $o{args} // {}, sub { $done->($wself, undef, $cb, @_) });
2132 return $self;
2133 }
2134  
2135 sub find_js { my $s = shift; $s->_find_js(find_js => $FIND_JS_ONE, \&_find_result, @_) }
2136 sub find_all_js { my $s = shift; $s->_find_js(find_all_js => $FIND_JS_ALL, \&_find_all_result, @_) }
2137  
2138 sub find {
2139 my ($self, $sel) = (shift, shift);
2140 # An odd trailing argument is the callback, whatever its type -- so a
2141 # non-coderef there still gets the callback diagnostic instead of being
2142 # read as an option name.
2143 my $cb;
2144 if (@_ % 2) {
2145 $cb = pop;
2146 Carp::croak('find: callback must be a code reference')
2147 if defined $cb && ref $cb ne 'CODE';
2148 }
2149 my %o = @_;
2150 if (my @bad = sort grep { $_ ne 'frame' } keys %o) {
2151 Carp::croak("find: unknown option(s): @bad");
2152 }
2153 my $frames = _frames_arg(find => $o{frame});
2154 _need_selector(find => $sel);
2155 $cb ||= sub {}; # an omitted callback is allowed -- the completion below calls $cb unconditionally, so give it a no-op rather than dying on undef
2156 # The hash form names a frame the main-frame script cannot reach, so the
2157 # whole query runs in the web process instead of walking contentDocument.
2158 # Resolved per call, never cached: a frame id dies with its frame.
2159 if (ref $frames eq 'HASH') {
2160 weaken(my $wf = $self);
2161 $self->_resolve_frame($frames, 'find', sub {
2162 my ($fid, $err) = @_;
2163 return $cb->(undef, $err) if $err;
2164 my $self = $wf or return $cb->(undef, 'browser closed');
2165 $self->_call_js_frame($fid, 'const el = document.querySelector(A.sel); return el ? { evwk_id: window.__evwk.put(el), evwk_epoch: window.__evwk.epoch } : null;', { sel => $sel },
2166 sub { _find_result($wf, $fid, $cb, @_) });
2167 });
2168 return $self;
2169 }
2170 # This wrapper closure (passed as _call_js's $cb) is itself captured
2171 # STRONGLY by _call_js's own (permanently GI-retained) completion
2172 # closure -- so even with _call_js's *own* $self weakened, THIS
2173 # closure's independent capture of $self is a second, equally-permanent
2174 # retaining path unless it too is weakened.
2175 weaken(my $wself = $self);
2176 $self->_call_js(
2177 $FRAME_JS . 'const el = d.querySelector(A.sel); return el ? { evwk_id: window.__evwk.put(el), evwk_epoch: window.__evwk.epoch } : null;',
2178 { sel => $sel, frames => $frames },
2179 sub {
2180 my ($r, $err) = @_;
2181 return $cb->(undef, $err) if $err;
2182 return $cb->(undef, undef) unless defined $r; # not found: undef, no error
2183 # A hostile/buggy page can make ANY JS value come back here (e.g.
2184 # Object.prototype.toJSON polluted to return something else
2185 # entirely) -- never trust the decoded shape before dereferencing
2186 # it: an unvalidated $r->{evwk_id} below would die inside
2187 # _defer's bare EV::timer(0,0,...), which EV's default $EV::DIED
2188 # swallows to stderr, permanently dropping this callback (a
2189 # silent hang, not an error) instead of ever reaching the caller.
2190 return $cb->(undef, 'find: unexpected result from page (registry tampered?)')
2191 unless ref $r eq 'HASH' && defined $r->{evwk_id};
2192 my $self = $wself or return $cb->(undef, 'browser closed');
2193 $cb->(EV::WebKit::Element->_new($self, $r->{evwk_id}, $r->{evwk_epoch}), undef);
2194 });
2195 }
2196  
2197 sub find_all {
2198 my ($self, $sel) = (shift, shift);
2199 # An odd trailing argument is the callback, whatever its type -- so a
2200 # non-coderef there still gets the callback diagnostic instead of being
2201 # read as an option name.
2202 my $cb;
2203 if (@_ % 2) {
2204 $cb = pop;
2205 Carp::croak('find_all: callback must be a code reference')
2206 if defined $cb && ref $cb ne 'CODE';
2207 }
2208 my %o = @_;
2209 if (my @bad = sort grep { $_ ne 'frame' } keys %o) {
2210 Carp::croak("find_all: unknown option(s): @bad");
2211 }
2212 my $frames = _frames_arg(find_all => $o{frame});
2213 _need_selector(find_all => $sel);
2214 $cb ||= sub {}; # omitted callback allowed -- see find()
2215 # The hash form names a frame the main-frame script cannot reach, so the
2216 # whole query runs in the web process instead of walking contentDocument.
2217 # Resolved per call, never cached: a frame id dies with its frame.
2218 if (ref $frames eq 'HASH') {
2219 weaken(my $wf = $self);
2220 $self->_resolve_frame($frames, 'find_all', sub {
2221 my ($fid, $err) = @_;
2222 return $cb->(undef, $err) if $err;
2223 my $self = $wf or return $cb->(undef, 'browser closed');
2224 $self->_call_js_frame($fid, 'return [...document.querySelectorAll(A.sel)].map(e => ({ evwk_id: window.__evwk.put(e), evwk_epoch: window.__evwk.epoch }));', { sel => $sel },
2225 sub { _find_all_result($wf, $fid, $cb, @_) });
2226 });
2227 return $self;
2228 }
2229 # same reasoning as find() above -- weaken.
2230 weaken(my $wself = $self);
2231 $self->_call_js(
2232 $FRAME_JS . 'return [...d.querySelectorAll(A.sel)].map(e => ({ evwk_id: window.__evwk.put(e), evwk_epoch: window.__evwk.epoch }));',
2233 { sel => $sel, frames => $frames },
2234 sub {
2235 my ($r, $err) = @_;
2236 return $cb->(undef, $err) if $err;
2237 # same shape distrust as find() above -- a tampered result (e.g.
2238 # the whole array replaced, or containing non-descriptor
2239 # elements) must degrade to a clean error, never dereference
2240 # blind and die inside _defer's unguarded timer.
2241 return $cb->(undef, 'find_all: unexpected result from page (registry tampered?)')
2242 unless ref $r eq 'ARRAY' && !grep { ref $_ ne 'HASH' || !defined $_->{evwk_id} } @$r;
2243 my $self = $wself or return $cb->(undef, 'browser closed');
2244 $cb->([ map { EV::WebKit::Element->_new($self, $_->{evwk_id}, $_->{evwk_epoch}) } @$r ], undef);
2245 });
2246 }
2247  
2248 # Shared by the core load-changed handler (in new(), above) and
2249 # _update_chrome (below) -- both are independently-connected 'load-changed'
2250 # listeners on the same view (chrome's fires FIRST -- see _build_chrome --
2251 # so this must be a pure, side-effect-free read: it must return the SAME
2252 # verdict for both call sites on the SAME event, before either one acts on
2253 # it). True if a 'finished' event, arriving right now with the view
2254 # currently (optimistically) showing $cur_uri, cannot be the current
2255 # pending's own:
2256 #
2257 # - mechanism 1 (committed-uri gate, primary): the pending has its OWN
2258 # captured committed uri ($p->[5], set on 'committed' -- see the
2259 # load-changed handler) and $cur_uri differs from it. Comparing
2260 # actual-committed to actual-committed (never to a user-passed target)
2261 # makes this immune to WebKit's own uri normalization/redirects. Inert
2262 # (falls through to mechanism 2) when the pending has NOT captured a
2263 # committed uri -- notably a bfcache-restored back()/forward(), which
2264 # jumps straight to 'finished' with no preceding started/committed at
2265 # all; gating on absence-of-commit here would hang a real, successful
2266 # navigation, so this mechanism deliberately does NOT do that.
2267 #
2268 # - mechanism 2 (started-since gate): the pending has no committed uri of its
2269 # own but DOES have a known target -- go(), as opposed to the history navs --
2270 # and has not yet seen its own 'started'. See the body; it is what catches
2271 # the tail of a load abandoned by a timeout. Note that mechanism 1
2272 # deliberately does not gate on absence-of-commit, and this does not
2273 # contradict that: it fires only for a nav that carries a target, which a
2274 # bfcache-restorable history navigation never does.
2275 #
2276 # - mechanism 3 (superseded-uri filter, covers what neither of the above can):
2277 # pending has NOT captured a committed uri, but _start_nav recorded the
2278 # identity of a nav it tore down mid-flight to create this pending (see
2279 # there). Unless $cur_uri happens to coincide with that identity -- an
2280 # irreducible, indistinguishable-but-harmless case (same uri either way;
2281 # see POD LIMITATIONS) -- a finished arriving before this pending's own
2282 # commit can only be that torn-down nav's belated tail, not a legitimate
2283 # bfcache-style finished of this pending's own (nothing was superseded to
2284 # create a genuine bfcache restore in the first place, so {_superseded}
2285 # is empty for one and this whole branch is skipped).
2286 sub _finished_is_stray {
2287 my ($self, $cur_uri) = @_;
2288 my $p = $self->{pending} or return 0;
2289 if (defined $p->[5]) {
2290 return (!defined $cur_uri || $cur_uri ne $p->[5]) ? 1 : 0;
2291 }
2292 # A pending with a KNOWN TARGET -- go(), as opposed to back/forward/reload/
2293 # load_html -- that has not yet seen its own 'started' cannot be the owner of
2294 # a 'finished': WebKit always starts a load before finishing it, the same
2295 # ordering the load-failed handler's started-since gate relies on. The
2296 # bfcache exception noted above, a restore jumping straight to 'finished',
2297 # is a HISTORY navigation, and those never carry a target here.
2298 #
2299 # This is what catches the tail of a load abandoned by a TIMEOUT. A timeout
2300 # consumes the pending but does not stop the load; the next go() cancels it,
2301 # and that cancellation's terminal 'finished' arrives with the view ALREADY
2302 # reporting the retry's uri -- so no uri comparison can separate them, and
2303 # {_superseded} is empty because nothing was pending to supersede. Left
2304 # unguarded it resolved the retry as an instant success on a page that had
2305 # not loaded, which is the ordinary retry-after-timeout pattern.
2306 return 1 if defined $p->[3] && !$p->[4];
2307 my $sup = $self->{_superseded};
2308 return 0 unless $sup && %$sup;
2309 return (defined $cur_uri && $sup->{$cur_uri}) ? 0 : 1;
2310 }
2311  
2312 sub _finish_nav {
2313 my ($self, $err, $gen) = @_;
2314 if (defined $gen) {
2315 # a generation-tagged caller (currently: only the per-nav timeout
2316 # timer, below) may only resolve the pending nav that minted it --
2317 # a timer belonging to an already-superseded/resolved nav must not
2318 # fire against whatever nav happens to be pending now. Compare
2319 # against the LIVE {pending} tuple (not a separately cached "current
2320 # gen" field): unlike such a field, this is automatically undef the
2321 # instant the matching nav resolves, with nothing to go stale.
2322 my $cur_gen = $self->{pending} ? $self->{pending}[2] : undef;
2323 return unless defined $cur_gen && $gen == $cur_gen;
2324 }
2325 # Snapshot BEFORE anything below runs, and hand only the snapshot to the
2326 # resolutions. Two bugs come from getting this wrong, and both were live:
2327 # - a waiter armed by one of the callbacks this navigation is about to
2328 # run (go()'s own callback is the natural place: "I have the page, now
2329 # click submit") belongs to the NEXT navigation, not this one. Draining
2330 # {_nav_waiters} at the end resolved it against the page already loaded.
2331 # - a FAILING api navigation left the waiters in place, and the failed
2332 # load's terminal 'finished' -- which arrives with no pending -- then
2333 # drained them through the no-pending SUCCESS path, reporting a bogus
2334 # success with an empty uri for a navigation that never happened.
2335 my $waiters = delete $self->{_nav_waiters};
2336 # Read the uri NOW, not at delivery: the waiters are resolved after this
2337 # navigation's own callback has run, and that callback starting another
2338 # navigation would otherwise make the waiter report the new one's target
2339 # as "where it landed".
2340 my $landed = $self->uri;
2341 my $p = delete $self->{pending};
2342 unless ($p) {
2343  
2344 # error with no pending nav (e.g. a stray load-failed): route to on_error.
2345 # This fires from the load-failed signal's glib dispatch frame, so defer it.
2346 # _defer_final, not _defer: on_error belongs to no registry (nothing
2347 # flushes it at quit), and the failure has ALREADY happened -- delivering
2348 # it needs nothing from $self. Through _defer it was hostage to the
2349 # instance outliving the tick, so a browser quit or dropped in the gap
2350 # swallowed the only notification a callback-less navigation ever gets.
2351 $self->_defer_final($self->{on_error}, $err) if $err && $self->{on_error};
2352 # A navigation the PAGE started (a link click, a form submit) lands here
2353 # with nobody's callback -- but wait_for_navigation is waiting on it, and
2354 # must be handed a browser whose title() is readable, exactly like go()'s
2355 # own callback is. So settle first, on success.
2356 if (defined $err) { $self->_resolve_nav_waiters($waiters, $landed, $err) }
2357 else { $self->_settle_props(sub { $_[0]->_resolve_nav_waiters($waiters, $landed, undef) }) }
2358 return;
2359 }
2360 $p->[1]->stop if $p->[1];
2361 my $cb = $p->[0];
2362 # {pending} is gone now, but the callback has NOT been delivered yet -- both
2363 # branches below hand it to a timer (a _defer tick, or the settle timer).
2364 # Between here and that tick it belongs to no registry, so a quit() (or a
2365 # bare drop, whose DESTROY runs quit) landing in the gap would silently drop
2366 # it. Track it: quit()'s flush then resolves it with 'browser closed', and
2367 # the wrapper dedupes, so whichever lands first wins and the other is a
2368 # no-op -- exactly once, either way.
2369 $cb = $self->_op_track($cb) if $cb;
2370 if ($err) {
2371 # signal-dispatch frame (load-failed) or quit()/_start_nav-supersede -- defer.
2372 # A nav started without a per-call callback still owes on_error a genuine
2373 # FAILURE (POD: on_error fires for a nav failure with no callback
2374 # waiting) -- otherwise it would vanish silently, since {pending} is
2375 # always populated so the "no pending" on_error branch above never runs
2376 # for an API-initiated nav. But 'superseded' is NOT a failure: it is
2377 # this instance's own intentional navigate-away (a later go()/back()/
2378 # reload() replacing an in-flight one), so a callback-less supersession
2379 # must NOT reach on_error. A caller that DID pass a callback still gets
2380 # 'superseded' delivered to it (the if-branch), unchanged.
2381 if ($cb) { $self->_defer($cb, undef, $err) }
2382 elsif ($self->{on_error} && $err ne 'superseded') { $self->_defer_final($self->{on_error}, $err) } # _defer_final: see above
2383 if ($err eq 'superseded') {
2384 # Nothing actually navigated anywhere: this instance replaced its own
2385 # in-flight nav, and the replacement is the navigation the waiters
2386 # are still waiting for. Put them back rather than resolving them.
2387 my $cur = $self->{_nav_waiters} ||= {};
2388 %$cur = (%{ $waiters || {} }, %$cur);
2389 }
2390 else { $self->_resolve_nav_waiters($waiters, $landed, $err) }
2391 }
2392 else {
2393 # A challenge raised by a SUBRESOURCE or an iframe leaves a note behind
2394 # while the main navigation succeeds; nothing consumed it, so it went on
2395 # to explain an unrelated later failure to the same host.
2396 delete $self->{_auth_challenge};
2397 $self->_settle_props(sub {
2398 my ($self) = @_;
2399 # A throwing per-call callback must not rob on_load of its turn
2400 # (POD promises on_load fires for every successful instance-initiated
2401 # nav). Run the cb guarded, fire on_load, then re-surface the cb's
2402 # own exception so EV's $EV::DIED still logs it.
2403 my $cberr;
2404 if ($cb) { eval { $cb->(1, undef); 1 } or $cberr = $@ }
2405 # on_load guarded too: if it ALSO throws, its exception must not
2406 # replace the per-call callback's on the way out (that one would be
2407 # lost entirely, and it is the one the caller is likelier to be
2408 # debugging). Report on_load's, re-raise the callback's.
2409 if ($self->{on_load}) {
2410 unless (eval { $self->{on_load}->(); 1 }) {
2411 warn "EV::WebKit: on_load callback died: $@";
2412 }
2413 }
2414 $self->_resolve_nav_waiters($waiters, $landed, undef);
2415 die $cberr if defined $cberr;
2416 });
2417 }
2418 }
2419  
2420 # Wait for the web-process props to reach the UI process, so a caller is not
2421 # handed a browser whose title() is still undef. The uri is already set by
2422 # 'started', so the title is the only prop that lags -- and this is a race
2423 # between the two things that can resolve it:
2424 #
2425 # notify::title -- the page HAS a title. Lands ~0.1ms after 'finished'.
2426 # the deadline -- the page has NO <title>, so no notification is ever coming
2427 # and only a timeout can resolve it.
2428 #
2429 # Both arms are kept on $self (id-keyed, like _defer, so a second nav settling
2430 # inside this window cannot GC this one's timer via a single-slot overwrite) so
2431 # quit() can cancel and disconnect them. Extracted from _finish_nav so a
2432 # navigation with NO pending -- one the page started -- settles the same way
2433 # before wait_for_navigation hands it over.
2434 sub _settle_props {
2435 my ($self, $done) = @_;
2436 my $id = ++$_settle_seq;
2437 weaken(my $wself = $self); # weak: same self-stored-timer cycle as the pending timer -- keep a bare drop during the brief settle window collectible
2438 my $settled = 0; # whichever arm arrives first wins
2439 my $finish_settle = sub {
2440 my $self = $wself or return;
2441 return if $settled++;
2442 delete $self->{_settle}{$id};
2443 if (my $h = delete $self->{_settle_sig}{$id}) {
2444 eval { $self->{view}->signal_handler_disconnect($h) } if $self->{view};
2445 }
2446 return if $self->{_dead};
2447 $done->($self);
2448 };
2449 $self->{_settle}{$id} = EV::timer(NAV_SETTLE_DELAY, 0, $finish_settle);
2450 # Re-arm at zero rather than settling here: the notification arrives inside
2451 # GLib's dispatch, and running the caller's callback (and its possible
2452 # EV::break) in that frame is the wedge $IN_DISPATCH exists for.
2453 if ($self->{view}) {
2454 $self->{_settle_sig}{$id} = $self->{view}->signal_connect('notify::title' => sub {
2455 my $self = $wself or return;
2456 return if $settled || !exists $self->{_settle}{$id};
2457 $self->{_settle}{$id} = EV::timer(0, 0, $finish_settle);
2458 });
2459 }
2460 return;
2461 }
2462  
2463 sub _resolve_nav_waiters {
2464 my ($self, $w, $uri, $err) = @_;
2465 return unless $w && %$w;
2466 for my $e (values %$w) {
2467 $e->{timer} = undef;
2468 $self->_defer($e->{cb}, (defined $err ? (undef, $err) : ($uri, undef)));
2469 }
2470 return;
2471 }
2472  
2473 sub _start_nav {
2474 my ($self, $cb, $target) = @_;
2475 # A challenge belongs to the navigation it was raised for; carrying the note
2476 # past this point would let it explain an unrelated later failure.
2477 delete $self->{_auth_challenge};
2478 my $old = $self->{pending};
2479 # replace any in-flight nav with a superseded error -- always acts on
2480 # whatever is CURRENTLY pending (no gen check passed here: this is a
2481 # synchronous, direct resolution of the immediately-preceding nav, not a
2482 # stray external signal, so there is nothing to disambiguate against).
2483 $self->_finish_nav('superseded') if $old;
2484 # R11: {_superseded} only ever matters for disambiguating a stray tail
2485 # signal (load-changed:finished, or load-failed) belonging to whatever
2486 # THIS call just tore down mid-flight -- see _finished_is_stray and the
2487 # load-failed handler in new(). Reset it here, unconditionally, on
2488 # EVERY new nav (not just when one was actually superseded): its
2489 # relevance is scoped to exactly the window between this _start_nav call
2490 # and the next one, so a leftover, never-consumed entry (e.g. because
2491 # WebKit happened to never deliver the tail signal it seemed to owe)
2492 # can never persist to wrongly poison a later, unrelated pending's own
2493 # legitimate no-commit (bfcache-style) finished.
2494 $self->{_superseded} = {};
2495 if ($old && $old->[4]) { # started_seen -- nothing was actually in flight otherwise, so no tail signal is owed
2496 # $old's own identity: its captured committed uri if it reached that
2497 # far, else whatever the view is optimistically showing for it right
2498 # now -- get_uri() here still reflects $old, since the caller (go/
2499 # reload/back/forward, below) hasn't yet issued the new
2500 # load/reload/go_back/go_forward call that would move it on.
2501 my $old_uri = defined $old->[5] ? $old->[5] : $self->{view}->get_uri;
2502 $self->{_superseded}{$old_uri} = 1 if defined $old_uri && length $old_uri;
2503 }
2504 my $gen = ++$_nav_seq;
2505 # WEAK: this timer lives inside $self->{pending}, so a strong $self here
2506 # would form a $self -> {pending} -> timer -> closure -> $self cycle that
2507 # a bare drop (no quit()) can't break until the nav resolves -- deferring
2508 # the instance's collection for up to {timeout}s (30s by default) while a
2509 # nav is in flight. Same class as the handler closures weakened for
2510 # collectability; quit() still stops this timer explicitly.
2511 weaken(my $wself = $self);
2512 my $timer = EV::timer($self->{timeout}, 0, sub { my $self = $wself or return; $self->_finish_nav('timeout', $gen) });
2513 $self->{pending} = [$cb, $timer, $gen, $target, 0, undef, 0]; # started_seen false, committed_uri undef, doc_scheme_seen false -- see load-changed/load-failed/mock_scheme
2514 # informational only (last-issued generation) -- unlike {pending}, this
2515 # is NOT cleared when the nav resolves, so it must never be used to test
2516 # "is a nav in flight" or as a gating comparison; _finish_nav's gen
2517 # check (above) reads the live {pending} tuple instead, precisely to
2518 # avoid that staleness.
2519 $self->{nav_gen} = $gen;
2520 return $gen;
2521 }
2522  
2523 sub go {
2524 my ($self, $uri, $cb) = @_;
2525 Carp::croak('go: callback must be a code reference') if defined $cb && ref $cb ne 'CODE';
2526 if ($self->{_dead} || !$self->{view}) { $self->_defer_final($cb, undef, 'browser closed') if $cb; return $self }
2527 unless (defined $uri && length $uri) { # a bare load_uri(undef) dies in the GI layer AND leaves {pending} dangling -- degrade cleanly instead
2528 $self->_defer_final($cb, undef, 'go: uri required') if $cb;
2529 return $self;
2530 }
2531 $self->{_seen_uris}{$uri} = 1; # feeds save_cookies' default URI list
2532 my $gen = $self->_start_nav($cb, $uri);
2533 $self->{view}->load_uri($uri);
2534 # WebKit may normalize the requested uri (add a trailing slash,
2535 # lower-case the host, strip a default port, ...) -- get_uri() reflects
2536 # that normalized form synchronously, immediately after load_uri()
2537 # returns, so resync the tracked target to it for an apples-to-apples
2538 # compare against a later load-failed's failing_uri (which WebKit
2539 # reports already normalized) -- see the load-failed handler in new().
2540 # Gen-guarded: load_uri() can reenter (e.g. a mock_scheme producer
2541 # calling go() again) and supersede this very pending before this line
2542 # runs -- only touch {pending} if it is still the nav we just started.
2543 if ($self->{pending} && $self->{pending}[2] == $gen) {
2544 $self->{pending}[3] = $self->{view}->get_uri;
2545 }
2546 return $self;
2547 }
2548  
2549 sub load_html {
2550 my ($self, $html, $cb) = @_;
2551 # Callback FIRST, like go(): a non-coderef here has to croak at the call
2552 # site, and checking the html first would hand it to _defer_final instead,
2553 # where the dereference dies inside a timer and only reaches $EV::DIED.
2554 Carp::croak('load_html: callback must be a code reference')
2555 if defined $cb && ref $cb ne 'CODE';
2556 # And guarded exactly as go() guards its uri: a bare load_html(undef) dies
2557 # inside the GI layer, and doing that AFTER _start_nav left {pending} armed
2558 # -- so the caller got a synchronous die AND, one timeout later, a phantom
2559 # 'timeout' for a navigation that never began.
2560 if (!defined $html) {
2561 $self->_defer_final($cb, undef, 'load_html: html required') if $cb;
2562 return $self;
2563 }
2564 if ($self->{_dead} || !$self->{view}) { $self->_defer_final($cb, undef, 'browser closed') if $cb; return $self }
2565 $self->_start_nav($cb); # no predictable target uri -- the load-failed uri-gate stays inert (undef) for this nav
2566 $self->{view}->load_html($html, undef);
2567 return $self;
2568 }
2569  
2570 sub _history_nav {
2571 my ($self, $can_method, $go_method, $errmsg, $cb) = @_;
2572 Carp::croak('callback must be a code reference') if defined $cb && ref $cb ne 'CODE';
2573 if ($self->{_dead} || !$self->{view}) { $self->_defer_final($cb, undef, 'browser closed') if $cb; return $self }
2574 unless ($self->{view}->$can_method) {
2575 # normal runtime condition (empty history side) -- deliver async, on a clean tick
2576 $self->_defer_final($cb, undef, $errmsg) if $cb;
2577 return $self;
2578 }
2579 $self->_start_nav($cb); # target uri not predictable ahead of the actual history entry -- uri-gate stays inert; cb may be undef, resolves on load finish like go()
2580 $self->{view}->$go_method;
2581 return $self;
2582 }
2583  
2584 sub back { my ($s,$cb)=@_; $s->_history_nav('can_go_back', 'go_back', 'cannot go back', $cb) }
2585 sub forward { my ($s,$cb)=@_; $s->_history_nav('can_go_forward', 'go_forward', 'cannot go forward', $cb) }
2586  
2587 sub reload {
2588 my ($self, $cb) = @_;
2589 Carp::croak('reload: callback must be a code reference') if defined $cb && ref $cb ne 'CODE';
2590 if ($self->{_dead} || !$self->{view}) { $self->_defer_final($cb, undef, 'browser closed') if $cb; return $self }
2591 unless (defined $self->{view}->get_uri && length $self->{view}->get_uri) {
2592 # nothing has ever been loaded -- WebKit emits no load-changed for a
2593 # reload() here, so the pending would resolve only via the full
2594 # timeout with a misleading 'timeout'. This is locally knowable, so
2595 # deliver a clean error at once, mirroring back()/forward().
2596 $self->_defer_final($cb, undef, 'nothing to reload') if $cb;
2597 return $self;
2598 }
2599 $self->_start_nav($cb); # no target passed -- a mid-reload redirect could otherwise defeat a same-uri gate; uri-gate stays inert
2600 $self->{view}->reload;
2601 return $self;
2602 }
2603  
2604 sub stop {
2605 my ($self) = @_;
2606 return $self if $self->{_dead} || !$self->{view};
2607 $self->{view}->stop_loading;
2608 return $self;
2609 }
2610  
2611 sub can_go_back { my $s=$_[0]; ($s->{_dead} || !$s->{view}) ? 0 : ($s->{view}->can_go_back ? 1 : 0) }
2612 sub can_go_forward { my $s=$_[0]; ($s->{_dead} || !$s->{view}) ? 0 : ($s->{view}->can_go_forward ? 1 : 0) }
2613  
2614 sub uri { my $s=$_[0]; ($s->{_dead} || !$s->{view}) ? undef : $s->{view}->get_uri }
2615 sub title { my $s=$_[0]; ($s->{_dead} || !$s->{view}) ? undef : $s->{view}->get_title }
2616 sub is_loading { my $s=$_[0]; ($s->{_dead} || !$s->{view}) ? 0 : ($s->{view}->is_loading ? 1 : 0) }
2617  
2618 # HTTP status of the current document, or undef when the load had none.
2619 #
2620 # Worth having because a navigation's own ok/err cannot tell you this: WebKit
2621 # reports a 404 or a 500 as a perfectly successful load (they have bodies, and
2622 # it displays them), so ok is 1 and err undef for both. Verified live.
2623 #
2624 # Deliberately a synchronous accessor rather than another callback argument:
2625 # the value is available from load-changed:committed onward and stays correct,
2626 # so reading it inside a nav callback works -- and this way the navigation state
2627 # machine, which took eleven review rounds to settle, is not touched at all.
2628 #
2629 # Redirects resolve to the FINAL response (a 302 chain reports the 200), which
2630 # is what a caller means by "the status of this page".
2631 sub status {
2632 my $s = shift;
2633 return undef if $s->{_dead} || !$s->{view};
2634 # Each step is eval-guarded and may legitimately be absent: no main resource
2635 # before the first commit, and no response at all when nothing was received
2636 # over HTTP (see the POD -- a refused connection lands here).
2637 my $res = eval { $s->{view}->get_main_resource } or return undef;
2638 my $resp = eval { $res->get_response } or return undef;
2639 my $code = eval { $resp->get_status_code };
2640 # 0 is what a non-HTTP load (load_html, and some custom schemes) reports; it
2641 # is not a status, so say so with undef rather than passing 0 to a caller who
2642 # will reasonably compare it numerically.
2643 return (defined $code && $code > 0) ? $code : undef;
2644 }
2645  
2646 sub html { my ($s, $cb) = @_; Carp::croak('html: callback must be a code reference') if defined $cb && ref $cb ne 'CODE'; $s->_call_js('return document.documentElement ? document.documentElement.outerHTML : null;', {}, $cb); return $s }
2647  
2648 sub set_user_agent {
2649 my ($s, $ua) = @_;
2650 return $s if $s->{_dead} || !$s->{view};
2651 Carp::croak('set_user_agent: expected a string') if ref $ua;
2652 # WebKit's setter (isValidUserAgentHeaderValue) silently rejects a header
2653 # value it dislikes -- control chars, any byte >= 0x80, leading/trailing
2654 # whitespace, an embedded quote or backslash, ... -- by printing a C-level
2655 # CRITICAL, KEEPING THE OLD VALUE, and raising no Perl exception. The exact
2656 # accepted set varies by build and is broader than any charset guess we
2657 # tried, so don't guess: apply it, then read it back and croak if it did
2658 # not stick. (A bad UA still logs one WebKit CRITICAL before we croak --
2659 # unavoidable, since only set() knows the real rule.)
2660 my $settings = $s->{view}->get_settings;
2661 $settings->set('user-agent', $ua);
2662 if (defined $ua) {
2663 my $got = $settings->get('user-agent');
2664 Carp::croak('set_user_agent: WebKit rejected this user agent (unsupported characters -- e.g. a control char, a byte >= 0x80, leading/trailing whitespace, or an embedded quote/backslash)')
2665 unless defined $got && $got eq $ua;
2666 }
2667 $s;
2668 }
2669 sub user_agent { my $s=$_[0]; ($s->{_dead} || !$s->{view}) ? undef : $s->{view}->get_settings->get('user-agent') }
2670  
2671 # The resolved device profile for this instance (read-only), or undef. See the
2672 # fingerprint => constructor option.
2673 sub fingerprint { $_[0]->{fingerprint} }
2674 sub network_fingerprint { $_[0]->{network_fingerprint} } # active curl target, or undef
2675 sub proxy_port { my $s = shift; $s->{proxy} ? $s->{proxy}->port : undef }
2676 sub fingerprint_profiles { shift; require EV::WebKit::Fingerprint; EV::WebKit::Fingerprint::profiles() }
2677 sub fingerprint_available { require EV::WebKit::Fingerprint; EV::WebKit::Fingerprint::available() }
2678  
2679 sub settings {
2680 my ($self, $kv) = @_;
2681 return $self if $self->{_dead} || !$self->{view};
2682 Carp::croak('settings: argument must be a hash reference') unless ref $kv eq 'HASH';
2683 my $s = $self->{view}->get_settings;
2684 # Validate all values BEFORE applying any: a reference value is never valid
2685 # for a WebKitSettings property (all are bool/int/string/enum scalars), and
2686 # GI's set() does not reject it -- it numifies the ref's ADDRESS into e.g.
2687 # an integer property, silently storing ASLR garbage that looks like
2688 # success. Checking up front also makes the common typed-value mistake
2689 # atomic (no partial application). NOTE: an invalid property NAME can still
2690 # only be detected by set() itself, mid-apply, so a croak from that path is
2691 # not transactional -- keys applied before it stay applied (see POD).
2692 for my $k (keys %$kv) {
2693 Carp::croak("settings: value for '$k' must be a scalar, not a " . ref($kv->{$k}) . ' reference')
2694 if ref $kv->{$k};
2695 }
2696 for my $k (keys %$kv) {
2697 (my $prop = $k) =~ tr/_/-/;
2698 # user-agent is just another WebKitSettings property, so it is reachable
2699 # through here -- but WebKit SILENTLY rejects a header value it dislikes
2700 # (keeps the old one, no exception, only a C-level CRITICAL). Without
2701 # this, settings({user_agent => $bad}) reported success while the value
2702 # never applied, quietly bypassing the very check set_user_agent exists
2703 # for. Route it through the validated path.
2704 if ($prop eq 'user-agent') { $self->set_user_agent($kv->{$k}); next }
2705 eval { $s->set($prop, $kv->{$k}); 1 } or Carp::croak("settings: cannot set '$k': " . _clean($@));
2706 }
2707 return $self;
2708 }
2709  
2710 sub set_proxy {
2711 my ($self, $proxy) = @_;
2712 return $self if $self->{_dead} || !$self->{session};
2713 my $s = $self->{session};
2714 # only undef and the literal string 'no-proxy' mean "clear the proxy" --
2715 # notably NOT '' (empty string), which is far more likely a caller
2716 # mistake than an intentional clear, and must not be swallowed silently
2717 # (see the URI validation below).
2718 if (!defined($proxy) || (!ref $proxy && $proxy eq 'no-proxy')) {
2719 $s->set_proxy_settings('no-proxy', undef);
2720 return $self;
2721 }
2722 my ($default, $ignore) = ref $proxy eq 'HASH'
2723 ? ($proxy->{default}, $proxy->{ignore} // [])
2724 : ($proxy, []);
2725 if (ref $proxy eq 'HASH') {
2726 Carp::croak('set_proxy: proxy hash requires a non-empty "default" URI')
2727 unless defined($default) && length($default);
2728 # A typo'd key (ignoer =>) must not be silently dropped -- the hosts the
2729 # caller meant to exempt would then be routed through the proxy.
2730 if (my @bad = sort grep { $_ ne 'default' && $_ ne 'ignore' } keys %$proxy) {
2731 Carp::croak("set_proxy: unknown proxy-hash key(s): @bad (expected 'default'/'ignore')");
2732 }
2733 }
2734 # A malformed default proxy URI is a privacy footgun: WebKit's own
2735 # webkit_network_proxy_settings_new/set_proxy_settings just print a
2736 # C-level CRITICAL and leave the proxy unset (routing direct) -- that is
2737 # NOT a Perl exception, so eval around set_proxy can never catch it.
2738 # Validate the shape (scheme://authority) proactively instead of trusting
2739 # WebKit to reject it.
2740 unless (defined($default) && !ref($default) && $default =~ m{^[a-z][a-z0-9+.-]*://[^/\s]+}i) {
2741 my $shown = !defined($default) ? '(undef)' : (ref($default) ? ref($default) : $default);
2742 Carp::croak("set_proxy: invalid proxy URI '$shown'");
2743 }
2744 # ignore_hosts is a GStrv: an undef entry marshals to a NULL that truncates
2745 # the list WebKit receives, silently routing the hosts AFTER it through the
2746 # proxy (a privacy leak -- the proxy analogue of a truncated deny-list). A
2747 # non-arrayref is a type error. Validate it. (An empty list is fine here: it
2748 # legitimately means "proxy every host".)
2749 Carp::croak('set_proxy: "ignore" must be an arrayref of host-pattern strings')
2750 unless ref $ignore eq 'ARRAY';
2751 defined && !ref && length or Carp::croak('set_proxy: "ignore" entries must be non-empty strings')
2752 for @$ignore;
2753 my $settings = WebKit::NetworkProxySettings->new($default, $ignore);
2754 $s->set_proxy_settings('custom', $settings);
2755 return $self;
2756 }
2757  
2758 # register a custom URI-scheme handler on this instance's WebContext, e.g.
2759 # $b->mock_scheme('mock', sub { my ($uri)=@_; return ($body, $content_type) }).
2760 # Must be called before the first navigation to that scheme.
2761 sub mock_scheme {
2762 my ($self, $scheme, $producer) = @_;
2763 Carp::croak('mock_scheme: a scheme name is required')
2764 if !defined $scheme || ref $scheme || !length $scheme;
2765 Carp::croak('mock_scheme: the producer must be a code reference')
2766 unless ref $producer eq 'CODE';
2767 return $self if $self->{_dead} || !$self->{context};
2768 # WEAK: this persistent scheme-handler closure is held by $self->{context},
2769 # so capturing $self strongly would form a $self -> {context} -> handler ->
2770 # $self cycle that a bare drop (no quit()) can never break -- the same
2771 # leak class as the signal handlers in new(). It only needs $self on the
2772 # error path (to resolve the pending nav); the request itself is finished
2773 # regardless.
2774 weaken(my $wself = $self);
2775 $self->{context}->register_uri_scheme($scheme, sub {
2776 # WebKitURISchemeRequestCallback is (request, user_data) -- request is
2777 # $_[0], NOT $_[1] (verified live against WebKitGTK 2.52.4; passing an
2778 # undef user_data through unchanged, it is not hidden by the binding).
2779 my ($req, undef) = @_;
2780 local $IN_DISPATCH = 1; # the producer runs nested in WebKit's dispatch frame -- see quit
2781 my $self = $wself; # may be gone if the browser was dropped mid-request; we still finish the request below
2782 my $uri = $req->get_uri;
2783  
2784 # Claim the navigation's document slot HERE, before the producer runs, so
2785 # success and failure agree on which request was the document. The first
2786 # request of this navigation whose uri matches the view's is the main
2787 # document (subresources are only discovered after it is parsed); a later
2788 # request for the same uri -- a self-referencing <img>/fetch -- is a
2789 # subresource, and its outcome is the page's business, not the nav's. See
2790 # the error branch below, which only fails the nav when this request WAS
2791 # the document.
2792 my $is_doc;
2793 if (my $p = $self && $self->{pending}) {
2794 my $doc = $self->{view} ? $self->{view}->get_uri : undef;
2795 $is_doc = (defined $doc && $uri eq $doc && !$p->[6]) ? do { $p->[6] = 1; 1 } : 0;
2796 }
2797  
2798 my ($resp_body, $ctype) = eval { $producer->($uri) };
2799 if (my $e = $@) {
2800 # This callback is invoked directly by WebKit's C code via a GI
2801 # callback-argument (webkit_uri_scheme_request's callback, not a
2802 # glib signal) -- nothing upstream wraps it in an eval, so an
2803 # uncaught die here previously unwound straight through WebKit's
2804 # C stack and out past EV::run, killing the WHOLE PROCESS
2805 # (confirmed live: uncaught die -> Perl top-level -> exit 255).
2806 # Must never let that reach the caller.
2807 #
2808 # finish_error() looks like the obvious clean way to tell WebKit
2809 # "this request failed" (which would fail the load like a real
2810 # network error, via the load-failed signal), but it is NOT
2811 # usable with the installed binding: WebKitURISchemeRequest's
2812 # finish_error() takes its GError argument transfer-ownership=
2813 # "none" per the WebKit-6.0 .gir, and the installed
2814 # Glib::Object::Introspection 0.052's boxed-argument marshaling
2815 # (gperl-i11n-marshal-arg.c:sv_to_arg) unconditionally asserts
2816 # transfer==GI_TRANSFER_EVERYTHING for a boxed "in" argument.
2817 # Calling finish_error with any Glib::Error -- even wrapped in
2818 # eval -- aborts the whole process (SIGABRT; confirmed live:
2819 # "Bail out! ERROR:gperl-i11n-marshal-arg.c:118:sv_to_arg:
2820 # assertion failed") *before* eval can catch anything, because
2821 # it is a C-level abort(), not a Perl exception. So finish_error
2822 # must not be called here at all.
2823 #
2824 # Instead: resolve the pending navigation with a synthetic error,
2825 # exactly like the 'timeout'/'superseded' synthetic errors
2826 # _start_nav already funnels through _finish_nav from non-signal
2827 # contexts. Then finish the request itself with an inert
2828 # placeholder body so WebKit's own request bookkeeping is
2829 # satisfied (a request must be finished exactly once) -- its
2830 # content is never meant to be seen; the real signal already went
2831 # to the nav callback above.
2832 #
2833 # ONLY if this request IS the navigation's own document. The scheme
2834 # handler serves every request for the scheme, not just navigations:
2835 # an <img>/<script>/<iframe> subresource comes through here too.
2836 # Firing unconditionally meant a producer that threw on a subresource
2837 # failed the top-level navigation whose page had in fact loaded
2838 # perfectly -- and if the nav had already resolved, the throw was
2839 # routed to on_error instead, whose contract is a navigation failure
2840 # with no callback waiting, not an arbitrary later resource fetch.
2841 #
2842 # The test is the VIEW'S CURRENT URI, not {pending}[3]: that target
2843 # is undef by design for reload/back/forward (the uri is not
2844 # predictable ahead of the history entry), so gating on it ignored a
2845 # producer that threw on THEIR OWN document -- reload() then reported
2846 # a false SUCCESS while the page showed the error placeholder.
2847 # WebKit sets the view's uri to the new document when the provisional
2848 # load starts, BEFORE fetching it, so right now it equals the
2849 # main-document request's uri and differs from every subresource's.
2850 # Verified for go/reload/back/forward (including A->B, where the view
2851 # already reads as B) and for load_html, whose subresources never
2852 # match -- its document does not come through a uri scheme at all.
2853 # ...and only if this request WAS the navigation's document (claimed
2854 # at the top of this handler, the same way for success and failure).
2855 # A self-referencing subresource that throws must not fail a
2856 # navigation whose document already loaded.
2857 $self->_finish_nav('scheme handler error: ' . _clean($e)) if $self && $is_doc;
2858 my $msg = 'scheme handler error';
2859 my $bytes = Glib::Bytes->new($msg);
2860 $req->finish(Glib::IO::MemoryInputStream->new_from_bytes($bytes), length($msg), 'text/plain');
2861 return;
2862 }
2863 $resp_body //= ''; $ctype //= 'text/html';
2864 # Glib::Bytes wants raw octets, not a Perl character string -- unlike
2865 # the JSON-bridge params above, this is not a GI `utf8`-typed
2866 # argument that expects/upgrades characters, so the producer's body
2867 # (documented as character data) must be byte-encoded here.
2868 # Unconditional, and on a COPY: a Latin-1-range scalar with the utf8
2869 # flag OFF (e.g. a bare "\x{e9}" literal, which Perl never flags) is
2870 # still, semantically, character data -- utf8::encode() correctly
2871 # turns either flag state into the right UTF-8 octets. Gating on
2872 # is_utf8() (as before) skipped that flag-off case and served its
2873 # raw Latin-1 byte instead of the 2-byte UTF-8 sequence, corrupting
2874 # any non-ASCII body that happened to stay unflagged. Encoding a
2875 # copy (not $resp_body itself) means the producer's own return value
2876 # is never mutated, however it is held.
2877 my $octets = $resp_body;
2878 utf8::encode($octets);
2879 my $bytes = Glib::Bytes->new($octets);
2880 my $stream = Glib::IO::MemoryInputStream->new_from_bytes($bytes);
2881 $req->finish($stream, $bytes->get_size, $ctype);
2882 });
2883 return $self;
2884 }
2885  
2886 sub show_devtools {
2887 my $self = shift;
2888 return $self if $self->{_dead} || !$self->{view};
2889 $self->{view}->get_settings->set('enable-developer-extras', 1);
2890 $self->{view}->get_inspector->show; # WebKitWebInspector
2891 return $self;
2892 }
2893  
2894 my $_waiter_seq = 0;
2895  
2896 # The polling engine behind wait_for and wait_for_js.
2897 #
2898 # Extracted rather than copied: everything delicate about wait_for lives in the
2899 # closure family below -- the ONE shared weak alias, the waiter registry that
2900 # lets quit() resolve a poll whose round trip is in flight, and the single
2901 # resolution point that dedupes and breaks the timer self-cycle. A second copy
2902 # of that would be a second place for any future fix to be forgotten, which is
2903 # exactly the sibling-site problem this codebase has been bitten by before.
2904 #
2905 # %a: probe -- sub { my ($done) = @_; ... $done->($ok, $payload, $err) }
2906 # called once per tick; $ok true resolves with $payload.
2907 # timeout, interval, cb.
2908 sub _poll_until {
2909 my ($self, %a) = @_;
2910 my $cb = $a{cb};
2911 my $probe = $a{probe};
2912 my $deadline = $a{timeout};
2913 my $interval = $a{interval};
2914 # REAL time, not a count of polls. Counting one interval per completed probe
2915 # ignored the probe's own round trip -- and each is a full JS round trip, so
2916 # the overshoot was unbounded: a 2s wait took ~40s on a page where find()
2917 # took a second.
2918 my $started = EV::now;
2919 my $w; # current poll timer
2920 my $deadline_timer; # independent hard deadline -- see below
2921 my $tick;
2922 my $wid; # registry id -- declared before $finish so its closure can capture it
2923 my $done = 0; # idempotency guard: quit() and the normal tick path can each try to resolve
2924 # $finish, like $tick just below, is transitively captured into the probe's
2925 # own completion closure -- $tick hands $finish to $probe, and the probe
2926 # (wait_for's find(), wait_for_js's script()) passes that on to _call_js,
2927 # whose GAsyncReadyCallback closure Glib::Object::Introspection retains
2928 # PERMANENTLY even after it fires. So $finish's own capture of $self (needed
2929 # below to self-deregister from the waiter registry) must be weakened too,
2930 # exactly like $tick's -- one shared weak alias for the whole closure
2931 # family, established before either closure is built.
2932 weaken(my $wself = $self);
2933 my $finish = sub { # single resolution point: break the $tick self-cycle + release the timer
2934 my ($el, $err) = @_;
2935 return if $done++; # already resolved (e.g. quit() got there first) -- no-op
2936 delete $wself->{_waiters}{$wid} if $wself;
2937 undef $w;
2938 undef $deadline_timer;
2939 undef $tick;
2940 $cb->($el, $err);
2941 };
2942 # register so quit() can resolve this deterministically even if it lands
2943 # while a poll's find() is in flight (see quit(), below): _call_js's
2944 # completion is dead-gated via _defer, so a find() in flight at quit()
2945 # time would otherwise never reach $finish on its own. This is the ONE
2946 # place that needs $self (not $wself) strongly: at registration time the
2947 # caller is guaranteed to be holding a live reference (it just called a
2948 # method on it), and the registry entry is exactly what self-deregisters
2949 # (via $finish, above) on every resolution path -- so it is never the
2950 # sole thing keeping $self alive.
2951 $wid = ++$_waiter_seq;
2952 $self->{_waiters}{$wid} = $finish;
2953 # The check above only runs when a probe COMPLETES, so a probe slower than
2954 # the whole wait still overruns it. This answers at the time asked for
2955 # whatever the probe is doing; $finish dedupes, so racing it is safe. Not
2956 # armed for a non-positive deadline, which keeps "always probe once".
2957 $deadline_timer = EV::timer($deadline, 0, sub { $finish->(undef, 'timeout') })
2958 if $deadline && $deadline > 0;
2959 $tick = sub {
2960 my $self = $wself or return;
2961 # belt-and-braces: quit()'s waiter registry (above) is what makes
2962 # resolution deterministic now, so this may fire before OR after
2963 # that resolution already ran -- $finish's own dedupe makes either
2964 # order safe.
2965 return $finish->(undef, 'browser closed') if $self->{_dead};
2966 $probe->(sub {
2967 # Already resolved (by the deadline timer, or quit)? Then do not
2968 # fall through to the re-poll branch, which would arm a timer calling
2969 # the $tick $finish has just undef'd. The elapsed check below catches
2970 # this on its own except when timer and completion land in one loop
2971 # sweep, sharing a cached EV::now that rounds a ULP short.
2972 return if $done;
2973 my ($ok, $payload, $err) = @_;
2974 return $finish->(undef, $err) if defined $err;
2975 return $finish->($payload, undef) if $ok;
2976 if (EV::now - $started >= $deadline) { return $finish->(undef, 'timeout') }
2977 $w = EV::timer($interval, 0, sub { $tick->() });
2978 });
2979 };
2980 $tick->();
2981 return $self;
2982 }
2983  
2984 sub wait_for {
2985 my ($self, $sel, %o) = (shift, shift);
2986 my $cb = pop;
2987 Carp::croak('wait_for: last argument must be a callback') unless ref $cb eq 'CODE';
2988 Carp::croak('wait_for: options must be name => value pairs') if @_ % 2;
2989 %o = @_;
2990 # find() and find_all() reject unknown keys; this is find() on a poll, so it
2991 # must too. Without the guard a typo'd `visble`/`gnoe` was silently dropped
2992 # and the option simply stayed unset -- which INVERTS the wait rather than
2993 # weakening it: `wait_for('#spinner', gnoe => 1)` resolved instantly WITH
2994 # the spinner, where `gone => 1` correctly waits for it to disappear.
2995 if (my @bad = sort grep { !/^(?:gone|visible|interval|timeout|frame)$/ } keys %o) {
2996 Carp::croak("wait_for: unknown option(s): @bad (expected gone/visible/interval/timeout/frame)");
2997 }
2998 Carp::croak('wait_for: gone and visible are mutually exclusive (gone waits for the selector to match NOTHING)')
2999 if $o{gone} && $o{visible};
3000 # Up front, NOT left to the find() inside the probe. _poll_until registers
3001 # the waiter and arms the deadline before the first tick, so a croak from in
3002 # there escaped to the caller AND left the timer running: wait_for(undef)
3003 # croaked synchronously and then delivered a stray 'timeout' a second later.
3004 # Over the control socket that is two frames for one request id, against an
3005 # answer closure documented as exactly one response per request.
3006 _need_selector(wait_for => $sel);
3007 if ($self->{_dead} || !$self->{view}) { $self->_defer_final($cb, undef, 'browser closed'); return $self }
3008 my $interval = $o{interval} // 0.05;
3009 $interval = 0.05 unless defined $interval && $interval > 0; # non-positive interval is meaningless for a poll -- snap to the default (else $elapsed never advances and the zero-delay re-poll busy-loops, starving the whole EV loop)
3010 my $visible = $o{visible};
3011 my $gone = $o{gone};
3012 my $frame = $o{frame}; # same-origin iframe chain -- see find
3013 _frames_arg(wait_for => $frame); # validate here, not once per poll
3014 my $id_form = ref $frame eq 'HASH' && defined $frame->{id}; # defined, not exists: { url => ..., id => undef } is a valid url form, and _resolve_frame routes it as one
3015 weaken(my $wself = $self);
3016 return $self->_poll_until(
3017 timeout => $o{timeout} // $self->{timeout},
3018 interval => $interval,
3019 cb => $cb,
3020 probe => sub {
3021 my ($done) = @_;
3022 my $self = $wself or return;
3023 $self->find($sel, ($frame ? (frame => $frame) : ()), sub {
3024 my ($el, $err) = @_;
3025 # A frame that is not there is "not settled yet", not a
3026 # failure -- the same principle as the 'stale element' case in
3027 # the visible branch below, and its unfixed twin until now.
3028 # A page that injects its payment iframe a moment after load is
3029 # the documented reason wait_for takes a frame at all, and
3030 # failing at 0.0s with 'no frame matched url' defeats exactly
3031 # that. For gone => 1, the frame going away IS the condition
3032 # the caller was waiting for: an overlay usually disappears by
3033 # having its whole iframe removed.
3034 if (defined $err
3035 && $err =~ /no frame matched|frame not found|frame is gone/) {
3036 return $done->(1, 1, undef) if $gone;
3037 # ...except for an { id => } frame, which cannot come back:
3038 # the extension calls frames_forget() on the very reply that
3039 # says the frame is gone, so that id is dead for good and
3040 # polling it can only ever reach the timeout. A url or a
3041 # selector CAN match a frame that appears later, which is
3042 # the whole point of waiting; an id cannot.
3043 return $done->(0, undef, $err) if $id_form;
3044 return $done->(0, undef, undef);
3045 }
3046 return $done->(0, undef, $err) if $err;
3047 # gone: success is the selector matching NOTHING, and there is
3048 # no element to hand back -- resolve with a plain true instead,
3049 # so a caller cannot mistake it for one.
3050 return $done->($el ? 0 : 1, 1, undef) if $gone;
3051 if ($el && $visible) {
3052 return $el->is_visible(sub {
3053 my ($vis, $verr) = @_;
3054 # 'stale element' here is NOT a failure -- it means the
3055 # node find() matched was replaced between that round
3056 # trip and this one (a spinner swapped for content, a
3057 # framework re-rendering). That is precisely the "not
3058 # settled yet" state wait_for exists to poll through, so
3059 # keep polling instead of finishing on it: a live page
3060 # that churns the selector's node used to make
3061 # wait_for(visible => 1) fail early with an error its own
3062 # POD never mentions (only 'timeout'), rather than
3063 # waiting for the element to hold still. Any OTHER error
3064 # is real and terminal.
3065 return $done->(0, undef, undef) if defined $verr && $verr =~ /stale element/;
3066 return $done->(0, undef, $verr) if $verr;
3067 $done->($vis ? 1 : 0, $el, undef);
3068 });
3069 }
3070 $done->($el ? 1 : 0, $el, undef);
3071 });
3072 },
3073 );
3074 }
3075  
3076 # Wait for the NEXT navigation to finish, whoever starts it.
3077 #
3078 # go()'s own callback covers navigations this API starts. Everything else --
3079 # a link click, a form submit, a script-driven redirect -- has no completion
3080 # signal at all: on_load deliberately does not fire for them, on_navigate fires
3081 # at commit rather than finish, and is_loading can read 0 for the whole of a
3082 # fast load. So "click submit, then scrape the next page" had no correct
3083 # spelling; arming a wait_for() before the click is worse than nothing, because
3084 # a selector that exists on both pages resolves against the one you are leaving.
3085 #
3086 # Arm it BEFORE the click: a navigation that finishes first would otherwise be
3087 # missed, since this waits for the next one, not the last one.
3088 my $_navwait_seq = 0;
3089 sub wait_for_navigation {
3090 my $self = shift;
3091 my $cb = pop;
3092 Carp::croak('wait_for_navigation: last argument must be a callback') unless ref $cb eq 'CODE';
3093 Carp::croak('wait_for_navigation: options must be name => value pairs') if @_ % 2;
3094 my %o = @_;
3095 if (my @bad = sort grep { $_ ne 'timeout' } keys %o) {
3096 Carp::croak("wait_for_navigation: unknown option(s): @bad");
3097 }
3098 # An EXPLICIT non-positive timeout is a caller mistake -- there is nothing a
3099 # zero deadline could mean here -- and croaks. An instance-wide timeout => 0
3100 # is inherited as-is, which across this module means "time out at once";
3101 # honouring it as "unbounded" here alone would make this the one method that
3102 # disagrees with every other.
3103 if (exists $o{timeout}) {
3104 Carp::croak('wait_for_navigation: timeout must be a positive number')
3105 unless Scalar::Util::looks_like_number($o{timeout}) && $o{timeout} > 0;
3106 }
3107 my $timeout = $o{timeout} // $self->{timeout};
3108 $timeout = 0 unless Scalar::Util::looks_like_number($timeout) && $timeout >= 0;
3109 if ($self->{_dead} || !$self->{view}) { $self->_defer_final($cb, undef, 'browser closed'); return $self }
3110 my $id = ++$_navwait_seq;
3111 $cb = $self->_op_track($cb); # so quit() mid-wait resolves it instead of dropping it
3112 weaken(my $wself = $self);
3113 my $entry = { cb => $cb };
3114 $entry->{timer} = EV::timer($timeout, 0, sub {
3115 my $s = $wself or return;
3116 my $e = delete $s->{_nav_waiters}{$id} or return;
3117 $s->_defer($e->{cb}, undef, 'timeout');
3118 });
3119 ($self->{_nav_waiters} ||= {})->{$id} = $entry;
3120 return $self;
3121 }
3122  
3123 sub wait_for_js {
3124 my ($self, $expr, %o) = (shift, shift);
3125 my $cb = pop;
3126 Carp::croak('wait_for_js: last argument must be a callback') unless ref $cb eq 'CODE';
3127 Carp::croak('wait_for_js: an expression is required') if !defined $expr || ref $expr;
3128 Carp::croak('wait_for_js: options must be name => value pairs') if @_ % 2;
3129 %o = @_;
3130 if (my @bad = sort grep { !/^(?:interval|timeout)$/ } keys %o) {
3131 Carp::croak("wait_for_js: unknown option(s): @bad (expected interval/timeout)");
3132 }
3133 if ($self->{_dead} || !$self->{view}) { $self->_defer_final($cb, undef, 'browser closed'); return $self }
3134 my $interval = $o{interval} // 0.05;
3135 $interval = 0.05 unless defined $interval && $interval > 0; # see wait_for
3136 my $last_err; # the most recent JS error, for the timeout message
3137 weaken(my $wself = $self);
3138 my $poll_cb = sub {
3139 my ($val, $err) = @_;
3140 # Rewrite a bare 'timeout' into something that names the expression AND
3141 # the last JS error, if any. A predicate that never becomes true and one
3142 # that throws every time both time out, and telling them apart from the
3143 # message is the difference between a two-minute fix and an afternoon.
3144 if (defined $err && $err eq 'timeout') {
3145 $err = "timeout waiting for: $expr" . (defined $last_err ? " (last JS error: $last_err)" : '');
3146 }
3147 $cb->($val, $err);
3148 };
3149 return $self->_poll_until(
3150 timeout => $o{timeout} // $self->{timeout},
3151 interval => $interval,
3152 cb => $poll_cb,
3153 probe => sub {
3154 my ($done) = @_;
3155 my $self = $wself or return;
3156 # Truthiness decided in JAVASCRIPT, and the value marshalled
3157 # SEPARATELY so its failure cannot sink the verdict. Both halves
3158 # matter: JSON.stringify DROPS a function, so deciding in Perl made
3159 # wait_for_js('window.jQuery') time out on a value truthy throughout
3160 # (and "0" is true in JS, false in Perl); and it THROWS on a cycle or
3161 # a BigInt, so returning the raw value beside the verdict lost the
3162 # whole payload for wait_for_js('window') and for any framework
3163 # object, which are built of back-references. !! runs once, on a
3164 # variable, so a side-effecting expression is still evaluated once.
3165 # __wf is _call_js's own lone-surrogate repair.
3166 $self->script("const __v = ($expr);"
3167 . " let __j; try { __j = JSON.stringify(__v,"
3168 . " (k, v) => typeof v === 'string' ? __wf(v) : v) } catch (e) { }"
3169 . " return { t: !!__v, j: __j === undefined ? null : __j };", sub {
3170 my ($r, $err) = @_;
3171 # A THROW is not terminal. `window.app.ready` throws a TypeError
3172 # for as long as window.app is undefined, which is exactly the
3173 # not-ready-yet state this method exists to wait through -- so
3174 # failing on it would make the common case unusable. The cost is
3175 # that a genuine typo also just times out, which is why the
3176 # message above carries the last error.
3177 if (defined $err) { $last_err = $err; return $done->(0, undef, undef) }
3178 return $done->(0, undef, undef) unless ref $r eq 'HASH';
3179 # j is the value's own JSON text, or null when it had none.
3180 my $val = defined $r->{j} ? eval { _dec($r->{j}) } : undef;
3181 $done->(($r->{t} ? 1 : 0), $val, undef);
3182 });
3183 },
3184 );
3185 }
3186  
3187 # Fetch a URI straight to disk, without navigating to it. Useful on its own,
3188 # and the reliable way to exercise the download path: a page-initiated download
3189 # depends on the server sending something WebKit refuses to display, whereas
3190 # this always produces one.
3191 sub download {
3192 my ($self, $uri, $path, $cb) = @_;
3193 Carp::croak('download: callback must be a code reference') if defined $cb && ref $cb ne 'CODE';
3194 # Normalise HERE, with the same rule save_to applies -- and croak at the
3195 # call site, where the caller can act on it. Left to the save_to inside the
3196 # download-started handler, the croak escaped into GLib's dispatch (which
3197 # only warns), stranding the callback and leaving decide-destination
3198 # unconnected for WebKit to answer however it liked.
3199 $path = EV::WebKit::Download::_norm_dest($path, 'download');
3200 if (!defined $uri || !length $uri) {
3201 $self->_defer_final($cb, undef, 'download: uri required') if $cb;
3202 return $self;
3203 }
3204 if ($self->{_dead} || !$self->{view}) {
3205 $self->_defer_final($cb, undef, 'browser closed') if $cb;
3206 return $self;
3207 }
3208 # The destination and callback belong to THIS request, but they can only be
3209 # applied once WebKit raises download-started. Key them by the identity of
3210 # the WebKitDownload that download_uri hands back -- NEVER by the uri, which
3211 # WebKit CANONICALISES before reporting it: 'http://h:p' gains a '/',
3212 # 'HTTP://' lowercases, '/./x' collapses, a query space becomes '%20'. Each
3213 # of those missed its parked entry, so the download was cancelled as
3214 # destination-less and the callback sat there until quit. Identity also makes
3215 # two concurrent downloads of the same uri distinct by construction.
3216 my $dl = eval { $self->{view}->download_uri($uri) };
3217 if (!$dl) {
3218 my $err = $@ || 'download failed to start';
3219 $self->_defer_final($cb, undef, "download: " . _clean($err)) if $cb;
3220 return $self;
3221 }
3222 # download-started is asynchronous on this engine, so the wrapper does not
3223 # exist yet and the request is parked for the handler to claim. Should a
3224 # future WebKit raise it synchronously from inside download_uri, the
3225 # wrapper is already indexed -- apply to it directly rather than parking an
3226 # entry no signal will ever come back for.
3227 my $addr = refaddr $dl;
3228 if (my $d = $self->{_dl_native}{$addr}) {
3229 $d->save_to($path);
3230 $d->on_finish($cb) if $cb;
3231 return $self;
3232 }
3233 # Hold the native strongly: it pins the address, so a later download cannot
3234 # be allocated at the same one and claim this entry.
3235 $self->{_dl_want}{$addr} = { dest => $path, cb => $cb, dl => $dl };
3236 return $self;
3237 }
3238  
3239 sub screenshot {
3240 my $self = shift;
3241 my $cb = pop;
3242 Carp::croak('screenshot: last argument must be a callback') unless ref $cb eq 'CODE';
3243 if ($self->{_dead} || !$self->{view}) { $self->_defer_final($cb, undef, 'browser closed'); return $self }
3244 # The unknown-option sweep every option-taking sibling has.
3245 # Both failure modes were measured: `ful => 1` silently produced a VIEWPORT
3246 # shot where the caller asked for the full document, reported as success and
3247 # indistinguishable from a correct one; and `screenshot(bytes => 1, $cb)` --
3248 # the natural spelling, since every other method here takes trailing pairs,
3249 # while the no-path form uniquely wants a hashref -- took 'bytes' for the
3250 # PATH, wrote a PNG to a file literally named `bytes` in the cwd, warned
3251 # "Odd number of elements" from inside this file, and reported success.
3252 # Control.pm's screenshot branch already guarded the socket path against
3253 # exactly this; the method it wraps did not.
3254 my ($path, %o);
3255 if (ref $_[0] eq 'HASH') {
3256 %o = %{ shift() };
3257 Carp::croak('screenshot: the options hashref takes no further arguments') if @_;
3258 }
3259 else {
3260 $path = shift;
3261 Carp::croak('screenshot: the path must be a plain string, not a ' . ref($path) . ' reference')
3262 if ref $path && !Scalar::Util::blessed($path);
3263 Carp::croak('screenshot: options must be name => value pairs') if @_ % 2;
3264 %o = @_;
3265 }
3266 if (my @bad = sort grep { !/^(?:full|transparent|bytes)$/ } keys %o) {
3267 Carp::croak("screenshot: unknown option(s): @bad (expected full/transparent/bytes)");
3268 }
3269 unless (defined $path || $o{bytes}) {
3270 $self->_defer_final($cb, undef, 'screenshot path required (or bytes => 1)');
3271 return $self;
3272 }
3273 my $region = $o{full} ? 'full-document' : 'visible';
3274 my $options = $o{transparent} ? 'transparent-background' : 'none';
3275 $cb = $self->_op_track($cb); # quit() mid-flight resolves this instead of dropping it
3276 my $cancel = Glib::IO::Cancellable->new;
3277 my $timer = EV::timer($self->{timeout}, 0, sub { $cancel->cancel });
3278 my $done = 0;
3279 # same GI async-ready-callback retention as _call_js (see there) -- weaken.
3280 weaken(my $wself = $self);
3281 $self->{view}->get_snapshot($region, $options, $cancel, sub {
3282 return if $done; $done = 1; $timer->stop;
3283 # Release the captures -- GI never lets go of this closure, so what it
3284 # still holds is held for the life of the process. See _call_js.
3285 my ($lcb, $lcancel) = ($cb, $cancel);
3286 undef $cb; undef $cancel; undef $timer;
3287 my $self = $wself or return;
3288 my $tex = eval { $self->{view}->get_snapshot_finish($_[1]) };
3289 return $self->_defer($lcb, undef, $lcancel->is_cancelled ? 'timeout' : _clean($@)) if $@;
3290 my $data = eval { $tex->save_to_png_bytes->get_data };
3291 return $self->_defer($lcb, undef, 'png encode: ' . _clean($@)) if $@;
3292 return $self->_defer($lcb, $data, undef) if $o{bytes};
3293 open my $fh, '>:raw', $path or return $self->_defer($lcb, undef, "open $path: $!");
3294 # print alone can look like it succeeded even when the underlying
3295 # write(2) is doomed (e.g. disk full): a short write is usually just
3296 # buffered by perlio, with the real failure only surfacing at close
3297 # (flush) time -- so capture errno right after print (in case it DID
3298 # fail synchronously) but let a subsequent close failure win, since
3299 # that's the common/authoritative case. Silently reporting success
3300 # here (as before) would tell the caller a screenshot exists when
3301 # nothing (or a truncated file) was actually written.
3302 my $ok = print $fh $data;
3303 my $err = $!;
3304 unless (close $fh) { $ok = 0; $err = $! }
3305 return $self->_defer($lcb, undef, "write $path: $err") unless $ok;
3306 $self->_defer($lcb, $path, undef);
3307 });
3308 return $self;
3309 }
3310  
3311 sub pdf {
3312 my $self = shift;
3313 my $path = shift;
3314 my $cb = pop; # signature: pdf($path, %opt, $cb) -- callback is always last
3315 Carp::croak('pdf: last argument must be a callback') unless ref $cb eq 'CODE';
3316 # UNBLESSED refs only. A blessed object may stringify to a path (File::Temp,
3317 # Path::Tiny), and t/56 deliberately passes one whose stringify DIES to prove
3318 # a setup-phase throw reaches the callback instead of escaping -- so this
3319 # must not swallow that case. A plain hashref, though, is the screenshot
3320 # habit applied to the wrong method, and used to become the FILENAME.
3321 Carp::croak('pdf: the path must be a plain string, not a ' . ref($path) . ' reference'
3322 . (ref $path eq 'HASH' ? ' (pdf takes a path first, then options as pairs)' : ''))
3323 if ref $path && !Scalar::Util::blessed($path);
3324 # Same sweep as screenshot above: a typo'd `papre` silently rendered iso_a4
3325 # and reported success.
3326 Carp::croak('pdf: options must be name => value pairs') if @_ % 2;
3327 {
3328 my %chk = @_;
3329 if (my @bad = sort grep { !/^(?:paper|margin|resolution|timeout)$/ } keys %chk) {
3330 Carp::croak("pdf: unknown option(s): @bad (expected paper/margin/resolution/timeout)");
3331 }
3332 }
3333 if ($self->{_dead} || !$self->{view}) { $self->_defer_final($cb, undef, 'browser closed'); return $self }
3334 unless (defined $self->{view}->get_uri && length $self->{view}->get_uri) {
3335 # Printing a view that has NEVER loaded a document SIGSEGVs deep in
3336 # WebKit's C print path (a native crash no eval can catch) -- refuse
3337 # cleanly, mirroring reload()'s "nothing to reload" pre-check. Any
3338 # prior navigation (even load_html, even a not-yet-committed go())
3339 # gives the view a uri and makes printing safe.
3340 $self->_defer_final($cb, undef, 'pdf: no page loaded');
3341 return $self;
3342 }
3343 $cb = $self->_op_track($cb); # quit() mid-flight resolves this (queued OR active) instead of dropping it
3344 my %o = @_;
3345 # SERIALIZE: two WebKit::PrintOperations running on one view at the same
3346 # time race at the engine level -- the failing one can fire 'finished' (a
3347 # false success), or disrupt the other, making concurrent pdf() outcomes
3348 # non-deterministic (the R12 magic-check catches a false success but not a
3349 # good op that got clobbered). Queue each request and run exactly one
3350 # PrintOperation at a time.
3351 my $id = ++$_pdf_seq;
3352 push @{ $self->{_pdf_queue} }, [$id, $path, \%o, $cb];
3353  
3354 # Watchdog, armed HERE (at enqueue) rather than when the job reaches the
3355 # head of the queue: the caller asked for a deadline from the moment they
3356 # called, and a job waiting behind a slow -- or genuinely stuck -- print
3357 # must be bounded too, or it would never resolve at all. Keyed by job id in
3358 # {_pdf_timers} (never captured by _pdf_run's closures): the callback closes
3359 # over the id (a number), the tracked $cb and a weak $self only, so nothing
3360 # here can form a refcount cycle with the PrintOperation.
3361 weaken(my $wself = $self);
3362 $self->{_pdf_timers}{$id} = EV::timer($o{timeout} // $self->{timeout}, 0, sub {
3363 my $self = $wself or return;
3364 return if $self->{_dead}; # quit() already resolved this callback
3365 delete $self->{_pdf_timers}{$id}; # gone == "this caller has given up" (see _pdf_pump)
3366 # plain 'timeout' -- the SAME error every other timed op in this module
3367 # resolves with (navigation, wait_for, the cookie ops), so a caller can
3368 # test $err eq 'timeout' uniformly. pdf's other errors are prefixed
3369 # because they are pdf-specific; a timeout is a cross-cutting contract.
3370 $self->_defer($cb, undef, 'timeout');
3371 });
3372 $self->_pdf_pump;
3373 return $self;
3374 }
3375  
3376 # Start the next queued pdf job, if any and none is already running.
3377 sub _pdf_pump {
3378 my $self = shift;
3379 return if $self->{_pdf_active} || $self->{_dead} || !$self->{view};
3380 my $q = $self->{_pdf_queue} || [];
3381 while (my $job = shift @$q) {
3382 # Its watchdog already fired (entry deleted), so this caller has been
3383 # told 'timeout' and is no longer waiting -- don't spend a print on a
3384 # document nobody wants. (An ALREADY-RUNNING op that times out is
3385 # different: it is still live and must keep the view -- see _pdf_run.)
3386 next unless exists $self->{_pdf_timers}{ $job->[0] };
3387 $self->{_pdf_active} = 1;
3388 $self->_pdf_run(@$job);
3389 return;
3390 }
3391 return;
3392 }
3393  
3394 # Run ONE PrintOperation to completion, then free the queue and pump the next.
3395 sub _pdf_run {
3396 my ($self, $id, $path, $o, $cb) = @_;
3397 my $done = 0; # caller's callback resolved?
3398 my $released = 0; # queue slot released?
3399 # weaken (as elsewhere): the $op and its signal closures are local/transient,
3400 # but never let a stray retention keep $self alive.
3401 weaken(my $wself = $self);
3402  
3403 # RESOLVING THE CALLER and RELEASING THE QUEUE are deliberately separate.
3404 # WebKit offers NO way to stop an in-flight print (WebKit-6.0's
3405 # PrintOperation has no cancel at all), so a print that has blown its
3406 # deadline is still running. Two PrintOperations alive on one view crash the
3407 # engine -- that race is the entire reason this queue exists -- so the
3408 # watchdog (armed in pdf(), at enqueue) only ever resolves the CALLER; it
3409 # must never hand the view to the next job. The view is released here, and
3410 # only when the engine itself says it is done with this operation.
3411  
3412 # resolve the caller exactly once. Does NOT touch the queue. (The watchdog
3413 # may already have answered them -- $cb is _op_track'd, so this is a no-op.)
3414 my $resolve = sub {
3415 my ($val, $err) = @_;
3416 return if $done; $done = 1;
3417 my $self = $wself or return;
3418 $self->_defer($cb, $val, $err);
3419 };
3420 # release the view for the next job, exactly once. ONLY safe when the engine
3421 # is really finished with this PrintOperation (its finished/failed arrived),
3422 # or when the op never started at all (setup/print threw). Also disarms this
3423 # job's watchdog: reached by id through $self, never captured here, so the
3424 # closures below cannot form a cycle with the PrintOperation.
3425 my $release = sub {
3426 return if $released; $released = 1;
3427 my $self = $wself or return;
3428 delete $self->{_pdf_timers}{$id};
3429 $self->{_pdf_active} = 0;
3430 # Kept on $self (weak closure, like every other timer here) so quit()
3431 # owns it: an untracked timer surviving teardown is exactly the kind of
3432 # loose end this module has been bitten by. Single slot is enough --
3433 # only one job is ever active, so only one pump can be in flight.
3434 $self->{_pdf_pump_timer} = EV::timer(0, 0, sub {
3435 my $s = $wself or return;
3436 delete $s->{_pdf_pump_timer};
3437 $s->_pdf_pump;
3438 });
3439 };
3440 # Wrap the WHOLE operation -- constructing the PrintOperation/settings/page
3441 # setup (which stringifies $path and the %opt values), connecting the
3442 # signals, and print() -- in one eval. A throw anywhere here (e.g. a hostile
3443 # $path/opt whose stringification dies, or a future stricter GI binding
3444 # rejecting a value) must reach the caller's callback and reset _pdf_active,
3445 # exactly as the print() throw already did: otherwise _pdf_active stays 1
3446 # and every later queued pdf() is starved forever (and a first job's throw
3447 # would escape synchronously out of pdf(), breaking its callback-only
3448 # contract). $op is declared in this scope (not the eval block) so its
3449 # lifetime is unchanged.
3450 my $op;
3451 my $dispatched = 0; # has print() been entered? (see the failure branch below)
3452 my $ok = eval {
3453 my $paper = $o->{paper} // 'iso_a4';
3454 my $mm = $o->{margin} // 0;
3455 my $dpi = $o->{resolution} // 300;
3456 $op = WebKit::PrintOperation->new($self->{view});
3457 my $ps = Gtk4::PrintSettings->new;
3458 # filename_to_uri, NOT 'file://' . path. GLib parses what it is given as
3459 # a URI, so a raw path is silently reinterpreted: it truncates at '#' or
3460 # '?' and percent-DECODES any %XX. Measured -- pdf("$dir/report#1.pdf")
3461 # wrote the PDF over "$dir/report", destroying whatever was there, and
3462 # then told the caller their own file had not been written, saying
3463 # nothing about the one that had. Naming a pdf from a page title or an
3464 # id is ordinary, and download's _norm_dest already guards this class.
3465 $ps->set('output-uri', Glib::filename_to_uri(rel2abs($path), undef));
3466 $ps->set('output-file-format', 'pdf');
3467 $ps->set_resolution($dpi);
3468 $ps->set_printer('Print to File');
3469 $op->set_print_settings($ps);
3470 my $pgs = Gtk4::PageSetup->new;
3471 $pgs->set_paper_size(Gtk4::PaperSize->new($paper));
3472 $pgs->set_top_margin($mm,'mm'); $pgs->set_bottom_margin($mm,'mm');
3473 $pgs->set_left_margin($mm,'mm'); $pgs->set_right_margin($mm,'mm');
3474 $op->set_page_setup($pgs);
3475 $op->signal_connect(finished => sub {
3476 unless ($done) {
3477 # R12: 'finished' alone isn't trustworthy (moot now that we serialize,
3478 # kept as belt-and-braces) -- verify a real PDF was written before
3479 # reporting success, mirroring screenshot()'s post-write verification.
3480 my $valid = defined($path) && -s $path && do {
3481 my $magic = '';
3482 if (open my $fh, '<:raw', $path) { read($fh, $magic, 5); close $fh }
3483 $magic eq '%PDF-';
3484 };
3485 $valid ? $resolve->($path, undef)
3486 : $resolve->(undef, "pdf: print reported success but no valid PDF written to "
3487 . (defined $path ? $path : '(undef path)'));
3488 }
3489 # The engine is done with this operation (even if the caller was
3490 # already given a 'timeout' answer above) -- only NOW is it safe to
3491 # hand the view to the next queued job.
3492 $release->();
3493 });
3494 $op->signal_connect(failed => sub {
3495 $resolve->(undef, "pdf failed: ".(ref $_[1] ? $_[1]->message : ($_[1]//'')));
3496 $release->();
3497 });
3498 # NB: no watchdog is armed here -- this job's deadline has been running
3499 # since pdf() enqueued it (see there). And there is nothing to cancel:
3500 # WebKit-6.0's PrintOperation exposes no cancel method at all, so once
3501 # print() is under way the only thing that ends it is the engine.
3502 $dispatched = 1;
3503 $op->print;
3504 1;
3505 };
3506 # Setup or print threw. Always answer the caller. Whether we may hand the
3507 # view to the NEXT job depends on whether the engine could already be
3508 # printing:
3509 # - the throw came from the setup statements above (paper/margin/path
3510 # stringification, PrintSettings/PageSetup construction): nothing was
3511 # dispatched, so release the slot -- otherwise _pdf_active stays 1 and
3512 # every later pdf() starves forever.
3513 # - the throw came from print() itself: we cannot know whether it got far
3514 # enough to start the engine. Releasing on that guess would be betting
3515 # the process on it -- a second PrintOperation alongside a live one
3516 # SEGFAULTS WebKit (the race this whole queue exists to prevent). So
3517 # hold the slot and let finished/failed release it, as on any normal
3518 # print. If the engine truly never started, those never come and this
3519 # instance's pdf() is done for -- but callers still get answers, not a
3520 # hang: every queued job's watchdog was armed at enqueue and fires on
3521 # its own deadline, and quit() clears the queue. A bounded, visible
3522 # stall beats a crash we cannot rule out.
3523 # (print() takes no arguments and is void, so a throw from it would almost
3524 # certainly be a pre-dispatch marshalling failure -- but "almost certainly"
3525 # is not a basis for risking a SIGSEGV.)
3526 unless ($ok) {
3527 my $e = _clean($@);
3528 $resolve->(undef, $e);
3529 $release->() unless $dispatched;
3530 }
3531 return;
3532 }
3533  
3534  
3535 # GIO async completions for cookie-manager/website-data-manager ops arrive from
3536 # inside the glib main-context dispatch that EV::Glib bridges into EV. Calling
3537 # EV::break synchronously from that frame (as a user callback naturally would,
3538 # matching every other callback in this module) unwinds out of ev_run while
3539 # still nested inside the glib dispatch, which corrupts EV::Glib's
3540 # prepare/check bookkeeping and wedges any *subsequent* EV::run into a
3541 # permanent busy spin -- confirmed with gdb: the main thread parks at a single
3542 # PC inside ev_run's pending-invoke loop, 99%+ CPU, no watcher (not even an
3543 # unrelated native EV::timer) ever fires again. Invisible to single-EV::run
3544 # tests (nothing runs afterward); fatal to the sequential-instance pattern
3545 # this task's persistence test needs (instance A's cookie op must be followed
3546 # by a second, independent EV::run for instance B). A zero-delay EV::timer
3547 # defers the user callback to a clean top-level tick, fully unwound from the
3548 # glib dispatch frame, which avoids the wedge.
3549 my $_defer_seq = 0;
3550 sub _defer {
3551 my ($self, $cb, @a) = @_;
3552 return unless $cb; # matches _defer_final's guard -- a cb-less call is a clean no-op,
3553 # not a deferred `undef->(@a)` (which EV would catch and route to
3554 # $EV::DIED, but that's still noise a cb-optional call shouldn't cause)
3555 return if $self->{_dead};
3556 my $id = ++$_defer_seq;
3557 # weak, like every other closure this module hangs off $self: a strong $self
3558 # here is self -> {_defer}{id} -> timer -> closure -> self, a real cycle.
3559 # It happens to be self-healing (the one-shot fires, deletes itself, drops
3560 # the last ref), which is exactly why it hid from every collectability test
3561 # -- they all spin a tick before checking. But an instance dropped with a
3562 # deferral pending then stayed alive until the loop ticked again, and if it
3563 # never did, until process exit. Dropping the timer with $self is safe: quit
3564 # (which DESTROY runs) flushes {_ops}/{_waiters}/{pending} itself, so the
3565 # callback this timer was about to deliver is resolved there instead.
3566 weaken(my $wself = $self);
3567 $self->{_defer}{$id} = EV::timer(0, 0, sub {
3568 my $s = $wself or return; # instance gone: quit() already flushed this callback
3569 delete $s->{_defer}{$id};
3570 $cb->(@a);
3571 });
3572 return;
3573 }
3574  
3575 # deliver an immediate-failure callback on the next clean EV tick, regardless
3576 # of _dead (unlike _defer, which suppresses post-quit delivery of in-flight
3577 # ops): calls made AFTER quit still owe their caller a 'browser closed'.
3578 my $_final_seq = 0;
3579 sub _defer_final {
3580 my ($self, $cb, @a) = @_;
3581 return unless $cb;
3582 my $id = 'f' . ++$_final_seq;
3583 # Deliberately NOT hung off $self: the answer is already decided, $self is
3584 # not needed to deliver it, and these callbacks (the early-error guards --
3585 # 'browser closed', 'uri required', ...) are in no registry, so quit() has
3586 # nothing to flush for them. Keeping the timer on $self would both create a
3587 # self -> hash -> timer -> closure -> self cycle AND make delivery hostage
3588 # to the instance outliving the tick -- drop the browser right after the
3589 # call and the callback would simply never fire. A file-scoped registry has
3590 # neither problem: the instance is collectable immediately, and the callback
3591 # still fires exactly once on the next tick.
3592 $FINAL{$id} = EV::timer(0, 0, sub {
3593 delete $FINAL{$id};
3594 $cb->(@a);
3595 });
3596 return;
3597 }
3598  
3599 # Register a one-shot async op's callback so quit() can resolve it with
3600 # 'browser closed' even if the op is still in flight (its GAsyncReadyCallback
3601 # completion is dead-gated via _defer and would otherwise be silently
3602 # swallowed on quit -- the same dropped-callback class the loop treats as a
3603 # defect). Returns a wrapper to use IN PLACE of $cb everywhere downstream: it
3604 # fires the real $cb at most once (dedupe guard) and deregisters itself the
3605 # instant it fires, whether that is a normal _defer delivery or quit()'s
3606 # synchronous flush. The wrapper weakens $self so an in-flight op cannot keep
3607 # a dropped browser alive (preserving the collectability guarantee, t/46).
3608 # The `if (my $s = $wself)` inside it is DEFENSIVE, not load-bearing: it covers
3609 # the wrapper outliving $self (only a DESTROY-driven teardown reaches
3610 # _flush_later, since an ordinary quit() defers past the dispatch frame), and
3611 # without it `delete $wself->{_ops}{$id}` would merely autovivify a hash on an
3612 # undef alias rather than die. Both measured -- do not read it as protecting
3613 # something.
3614 #
3615 # A wait_for and a pending nav are NOT tracked here, because each already has
3616 # somewhere to be flushed FROM: a wait_for's $finish lives in {_waiters} and a
3617 # pending nav's raw callback in {pending}, and _teardown flushes both in place.
3618 # The RESOLUTION side of a nav is a different matter and IS tracked --
3619 # _finish_nav and wait_for_navigation both wrap their callback with this.
3620 my $_op_seq = 0;
3621 sub _op_track {
3622 my ($self, $cb) = @_;
3623 return $cb unless ref $cb eq 'CODE';
3624 my $id = ++$_op_seq;
3625 weaken(my $wself = $self);
3626 my $fired = 0;
3627 my $wrap = sub {
3628 return if $fired; $fired = 1;
3629 if (my $s = $wself) { delete $s->{_ops}{$id} }
3630 $cb->(@_);
3631 };
3632 ($self->{_ops} ||= {})->{$id} = $wrap;
3633 return $wrap;
3634 }
3635  
3636 # The set of native objects a cookie-manager async op must keep alive until
3637 # its NATIVE side completes. quit()/DESTROY drop $self's references to these
3638 # synchronously; if WebKit finalizes them (network session / web context)
3639 # while a get_cookies/add_cookie is still in flight, it use-after-frees deep
3640 # in its C code (segfault, reproducible). A cookie op captures this list
3641 # strongly for the duration of the underlying GIO call and empties it (on a
3642 # clean tick) the instant the call finishes -- so the objects outlive the op
3643 # regardless of a concurrent teardown, yet never leak. $hold[0] is the session
3644 # (callers use it to reach the cookie manager after $self->{session} is gone).
3645 sub _native_hold { my $self = shift; return @{$self}{qw/session context ucm view/} }
3646  
3647 # Release a captured native keep-alive (see _native_hold) on the next CLEAN EV
3648 # tick. A cookie-manager completion must NOT drop these refs synchronously:
3649 # doing so finalizes the network session/context from *inside* WebKit's own
3650 # dispatch of that very completion, which re-enters and use-after-frees
3651 # (segfault). Deferring the finalization out of the dispatch frame -- exactly
3652 # why _defer exists -- makes it safe. Not dead-gated: it must run after quit()
3653 # too, or the natives would leak. $ref is a reference to the op's @hold array.
3654 sub _release_natives_later {
3655 my $ref = shift;
3656 my $rt; $rt = EV::timer(0, 0, sub { @$ref = (); undef $rt });
3657 return;
3658 }
3659  
3660 sub set_cookie {
3661 my ($self, $spec, $cb) = @_;
3662 Carp::croak('set_cookie: callback must be a code reference') if defined $cb && ref $cb ne 'CODE';
3663 if ($self->{_dead} || !$self->{session}) { $self->_defer_final($cb, undef, 'browser closed'); return $self }
3664 unless (ref $spec eq 'HASH') { # a plain-string arg would else die raw "Can't use string as a HASH ref" inside the loop below
3665 $self->_defer_final($cb, undef, 'set_cookie: spec must be a hash reference');
3666 return $self;
3667 }
3668 for my $k (qw/name value domain/) {
3669 unless (defined $spec->{$k}) {
3670 $self->_defer_final($cb, undef, "set_cookie: missing '$k'");
3671 return $self;
3672 }
3673 }
3674 # A typo'd security flag (secur => / http_ony =>) must not be silently
3675 # dropped: the cookie would then be created WITHOUT Secure/HttpOnly and sent
3676 # over plaintext / exposed to JS. Reject unknown spec keys.
3677 {
3678 my %known = map { $_ => 1 } qw/name value domain path max_age secure http_only/;
3679 if (my @bad = sort grep { !$known{$_} } keys %$spec) {
3680 $self->_defer_final($cb, undef, "set_cookie: unknown key(s): @bad");
3681 return $self;
3682 }
3683 }
3684 my $c = eval {
3685 Soup::Cookie->new(
3686 $spec->{name}, $spec->{value},
3687 $spec->{domain}, $spec->{path} // '/',
3688 $spec->{max_age} // -1,
3689 );
3690 };
3691 unless ($c) {
3692 $self->_defer_final($cb, undef, 'set_cookie: ' . _clean($@));
3693 return $self;
3694 }
3695 $c->set_secure(1) if $spec->{secure};
3696 $c->set_http_only(1) if $spec->{http_only};
3697 $cb = $self->_op_track($cb); # quit() mid-flight resolves this instead of dropping it
3698 my $cancel = Glib::IO::Cancellable->new;
3699 my $timer = EV::timer($self->{timeout}, 0, sub { $cancel->cancel }); # watchdog: bound a stuck op (cancel -> completion resolves 'timeout')
3700 my @hold = $self->_native_hold; # keep natives alive until this add_cookie's native side finishes (UAF on teardown otherwise -- see _native_hold)
3701 # same GI async-ready-callback retention as _call_js (see there) -- weaken.
3702 weaken(my $wself = $self);
3703 my $done = 0;
3704 $hold[0]->get_cookie_manager->add_cookie($c, $cancel, sub {
3705 return if $done; $done = 1;
3706 $timer->stop;
3707 my $ok = eval { $hold[0]->get_cookie_manager->add_cookie_finish($_[1]); 1 }; # captured session, NOT $self->{session} (deleted by quit)
3708 _release_natives_later(\@hold); # drop the keep-alive on a clean tick (never synchronously here -- see _release_natives_later)
3709 # Release the captures -- GI never lets go of this closure, so what it
3710 # still holds is held for the life of the process. See _call_js.
3711 my ($lcb, $lcancel) = ($cb, $cancel);
3712 undef $cb; undef $cancel; undef $timer;
3713 my $self = $wself or return;
3714 $self->_defer($lcb, $ok ? 1 : undef, $ok ? undef : ($lcancel->is_cancelled ? 'timeout' : _clean($@)));
3715 });
3716 return $self;
3717 }
3718  
3719 sub cookies {
3720 my ($self, $uri, $cb) = @_;
3721 Carp::croak('cookies: callback must be a code reference') if defined $cb && ref $cb ne 'CODE';
3722 if ($self->{_dead} || !$self->{session}) { $self->_defer_final($cb, undef, 'browser closed'); return $self }
3723 unless (defined $uri && length $uri) {
3724 $self->_defer_final($cb, undef, 'cookies: uri required');
3725 return $self;
3726 }
3727 $cb = $self->_op_track($cb); # quit() mid-flight resolves this instead of dropping it
3728 my $cancel = Glib::IO::Cancellable->new;
3729 my $timer = EV::timer($self->{timeout}, 0, sub { $cancel->cancel }); # watchdog: bound a stuck op (cancel -> completion resolves 'timeout')
3730 my @hold = $self->_native_hold; # keep natives alive until this get_cookies' native side finishes (UAF on teardown otherwise -- see _native_hold)
3731 weaken(my $wself = $self);
3732 my $done = 0;
3733 $hold[0]->get_cookie_manager->get_cookies($uri, $cancel, sub {
3734 return if $done; $done = 1;
3735 $timer->stop;
3736 # get_cookies_finish returns a single arrayref of Soup::Cookie objects,
3737 # NOT a flattened list -- must deref, not `my @c = ...finish(...)`. Use
3738 # the captured session (NOT $self->{session}, which quit deletes).
3739 my $list = eval { $hold[0]->get_cookie_manager->get_cookies_finish($_[1]) };
3740 _release_natives_later(\@hold); # drop the keep-alive on a clean tick (never synchronously here -- see _release_natives_later)
3741 # Release the captures -- GI never lets go of this closure, so what it
3742 # still holds is held for the life of the process. See _call_js.
3743 my ($lcb, $lcancel) = ($cb, $cancel);
3744 undef $cb; undef $cancel; undef $timer;
3745 my $self = $wself or return;
3746 return $self->_defer($lcb, undef, $lcancel->is_cancelled ? 'timeout' : _clean($@)) if $@;
3747 $self->_defer($lcb, [ map { {
3748 name => $_->get_name, value => $_->get_value,
3749 domain => $_->get_domain, path => $_->get_path,
3750 secure => $_->get_secure ? 1 : 0, http_only => $_->get_http_only ? 1 : 0,
3751 } } @$list ], undef);
3752 });
3753 return $self;
3754 }
3755  
3756 sub clear_cookies {
3757 my ($self, $cb) = @_;
3758 Carp::croak('clear_cookies: callback must be a code reference') if defined $cb && ref $cb ne 'CODE';
3759 if ($self->{_dead} || !$self->{session}) { $self->_defer_final($cb, undef, 'browser closed'); return $self }
3760 # Deliberately NO _native_hold here, unlike its three cookie-manager
3761 # siblings above. Those crash if the session is finalised under an in-flight
3762 # op; this one goes through the website-data-manager, whose native lifetime
3763 # does not depend on {session}/{view} surviving teardown, so it is safe
3764 # without one (originally established when the teardown UAF was fixed, and
3765 # re-confirmed since under ~900 quit/DESTROY-mid-flight iterations and
3766 # valgrind). Keep it that way -- do not "restore uniformity" by adding a
3767 # hold, and do not copy this op's shape onto a cookie-manager one.
3768 my $wdm = $self->{session}->get_website_data_manager;
3769 $cb = $self->_op_track($cb); # quit() mid-flight resolves this instead of dropping it
3770 my $cancel = Glib::IO::Cancellable->new;
3771 my $timer = EV::timer($self->{timeout}, 0, sub { $cancel->cancel }); # watchdog: bound a stuck op (cancel -> completion resolves 'timeout')
3772 weaken(my $wself = $self);
3773 my $done = 0;
3774 # WebKit::WebsiteDataTypes is a GFlags type: Glib::Object::Introspection
3775 # marshals flags as an arrayref of nick strings, not a bare string.
3776 # 0 timespan = clear everything (not just data since some cutoff).
3777 $wdm->clear(['cookies'], 0, $cancel, sub {
3778 return if $done; $done = 1;
3779 $timer->stop;
3780 my $ok = eval { $wdm->clear_finish($_[1]); 1 };
3781 # Release the captures -- GI never lets go of this closure, so what it
3782 # still holds is held for the life of the process (the data-manager
3783 # included). See _call_js.
3784 my ($lcb, $lcancel) = ($cb, $cancel);
3785 undef $cb; undef $cancel; undef $timer; undef $wdm;
3786 my $self = $wself or return;
3787 $self->_defer($lcb, $ok ? 1 : undef, $ok ? undef : ($lcancel->is_cancelled ? 'timeout' : _clean($@)));
3788 });
3789 return $self;
3790 }
3791  
3792 sub save_cookies {
3793 my $self = shift;
3794 my $cb = pop;
3795 Carp::croak('save_cookies: callback must be a code reference') if defined $cb && ref $cb ne 'CODE';
3796 if ($self->{_dead} || !$self->{session}) { $self->_defer_final($cb, undef, 'browser closed'); return $self }
3797 my $file = shift;
3798 unless (defined $file && length $file) {
3799 $self->_defer_final($cb, undef, 'snapshot file required');
3800 return $self;
3801 }
3802 if (@_) {
3803 Carp::croak('save_cookies: the URI list must be an array reference'
3804 . (ref $_[0] ? '' : ' (cookies() takes a bare uri, but this takes a list)'))
3805 unless ref $_[0] eq 'ARRAY';
3806 }
3807 my $uris = @_ ? shift : [ keys %{ $self->{_seen_uris} || {} } ];
3808 unless (@$uris) {
3809 $self->_defer_final($cb, undef, 'no URIs to save (navigate first or pass a URI list)');
3810 return $self;
3811 }
3812  
3813 # Per-URI get_cookies (NOT get_all_cookies): get_all_cookies/get_all_cookies_finish
3814 # are a latent memory-safety hazard (valgrind-confirmed invalid read when a call is
3815 # left in-flight at teardown).
3816 # get_cookies($uri) is the proven-clean enumeration path already used by cookies()
3817 # above, so save_cookies fans it out across every URI this instance has navigated
3818 # to (or an explicit list) and merges the results. This is an explicit, opt-in JSON
3819 # snapshot -- distinct from cookie_jar's native persistence (see new()) -- and the
3820 # only way to capture SESSION cookies, which native persistence excludes by design.
3821 # Expiry stays session-only here: get_expires dies (GDateTime not registered with
3822 # gperl in this GI binding), so it is deliberately never called.
3823 $cb = $self->_op_track($cb); # quit() mid-flight resolves this instead of dropping it
3824 my (%dedup, @rows, $err);
3825 my $pending = scalar @$uris;
3826 my @hold = $self->_native_hold; # keep natives alive until ALL per-URI get_cookies native sides finish (UAF on teardown otherwise -- see _native_hold); released once on the last completion
3827 # one shared weak $self, captured by every per-URI closure below (same GI
3828 # async-ready-callback retention as _call_js -- see there).
3829 weaken(my $wself = $self);
3830 my @cancels;
3831 my $timer = EV::timer($self->{timeout}, 0, sub { $_->cancel for @cancels }); # one watchdog for the whole fan-out -- cancel every in-flight per-URI op
3832 for my $uri (@$uris) {
3833 my $cancel = Glib::IO::Cancellable->new;
3834 push @cancels, $cancel;
3835 my $done = 0;
3836 $hold[0]->get_cookie_manager->get_cookies($uri, $cancel, sub {
3837 return if $done; $done = 1;
3838 my $list = eval { $hold[0]->get_cookie_manager->get_cookies_finish($_[1]) }; # captured session, NOT $self->{session} (deleted by quit)
3839 # A snapshot is all-or-nothing on purpose: writing a file that is
3840 # silently missing one URI's cookies is worse than not writing one.
3841 # But name the URI that failed -- with a bare message the caller
3842 # cannot tell WHICH of the fan-out went wrong.
3843 if ($@) { $err = $cancel->is_cancelled ? 'timeout' : "$uri: " . _clean($@) }
3844 elsif (ref($list) eq 'ARRAY') {
3845 for my $c (@$list) {
3846 my $key = join("\x1e", $c->get_name, $c->get_domain, $c->get_path);
3847 next if $dedup{$key}++;
3848 push @rows, {
3849 name => $c->get_name, value => $c->get_value,
3850 domain => $c->get_domain, path => $c->get_path,
3851 secure => $c->get_secure ? 1 : 0, http_only => $c->get_http_only ? 1 : 0,
3852 };
3853 }
3854 }
3855 my $last = (--$pending <= 0); # decrement regardless of $self liveness so the keep-alive is always released
3856 $timer->stop if $last; # all per-URI ops done -- disarm the watchdog
3857 _release_natives_later(\@hold) if $last; # last per-URI native op done -- drop the keep-alive on a clean tick
3858 my $self = $wself or return;
3859 return if !$last; # more URIs still in flight
3860 # Release the captures on the LAST completion -- GI never lets go of
3861 # these closures, so what they still hold is held for the life of
3862 # the process. Only the last one may do it: the others are still
3863 # using @cancels via the shared watchdog. See _call_js.
3864 my $lcb = $cb;
3865 undef $cb; undef $timer; @cancels = ();
3866 return $self->_defer($lcb, undef, $err) if $err;
3867 my $ok = eval {
3868 # :utf8 -- _enc (character-mode codec) can hand back a wide
3869 # Perl string; encode it properly instead of a raw byte dump.
3870 open my $fh, '>:utf8', $file or die "open $file: $!\n";
3871 print $fh _enc(\@rows);
3872 close $fh or die "close $file: $!\n";
3873 1;
3874 };
3875 return $self->_defer($lcb, undef, _clean($@)) unless $ok;
3876 $self->_defer($lcb, scalar(@rows), undef);
3877 });
3878 }
3879 return $self;
3880 }
3881  
3882 sub load_cookies {
3883 my ($self, $file, $cb) = @_;
3884 Carp::croak('load_cookies: callback must be a code reference') if defined $cb && ref $cb ne 'CODE';
3885 if ($self->{_dead} || !$self->{session}) { $self->_defer_final($cb, undef, 'browser closed'); return $self }
3886 unless (defined $file && length $file) {
3887 $self->_defer_final($cb, undef, 'snapshot file required');
3888 return $self;
3889 }
3890 $cb = $self->_op_track($cb); # quit() mid-flight resolves this instead of dropping it
3891 # NOT `return $self->_defer(...)`: _defer returns bare, so chaining off
3892 # the documented `Returns $b` died on the ordinary first run, where the
3893 # jar does not exist yet and this path is explicitly not an error.
3894 unless (-e $file) { $self->_defer($cb, 0, undef); return $self }
3895 my $rows = eval {
3896 # :utf8 -- must hand _dec (character-mode codec) back a proper
3897 # character string, matching how save_cookies wrote it.
3898 open my $fh, '<:utf8', $file or die "open $file: $!\n";
3899 my $json = do { local $/; <$fh> };
3900 close $fh;
3901 _dec($json);
3902 };
3903 $rows = [] if $@ || ref($rows) ne 'ARRAY'; # treat garbage/unreadable jar as empty, not fatal
3904 # ...and the same for each individual row: a non-hashref entry or one
3905 # missing a required key is skipped rather than fatal (set_cookie itself
3906 # now degrades the same way for a bad spec -- see above -- but filtering
3907 # here keeps the loaded-count semantics honest, since a skipped row was
3908 # never even attempted).
3909 my @valid = grep {
3910 ref $_ eq 'HASH' && defined $_->{name} && defined $_->{value} && defined $_->{domain}
3911 } @$rows;
3912 my $n = @valid;
3913 unless ($n) { $self->_defer($cb, 0, undef); return $self } # see above
3914 my ($pending, $loaded, $timedout) = ($n, 0, 0);
3915 weaken(my $wself = $self);
3916 for my $row (@valid) {
3917 $self->set_cookie({
3918 name => $row->{name}, value => $row->{value},
3919 domain => $row->{domain}, path => $row->{path},
3920 max_age => defined $row->{expires} ? $row->{expires} - time() : -1,
3921 secure => $row->{secure}, http_only => $row->{http_only},
3922 }, sub {
3923 my ($ok, $err) = @_;
3924 $loaded++ if $ok;
3925 # A watchdog timeout cancelled the delegated set_cookie(s): the load
3926 # was cut short, so say so. Reporting the plain (loaded, undef) count
3927 # here would be indistinguishable from "the jar held no valid rows".
3928 $timedout = 1 if defined $err && $err eq 'timeout';
3929 return if --$pending > 0;
3930 # If quit() has torn the browser down, do NOT deliver a
3931 # (loaded, undef) success here: each delegated set_cookie is its
3932 # own tracked op, so quit()'s flush fires this last one AND our
3933 # own {_ops} entry in an undefined order -- letting this branch win
3934 # would hand the caller a fake 0-loaded "success" instead of the
3935 # 'browser closed' our own entry owes them. Leave it to that entry.
3936 return if $wself && $wself->{_dead};
3937 # otherwise we're on a clean tick (set_cookie routes its callback
3938 # through _defer), so a direct $cb->() is safe.
3939 return $cb->(undef, 'timeout') if $timedout;
3940 $cb->($loaded, undef);
3941 });
3942 }
3943 return $self;
3944 }
3945  
3946 sub quit {
3947 my $self = shift;
3948 return if $self->{_dead};
3949 $self->{_dead} = 1; # set first: re-entrant calls now hit the guards
3950 # Shut the in-process proxy down first: plain EV/Perl (no GI callbacks), so
3951 # it is safe even inside a dispatch frame, and stopping it before the
3952 # GI/window teardown keeps proxy traffic from racing it.
3953 if (my $proxy = delete $self->{proxy}) { eval { $proxy->shutdown } }
3954 delete $self->{network_fingerprint};
3955 $_->stop for values %{ $self->{_defer} || {} }; # cancel in-flight deferred callbacks
3956 $self->{_defer} = {};
3957 $_->stop for values %{ $self->{_settle} || {} };
3958 $self->{_settle} = {};
3959 # ...and the notify::title handlers racing those timers, which would
3960 # otherwise stay subscribed to a view we are about to destroy.
3961 if (my $v = $self->{view}) {
3962 eval { $v->signal_handler_disconnect($_) } for values %{ $self->{_settle_sig} || {} };
3963 }
3964 $self->{_settle_sig} = {};
3965 # Called from INSIDE a WebKit/GLib dispatch frame (on_dialog, on_policy,
3966 # on_console, a mock_scheme producer)? Then finish on a clean EV tick
3967 # instead of here. _teardown resolves other ops' callbacks, and those are
3968 # promised to arrive on a clean tick -- running one nested in WebKit's frame
3969 # means a caller's EV::break lands there too, which busy-spins the NEXT
3970 # EV::run (the EV::Glib lifecycle wedge; see the on_dialog POD). Destroying
3971 # the native window/view inside that frame is the same class of hazard
3972 # _release_natives_later exists for. We got here through the loop, so the
3973 # tick is guaranteed to fire; the timer's strong $self keeps the instance
3974 # alive until it does. NOT during DESTROY: taking a strong ref to a
3975 # refcount-0 object resurrects it, and it would be freed anyway the moment
3976 # DESTROY returns, leaving the timer holding a corpse -- there we tear down
3977 # in place (nothing can still hold a callback that reaches back to $self, or
3978 # the refcount would not have hit 0).
3979 if ($IN_DISPATCH && !$self->{_destroying}) {
3980 my $t; $t = EV::timer(0, 0, sub { undef $t; $self->_teardown });
3981 return;
3982 }
3983 $self->_teardown;
3984 return;
3985 }
3986  
3987 # Resolve every outstanding async callback exactly once with 'browser closed',
3988 # so nothing a caller is awaiting is silently dropped by _defer's dead-gate,
3989 # then release the natives. wait_for waiters have their own registry (each
3990 # finisher self-dedupes -- see wait_for); every other one-shot op
3991 # (script/find/html/screenshot/pdf/cookie) is tracked in {_ops} (see _op_track)
3992 # and its wrapper likewise fires at most once. Clear each registry BEFORE firing
3993 # so a wrapper's own self-deregister -- or a re-entrant call from the user's
3994 # callback -- finds nothing to delete. Waiters first: a wait_for poll's find()
3995 # lives in {_ops} too, but its finisher has already run by the time that wrapper
3996 # fires (a no-op).
3997 sub _teardown {
3998 my $self = shift;
3999 # Collect every owed callback first, then decide HOW to deliver them.
4000 my @w = values %{ $self->{_waiters} || {} };
4001 $self->{_waiters} = {};
4002 my @ops = values %{ $self->{_ops} || {} };
4003 $self->{_ops} = {};
4004 my @owed = (@w, @ops);
4005 $self->{_pdf_queue} = []; $self->{_pdf_active} = 0; # drop un-started pdf jobs (their cbs are owed below via {_ops}); an active PrintOperation's stray completion is a _defer no-op after this
4006 $self->{_pdf_timers} = {}; # disarm every pdf watchdog (queued and active)
4007 delete $self->{_pdf_pump_timer}; # and the queue's own continuation tick (nothing left to pump)
4008 if (my $nw = delete $self->{_nav_waiters}) { # disarm every navigation waiter watchdog
4009 $_->{timer}->stop for grep { $_->{timer} } values %$nw;
4010 }
4011 if (my $p = delete $self->{pending}) { # a still-pending nav is owed an answer too (not via _defer, which now no-ops)
4012 $p->[1]->stop if $p->[1];
4013 push @owed, $p->[0] if $p->[0];
4014 }
4015 # In-flight downloads: cancel them and collect their on_finish callbacks the
4016 # same way. A download that is still running when the browser closes would
4017 # otherwise leave its caller waiting for a completion signal that can no
4018 # longer arrive -- the exact silent hang {_ops} exists to prevent. Take the
4019 # callbacks directly (not via _finish, which routes through _defer and would
4020 # be dead-gated by now) and mark each wrapper done so a late native signal
4021 # cannot deliver twice.
4022 # _flush already invokes each owed callback as ->(undef, 'browser closed'),
4023 # which is exactly on_finish's ($path, $err) signature, so the raw callback
4024 # goes straight in.
4025 delete $self->{_dl_native}; # the by-identity index; the wrappers themselves are handled just below
4026 for my $d (values %{ delete $self->{_downloads} || {} }) {
4027 eval { $d->{dl}->cancel };
4028 $d->{done} = 1; # a late native signal now finds nothing to deliver
4029 $d->_unhook; # ...and break the closure cycle, or the wrapper outlives us
4030 # Record the verdict on the wrapper too, not just in the callback we are
4031 # about to flush: a caller still holding this object can register
4032 # on_finish AFTER the close, and that late registration delivers from
4033 # {path}/{err}. Leaving them unset would report (undef, undef) -- a
4034 # successful download to nowhere, which reads as success.
4035 $d->{err} = 'browser closed';
4036 push @owed, delete $d->{on_finish} if $d->{on_finish};
4037 }
4038 # ...and requests parked by download() that never reached download-started.
4039 for my $want (values %{ delete $self->{_dl_want} || {} }) {
4040 push @owed, $want->{cb} if $want->{cb};
4041 }
4042 # Still inside a WebKit dispatch frame? Then these callbacks must not run
4043 # HERE. quit() defers the whole teardown for exactly that reason -- but it
4044 # cannot when DESTROY brought us here (a strong ref to a refcount-0 object
4045 # resurrects a corpse), so a bare drop from inside a handler lands right
4046 # here with the frame still on the stack. Release the natives in place (no
4047 # choice at refcount 0) but hand the CALLBACKS to a clean tick: delivering
4048 # them needs nothing from $self -- their answer is already decided -- so the
4049 # same file-scoped registry _defer_final uses carries them out without
4050 # holding the instance. ($IN_DISPATCH is false on quit()'s own deferred
4051 # tick, since `local` unwound with the handler, so that path still delivers
4052 # synchronously -- as it must, or `$b->quit` with no further EV::run would
4053 # never resolve anything.)
4054 if ($IN_DISPATCH) { _flush_later(\@owed) }
4055 else { _flush($_) for @owed }
4056 $self->{win}->destroy if $self->{win}; # release the native GTK window (caller owns the X display)
4057 delete @{$self}{qw/view win ucm session context chrome _user_scripts _user_styles/};
4058 return;
4059 }
4060  
4061 # Deliver owed callbacks on a clean tick, capturing ONLY the callbacks -- never
4062 # $self, so this can be used while $self is being destroyed.
4063 sub _flush_later {
4064 my $cbs = shift;
4065 my @cbs = grep { $_ } @$cbs;
4066 return unless @cbs;
4067 my $id = 'q' . ++$_final_seq;
4068 $FINAL{$id} = EV::timer(0, 0, sub { delete $FINAL{$id}; _flush($_) for @cbs });
4069 return;
4070 }
4071  
4072 # Deliver one flushed callback. EVERY invocation is guarded: a throwing user
4073 # callback must not abort the flush -- that would silently drop every sibling
4074 # callback after it AND skip the native teardown below it. {_dead} is set on
4075 # quit()'s first line, so a later quit() can never retry: an exception escaping
4076 # here used to leak the window, the WebView (with its web + network processes),
4077 # the context and the session for the rest of the process's life, and under a
4078 # bare drop (DESTROY evals quit) it did so in total silence. warn, as on_dialog
4079 # already does for the same reason -- quit() itself never throws.
4080 sub _flush {
4081 my $cb = shift;
4082 return unless $cb;
4083 return if eval { $cb->(undef, 'browser closed'); 1 };
4084 warn "EV::WebKit: callback died during quit(): $@";
4085 return;
4086 }
4087 # _destroying: tells quit() it is running on a refcount-0 object, so it must
4088 # tear down in place and never defer itself onto a timer (which would take a
4089 # fresh strong ref to a corpse -- see quit).
4090 sub DESTROY { my $self = shift; $self->{_destroying} = 1; eval { $self->quit } }
4091  
4092 {
4093 package EV::WebKit::UserContent;
4094 our $VERSION = '0.04';
4095 # Handle for one injected user script or stylesheet. Holds a WEAK ref to the
4096 # browser (so a dangling handle never keeps the instance alive) plus the id
4097 # of its native in the browser's per-kind registry. remove() is idempotent:
4098 # the shared registry is the single source of truth, so an item removed
4099 # individually OR by remove_all_user_* (which clears the registry) makes
4100 # every later remove() on it a clean no-op.
4101 sub _new {
4102 my ($class, $browser, $id, $kind) = @_;
4103 my $self = bless { id => $id, kind => $kind }, $class;
4104 Scalar::Util::weaken($self->{browser} = $browser);
4105 return $self;
4106 }
4107 sub remove {
4108 my $self = shift;
4109 my $b = $self->{browser} or return $self; # browser already collected
4110 return $self if $b->{_dead} || !$b->{ucm}; # torn down: registry gone with the ucm
4111 my $reg = $b->{"_user_$self->{kind}s"} or return $self;
4112 my $native = delete $reg->{ $self->{id} } or return $self; # already removed
4113 my $m = $self->{kind} eq 'style' ? 'remove_style_sheet' : 'remove_script';
4114 $b->{ucm}->$m($native);
4115 return $self;
4116 }
4117 }
4118  
4119 {
4120 package EV::WebKit::Dialog;
4121 our $VERSION = '0.04';
4122 # lightweight wrapper around a WebKitScriptDialog, valid only for the
4123 # duration of the script-dialog signal handler that receives it.
4124 sub _new { bless { d => $_[1] }, $_[0] }
4125 sub type { $_[0]{d}->get_dialog_type } # nick: alert/confirm/prompt/before-unload-confirm
4126 sub message { $_[0]{d}->get_message }
4127  
4128 # confirm/before-unload-confirm share the one confirm_set_confirmed setter;
4129 # alert has no setter at all (acknowledging it is just returning handled=1).
4130 sub _is_confirm { $_[0] eq 'confirm' || $_[0] eq 'before-unload-confirm' }
4131  
4132 sub accept {
4133 my ($s, $text) = @_;
4134 my $d = $s->{d};
4135 my $t = $d->get_dialog_type;
4136 if ($t eq 'prompt') { $d->prompt_set_text($text) if defined $text }
4137 elsif (_is_confirm($t)) { $d->confirm_set_confirmed(1) }
4138 $s->{answered} = 1;
4139 }
4140  
4141 sub dismiss {
4142 my $s = shift;
4143 my $d = $s->{d};
4144 my $t = $d->get_dialog_type;
4145 $d->confirm_set_confirmed(0) if _is_confirm($t);
4146 $s->{answered} = 1;
4147 }
4148 }
4149  
4150 {
4151 package EV::WebKit::FileChooser;
4152 our $VERSION = '0.04';
4153 # lightweight wrapper around a WebKitFileChooserRequest, valid only for the
4154 # duration of the run-file-chooser handler that receives it.
4155 sub _new { bless { r => $_[1] }, $_[0] }
4156  
4157 # What the <input type=file> asked for. mime_types is the accept= list (an
4158 # empty list means anything); multiple tells you whether more than one file
4159 # is allowed, so a handler can avoid offering files WebKit will discard.
4160 sub mime_types { my $m = eval { $_[0]{r}->get_mime_types }; ref $m eq 'ARRAY' ? @$m : () }
4161 sub multiple { $_[0]{r}->get_select_multiple ? 1 : 0 }
4162 sub selected { my $f = eval { $_[0]{r}->get_selected_files }; ref $f eq 'ARRAY' ? @$f : () }
4163  
4164 sub select {
4165 my ($s, @files) = @_;
4166 Carp::croak('select: at least one file path is required') unless @files;
4167 Carp::croak('select: this chooser accepts a single file only')
4168 if @files > 1 && !$s->multiple;
4169 for my $f (@files) {
4170 Carp::croak('select: file paths must be plain strings') if !defined $f || ref $f;
4171 # WebKit hands the page whatever we pass without checking, and a
4172 # missing file becomes an unreadable entry the form then submits as
4173 # empty -- fail here, where the caller can see why.
4174 Carp::croak("select: no such file: $f") unless -e $f;
4175 }
4176 $s->{r}->select_files(\@files);
4177 $s->{done} = 1;
4178 return $s;
4179 }
4180  
4181 sub cancel { $_[0]{r}->cancel; $_[0]{done} = 1; return $_[0] }
4182 }
4183  
4184 {
4185 package EV::WebKit::Auth;
4186 our $VERSION = '0.04';
4187 # A WebKitAuthenticationRequest, valid only for the duration of the
4188 # on_authenticate handler that receives it.
4189 sub _new { bless { r => $_[1] }, $_[0] }
4190  
4191 sub host { eval { $_[0]{r}->get_host } }
4192 sub port { eval { $_[0]{r}->get_port } }
4193 sub realm { eval { $_[0]{r}->get_realm } }
4194 sub scheme { eval { $_[0]{r}->get_scheme } }
4195 sub for_proxy { eval { $_[0]{r}->is_for_proxy } ? 1 : 0 }
4196 # True when the credentials just supplied were rejected. A handler that
4197 # ignores it and answers with the same pair again is a loop, since WebKit
4198 # re-asks after every rejection.
4199 sub is_retry { eval { $_[0]{r}->is_retry } ? 1 : 0 }
4200  
4201 sub login {
4202 my ($s, $user, $pass) = (shift, shift, shift);
4203 Carp::croak('login: a username and password are required')
4204 if !defined $user || ref $user || !defined $pass || ref $pass;
4205 Carp::croak('login: options must be name => value pairs') if @_ % 2;
4206 my %o = @_;
4207 my $persist = $o{persist} // 'for-session';
4208 Carp::croak("login: persist must be 'for-session', 'permanent' or 'none'")
4209 unless $persist =~ /\A(?:for-session|permanent|none)\z/;
4210 if (my @bad = sort grep { $_ ne 'persist' } keys %o) {
4211 Carp::croak("login: unknown option(s): @bad");
4212 }
4213 # The three names ARE WebKitCredentialPersistence's own nicks
4214 # (none/for-session/permanent) -- an earlier spelling of 'none' as
4215 # 'no-persistence' made every persist => 'none' call fail at the enum.
4216 my $cred = eval { WebKit::Credential->new($user, $pass, $persist) };
4217 Carp::croak('login: cannot build a credential: ' . EV::WebKit::_clean($@)) unless $cred;
4218 $s->{r}->authenticate($cred);
4219 $s->{done} = 'login'; # which way it was answered, for the failure message
4220 return $s;
4221 }
4222  
4223 sub cancel { eval { $_[0]{r}->cancel }; $_[0]{done} = 'cancel'; return $_[0] }
4224 }
4225  
4226 {
4227 package EV::WebKit::Download;
4228 our $VERSION = '0.04';
4229 # A download in progress. Unlike Dialog/FileChooser this OUTLIVES the signal
4230 # that created it: WebKit reports progress and completion later, so the
4231 # object is retained by the browser until it finishes or fails.
4232 my $SEQ = 0;
4233 sub _new {
4234 my ($class, $browser, $dl) = @_;
4235 Scalar::Util::weaken(my $b = $browser); # the browser owns us; do not own it back
4236 # `native` is the browser's {_dl_native}/{_dl_want} key -- the identity
4237 # of the WebKitDownload, which is what download() matches on (its uri
4238 # is not stable enough; see download()).
4239 return bless { b => $b, dl => $dl, native => Scalar::Util::refaddr($dl),
4240 seq => ++$SEQ, overwrite => 0 }, $class;
4241 }
4242  
4243 sub uri { eval { $_[0]{dl}->get_request->get_uri } }
4244 sub suggested { $_[0]{suggested} } # only known once decide-destination has fired
4245 sub destination { $_[0]{dest} }
4246 sub progress { eval { $_[0]{dl}->get_estimated_progress } // 0 }
4247 sub received { eval { $_[0]{dl}->get_received_data_length } // 0 }
4248  
4249 # Choose where this download lands. Called from on_download; without it the
4250 # download is cancelled rather than written to WebKit's default directory.
4251 # Shared with EV::WebKit::download, so a destination that this would reject
4252 # is rejected THERE -- synchronously, at the caller's own call site -- rather
4253 # than later, from inside the download-started signal handler where a croak
4254 # escapes into GLib and takes the caller's callback (and, measured, the
4255 # process) with it. $what names the caller for the message.
4256 sub _norm_dest {
4257 my ($path, $what) = @_;
4258 Carp::croak("$what: a destination path is required")
4259 if !defined $path || ref $path || !length $path;
4260 return _abs_dest($path) unless $path =~ /^file:/i;
4261 my $shown = $path;
4262 $path =~ s{^file://}{}i
4263 or Carp::croak("$what: not a local file:// URI: $shown");
4264 $path =~ s{^localhost(?=/)}{}i; # hostnames are case-insensitive, and the scheme above is stripped /i
4265 Carp::croak("$what: not a local file:// URI: $shown") unless $path =~ m{^/};
4266 $path =~ s/%([0-9A-Fa-f]{2})/chr hex $1/ge;
4267 # %00 decodes to a NUL, which no filesystem accepts and which C -- on the
4268 # other side of the GI call -- reads as end-of-string: 'file:///tmp/a%00b'
4269 # would have written /tmp/a and reported success for a path the caller
4270 # never asked for. Say so instead.
4271 Carp::croak("$what: the decoded path contains a NUL byte: $shown")
4272 if index($path, "\0") >= 0;
4273 return _abs_dest($path);
4274 }
4275  
4276 # ABSOLUTE, always. webkit_download_set_destination has a
4277 # g_path_is_absolute precondition: handed a relative path it emits only a
4278 # C-level CRITICAL, sets NOTHING, and -- because decide-destination has
4279 # already answered "handled" -- WebKit then waits forever for a destination
4280 # that never arrives. download() is deliberately exempt from the per-op
4281 # timeout, so nothing bounds that: the callback never fires at all until
4282 # quit() flushes it as 'browser closed'. Measured, on both download() and
4283 # save_to(). pdf() resolves its own path the same way, for its own reasons.
4284 sub _abs_dest { File::Spec::Functions::rel2abs($_[0]) } # qualified: the import is in EV::WebKit, not this inner package
4285  
4286 sub save_to {
4287 my ($s, $path) = (shift, shift);
4288 Carp::croak('save_to: options must be name => value pairs') if @_ % 2;
4289 my %o = @_;
4290 if (my @bad = sort grep { $_ ne 'overwrite' } keys %o) {
4291 Carp::croak("save_to: unknown option(s): @bad (expected overwrite)");
4292 }
4293 # A PLAIN FILESYSTEM PATH, never a file:// URI. WebKitGTK 6.0 changed
4294 # webkit_download_set_destination to take a path (2.x took a URI), and
4295 # handing it a URI does not fail -- the download simply stalls forever,
4296 # emitting neither 'finished' nor 'failed', so the caller waits on a
4297 # callback that can never arrive. Accept a file:// URI from the caller
4298 # and strip it, rather than passing that trap along. Strip it PROPERLY,
4299 # though: taking the prefix off and stopping there left the rest still
4300 # URI-encoded, so 'file:///tmp/a%20b' wrote a file literally named
4301 # 'a%20b', and 'file://localhost/x' became the relative path
4302 # 'localhost/x'. Decode the escapes, accept the empty and 'localhost'
4303 # authorities (both mean this machine), and refuse any other host --
4304 # which names a file we cannot write and would otherwise become a
4305 # nonsense relative path.
4306 $path = _norm_dest($path, 'save_to');
4307 $s->{dest} = $path;
4308 $s->{overwrite} = $o{overwrite} ? 1 : 0;
4309 return $s;
4310 }
4311  
4312 sub on_finish {
4313 my ($s, $cb) = @_;
4314 Carp::croak('on_finish: expected a code reference') if defined $cb && ref $cb ne 'CODE';
4315 $s->{on_finish} = $cb;
4316 # A download that already finished (or failed) before the caller got
4317 # round to registering must still deliver, or the callback is lost.
4318 $s->_deliver if $s->{done};
4319 return $s;
4320 }
4321  
4322 sub cancel { eval { $_[0]{dl}->cancel }; return $_[0] }
4323  
4324 # Called at most once per download; later duplicate signals are ignored so a
4325 # cancel's error is not overwritten by the 'finished' that follows it.
4326 sub _finish {
4327 my ($s, $path, $err) = @_;
4328 return if $s->{done};
4329 $s->{done} = 1;
4330 $s->{path} = $path; # already a plain path -- see save_to
4331 $s->{err} = $err;
4332 $s->_deliver;
4333 # Release the browser's retention of this wrapper; the callback above
4334 # has already been handed everything it needs.
4335 my $b = $s->{b};
4336 if ($b) {
4337 delete $b->{_downloads}{ $s->{seq} };
4338 delete $b->{_dl_native}{ $s->{native} };
4339 }
4340 $s->_unhook;
4341 return;
4342 }
4343  
4344 # Drop the native's references to our three signal closures. Each of them
4345 # captures $s, and $s holds the native as {dl}: a cycle refcounting cannot
4346 # collect, so every completed download used to keep both alive until the
4347 # process exited (measured: 3 of 3 wrappers still reachable after finishing).
4348 # Disconnecting from inside one of those handlers' own emission is
4349 # supported by GLib -- the handler is marked and removed after it returns.
4350 # The accessors stay usable afterwards: {dl} is untouched, only the
4351 # subscriptions go.
4352 sub _unhook {
4353 my $s = shift;
4354 my $ids = delete $s->{sig} or return;
4355 my $dl = $s->{dl} or return;
4356 eval { $dl->signal_handler_disconnect($_) } for @$ids;
4357 return;
4358 }
4359  
4360 sub _deliver {
4361 my ($s) = @_;
4362 my $cb = delete $s->{on_finish} or return;
4363 my $b = $s->{b};
4364 my ($path, $err) = ($s->{path}, $s->{err});
4365 # Deferred like every other callback: _finish runs inside WebKit's own
4366 # signal dispatch, and calling user code (which may call EV::break) from
4367 # there is the documented lifecycle wedge.
4368 #
4369 # _defer is dead-gated, so it silently swallows anything delivered after
4370 # quit(). That is right for an op still in flight (quit already flushed
4371 # its callback) but WRONG here: a caller holding this object can call
4372 # on_finish AFTER the browser closed -- teardown marked us done, so we
4373 # land straight in this branch -- and the answer simply vanished. Use
4374 # the un-gated final registry once the browser is dead, which is the
4375 # same route every other post-quit call takes to report 'browser
4376 # closed'.
4377 #
4378 # _op_track before _defer, so the deferral is not the ONLY thing holding
4379 # this answer. _finish drops the wrapper from {_downloads} the moment it
4380 # runs, and quit() cancels every pending _defer timer -- so a quit()
4381 # landing in the window between them found nothing owed in either place
4382 # and the callback vanished (reproduced: quit() from a watcher in the
4383 # same loop iteration as 'finished'). Every other async op here is
4384 # already tracked for exactly this reason; downloads were not.
4385 # _flush delivers as ->(undef, 'browser closed'), which is on_finish's
4386 # own ($path, $err) shape, and the tracker's dedupe means whichever of
4387 # the two arrives first is the only one the caller sees.
4388 if ($b && !$b->{_dead}) { $b->_defer($b->_op_track($cb), $path, $err) }
4389 elsif ($b) { $b->_defer_final($cb, $path, $err) }
4390 else { eval { $cb->($path, $err); 1 } or warn "EV::WebKit: download on_finish died: $@" }
4391 return;
4392 }
4393 }
4394  
4395 {
4396 package EV::WebKit::Policy;
4397 our $VERSION = '0.04';
4398 # lightweight wrapper around a WebKit(Navigation|Response)PolicyDecision,
4399 # valid only for the duration of the decide-policy signal handler that
4400 # receives it.
4401 sub _new { bless { d => $_[1], type => $_[2], uri => $_[3] }, $_[0] }
4402 sub uri { $_[0]{uri} } # nav/new-window: request URI; response: request URI
4403 sub type { $_[0]{type} } # nick: navigation-action/new-window-action/response
4404 sub allow { $_[0]{d}->use; $_[0]{done} = 1 }
4405 sub block { $_[0]{d}->ignore; $_[0]{done} = 1 }
4406 }
4407  
4408 1;
4409  
4410 =pod
4411  
4412 =head1 NAME
4413  
4414 EV::WebKit - async WebKitGTK 6.0 (GTK4) browser automation on EV
4415  
4416 =head1 SYNOPSIS
4417  
4418 use EV;
4419 use EV::WebKit;
4420  
4421 # run under `xvfb-run -a perl script.pl` for a headless display,
4422 # or with a real $DISPLAY for a visible, interactive window.
4423  
4424 die "WebKitGTK 6.0 / GTK4 typelibs not available\n"
4425 unless EV::WebKit->available;
4426  
4427 my $b = EV::WebKit->new(
4428 window => [1024, 768],
4429 on_console => sub { warn "console: $_[0]\n" },
4430 on_error => sub { warn "error: $_[0]\n" },
4431 );
4432  
4433 $b->go('https://example.com', sub {
4434 my (undef, $err) = @_;
4435 # A die inside an EV callback goes to $EV::DIED, which by default only
4436 # warns -- so report and break, or the loop keeps spinning.
4437 if ($err) { warn "navigation failed: $err\n"; return EV::break }
4438  
4439 $b->find('h1', sub {
4440 my ($el, $err) = @_;
4441 if ($err) { warn "find failed: $err\n"; return EV::break }
4442 $el->text(sub { print "H1: $_[0]\n" }) if $el;
4443 });
4444  
4445 $b->wait_for('#maybe-async', timeout => 5, sub {
4446 my ($el, $err) = @_; # $err eq 'timeout' just means it never showed up
4447  
4448 $b->screenshot('shot.png', sub {
4449 my (undef, $err) = @_;
4450 warn "screenshot failed: $err\n" if $err;
4451 # quit() resolves anything STILL in flight with 'browser
4452 # closed' -- so only quit once you have the results you want.
4453 $b->quit;
4454 EV::break;
4455 });
4456 });
4457 });
4458  
4459 EV::run;
4460  
4461 Pass C<< chrome => 1 >> to C<new> and export a real C<$DISPLAY> (instead of
4462 C<xvfb-run>) for a visible, interactive window with basic back/forward/reload
4463 chrome; every method above keeps working unchanged.
4464  
4465 =head1 DESCRIPTION
4466  
4467 EV::WebKit drives a real, in-process WebKitGTK 6.0 web view for browser
4468 automation: navigation, DOM queries and manipulation, JavaScript execution,
4469 screenshots, PDF export, cookies, and basic network control. It is pure
4470 Perl over GObject Introspection -- no XS, and the only thing compiled at
4471 install is one small optional extension (see L</"REQUIREMENTS">) -- and
4472 integrates WebKitGTK's GLib main loop into L<EV> via
4473 L<EV::Glib>, so it composes with other EV-based code in the same process.
4474  
4475 DOM access works by injecting JavaScript through WebKit's
4476 C<call_async_javascript_function> and JSON-marshalling the result back into
4477 Perl data; elements found via C<find>/C<find_all> are returned as
4478 lightweight L<EV::WebKit::Element> handles (a page-side registry id plus a
4479 back-reference to the browser), not live DOM references held on the Perl
4480 side -- see L<EV::WebKit::Element>.
4481  
4482 EV::WebKit does not manage a display of its own; see L</"LIMITATIONS">.
4483  
4484 =head1 CALLBACK CONVENTION
4485  
4486 EV::WebKit is entirely single-threaded and cooperative: every operation
4487 that talks to the web view is asynchronous and runs on the ambient L<EV>
4488 loop. The caller starts and stops that loop (C<EV::run>, C<EV::break>) --
4489 no EV::WebKit method ever calls either for you. Methods that need to wait
4490 for a result take a trailing callback:
4491  
4492 sub { my ($result, $err) = @_; ... }
4493  
4494 On success, C<$err> is C<undef> and C<$result> holds the method's result
4495 (shape documented per method below). On failure, C<$result> is C<undef>
4496 and C<$err> is a short, human-readable string -- Perl's own " at FILE line
4497 N." diagnostic suffix is stripped where it would otherwise appear -- such
4498 as C<timeout>, C<browser closed>, or a cleaned JavaScript exception
4499 message. Methods never throw for ordinary runtime failures; always check
4500 C<$err>. Some methods are plain synchronous accessors/mutators and take no callback at
4501 all: the state readers (C<uri>, C<title>, C<is_loading>, C<status>,
4502 C<can_go_back>, C<can_go_forward>), C<stop>, the configuration setters
4503 (C<settings>, C<set_user_agent>/C<user_agent>, C<set_proxy>, C<zoom>,
4504 C<show_devtools>, C<mock_scheme>), the user-content methods
4505 (C<add_user_script>/C<add_user_style> and their removes), the fingerprint
4506 accessors, and C<quit>. Where it is not obvious from the usage line, the
4507 method's own entry says so.
4508  
4509 C<EV::break> is safe to call directly from the trailing C<($result, $err)>
4510 callbacks described above, and from C<on_load>, C<on_error>, C<on_close> and
4511 C<on_navigate>, since all of those run on a clean EV tick. So do C<on_request>
4512 and C<on_response>, which run in the proxy rather than in WebKit at all. C<on_console>, C<on_dialog>, C<on_policy>,
4513 C<on_file_chooser>, C<on_download>, C<on_authenticate> and a C<mock_scheme>
4514 producer, however, all
4515 fire synchronously inside WebKit's own dispatch frame -- do NOT call
4516 C<EV::break> directly from those; schedule it instead, e.g.
4517 C<< EV::timer(0, 0, sub { EV::break }) >>. (Calling C<quit> from them B<is>
4518 safe: it detects the frame and defers its own teardown.)
4519  
4520 =head1 CONSTRUCTOR
4521  
4522 =head2 available
4523  
4524 my $ok = EV::WebKit->available;
4525  
4526 Returns true if the required WebKit-6.0/Gtk-4.0/Gdk-4.0/JavaScriptCore-6.0
4527 and Soup-3.0 GObject-Introspection typelibs can be loaded, false
4528 otherwise. Safe to call before C<new> to fail gracefully (e.g. to C<plan
4529 skip_all> a test) instead
4530 of letting C<new> die. Checking typelib availability does not require a
4531 display.
4532  
4533 =head2 new
4534  
4535 my $b = EV::WebKit->new(%options);
4536  
4537 Constructs a new browser: sets up (once per process) the GObject
4538 Introspection typelibs, initializes GTK4 (only once a display is known --
4539 see L</"LIMITATIONS">), creates a WebKit network session, user content
4540 manager, web context and view, and shows a native GTK4 window containing
4541 it. Dies if the typelibs are unavailable or if no X display can be
4542 determined (see C<display> below). C<%options>:
4543  
4544 =over 4
4545  
4546 =item C<< window => [$width, $height] >>
4547  
4548 Initial window size in pixels. Default C<[1280, 1024]>.
4549  
4550 A C<fingerprint> profile overrides this where the two would contradict each
4551 other, since a window larger than the screen it claims to be on is itself a
4552 tell: a mobile profile sizes the window to the profile's own screen and ignores
4553 C<window> outright, and a desktop profile caps each dimension at its screen's.
4554  
4555 =item C<< display => ':N' >>
4556  
4557 Sets C<$ENV{DISPLAY}> to this value before initializing GTK. If omitted, an
4558 already-exported C<$DISPLAY> is used; if neither is available, C<new> dies
4559 telling you to run under C<xvfb-run> or pass this option -- EV::WebKit
4560 never starts an X server itself (see L</"LIMITATIONS">).
4561  
4562 B<One display per process.> GTK connects to a display once and cannot be
4563 moved to another, so every instance after the first shares the first one's
4564 display. Passing a C<display> that disagrees with it croaks rather than
4565 being silently ignored.
4566  
4567 =item C<< timeout => $seconds >>
4568  
4569 Default per-operation timeout, in seconds. Applies to every async operation
4570 that can block -- navigation (C<go>/C<load_html>/C<back>/C<forward>/
4571 C<reload>), C<script>/C<script_async>, C<find>/C<find_all>/C<find_js>/
4572 C<find_all_js> and the L<EV::WebKit::Element> accessors, C<frames> and
4573 everything routed through a frame, C<resize>, C<html>, C<screenshot>, C<pdf>,
4574 and the cookie operations
4575 (C<set_cookie>/C<cookies>/C<clear_cookies>/C<save_cookies>/C<load_cookies>) --
4576 and is the default for C<wait_for>'s and C<pdf>'s own C<timeout> option, and C<wait_for_navigation>'s. On expiry the operation's
4577 callback is resolved with C<$err eq 'timeout'>. Default C<30>.
4578  
4579 C<download> is the deliberate exception: a large file legitimately takes longer
4580 than any per-operation timeout would allow, so a download is bounded only by
4581 the server and by C<quit>. Use C<< $dl->cancel >> to end one early.
4582  
4583 =item C<< popups => 'follow' | 'block' >>
4584  
4585 What to do with a navigation that asks for a new window. Documented in full
4586 under L</EVENTS>, with the rest of the options that shape how the browser
4587 reacts to the page.
4588  
4589 =item C<< user_agent => $string >>
4590  
4591 Sets the initial User-Agent (equivalent to calling C<set_user_agent> right
4592 after construction).
4593  
4594 =item C<< ephemeral => $bool >>
4595  
4596 Use an ephemeral (in-memory, non-persistent) network session when true, or
4597 an on-disk/persistent one when false. Default C<1>. Forced to C<0>
4598 automatically when C<cookie_jar> is given -- native cookie persistence
4599 requires a non-ephemeral session (see C<cookie_jar> below).
4600  
4601 =item C<< devtools => 1 >>
4602  
4603 Enables the C<enable-developer-extras> setting at construction time
4604 (required before the Web Inspector will do anything useful; see
4605 C<show_devtools>).
4606  
4607 =item C<< title => $string >>
4608  
4609 Sets the native GTK4 window's title.
4610  
4611 =item C<< chrome => 1 >>
4612  
4613 Build a minimal browser chrome: a GNOME header bar with back, forward and
4614 reload buttons and an address entry, installed as the window title bar.
4615 Intended for visible use on a real display; harmless under xvfb-run. The
4616 reload button turns into a stop button while a page is loading. The address
4617 entry navigates on Enter (https:// is assumed when no scheme is given) and
4618 tracks the current page uri except while it has keyboard focus. The window
4619 title follows the page title. Automation methods keep working unchanged.
4620  
4621 =item C<< cookie_jar => $path >>
4622  
4623 Configures C<$path> as this instance's native, WebKit-managed persistent
4624 cookie store (forces a non-ephemeral session -- see C<ephemeral> above).
4625 Cookies with a real expiry (a C<max_age> greater than C<0>, or a
4626 C<Set-Cookie: ...; Max-Age=>/C<Expires=> response header) are written to
4627 C<$path> automatically and read back automatically by any later instance
4628 pointed at the same file -- no C<save_cookies>/C<load_cookies> call needed.
4629 SESSION cookies (no expiry) are I<excluded> from this store by design (RFC
4630 6265, same as every real browser); use C<save_cookies>/C<load_cookies> to
4631 snapshot those. See L</"Cookie Management"> and L</"LIMITATIONS">.
4632 Do not point save_cookies/load_cookies at the same file as cookie_jar: the
4633 native store and the JSON snapshot are different formats written by
4634 independent writers, and sharing a path will corrupt the file.
4635  
4636 =item C<< jar_format => 'sqlite' | 'text' >>
4637  
4638 Storage format for the persistent cookie store. C<sqlite> (default) is
4639 queryable with C<sqlite3>; C<text> is a human-readable Netscape-format cookie
4640 file. It applies to whichever store exists: C<cookie_jar>'s file if you gave
4641 one, otherwise C<data_dir>'s own (C<cookies.txt> under C<text>, rather than
4642 C<cookies.sqlite>). Ignored only when neither option is given.
4643  
4644 =item C<< data_dir => $path >>
4645  
4646 Points this instance's entire session -- cookies, C<localStorage>,
4647 C<IndexedDB>, the HTTP cache, service-worker state -- at C<$path>, and restores
4648 it whenever an instance is later built with the same C<$path>. Two instances
4649 with different C<data_dir>s share nothing. Forces a non-ephemeral session (see
4650 C<ephemeral> above); C<< data_dir => ..., ephemeral => 1 >> croaks.
4651  
4652 C<data_dir> persists what C<cookie_jar> does B<and more>: C<localStorage>,
4653 C<IndexedDB>, the cache and service-worker state, none of which C<cookie_jar>
4654 touches. Cookies persist under the same rule as C<cookie_jar> -- those with a
4655 real expiry -- written to a C<< $data_dir/cookies.sqlite >>, or
4656 C<cookies.txt> under C<< jar_format => 'text' >> (see L</"LIMITATIONS">), and
4657 only when C<cookie_jar> was not given as well.
4658 Two things are B<never> written to disk: session cookies
4659 (no expiry -- RFC 6265, use C<save_cookies>/C<load_cookies> to snapshot those)
4660 and C<sessionStorage> (WebKit treats it as inherently per-session).
4661  
4662 C<data_dir> and C<cookie_jar> compose, but not additively for cookies: there is
4663 one cookie store, and C<cookie_jar> B<replaces> the one C<data_dir> would have
4664 used rather than adding to it. Everything else -- C<localStorage>,
4665 C<IndexedDB>, the cache, service workers -- still goes under C<data_dir>. So a
4666 session saved with both and later reopened with C<data_dir> alone finds no
4667 cookies: keep passing C<cookie_jar> if you passed it once. A relative C<$path>
4668 is resolved against
4669 the current directory at construction time. C<$path> (and any missing parent
4670 directories) is created for you; an empty string, a path that is already a
4671 non-directory file, or a path with no writable ancestor croaks from C<new>
4672 rather than failing later.
4673  
4674 Do not point C<save_cookies>/C<load_cookies> at C<data_dir>'s own cookie file
4675 (C<< $path/cookies.sqlite >>, or C<cookies.txt>), for the same reason as
4676 C<cookie_jar>: they are
4677 different formats written by independent writers. And note C<load_cookies>
4678 replaces any cookie with the same name/domain/path -- since a loaded cookie
4679 comes back as a session cookie (no expiry survives a snapshot), loading a
4680 snapshot into a C<data_dir> instance can B<downgrade> an already-persisted
4681 cookie of that identity, dropping it from the store on the next C<quit>.
4682  
4683 B<One live instance per C<data_dir> at a time.> WebKit's C<localStorage> and
4684 C<IndexedDB> databases are not built for concurrent writers, so two live
4685 instances pointed at the same C<data_dir> in one process can corrupt them --
4686 the same caution as not sharing a file between C<cookie_jar> and
4687 C<save_cookies>.
4688  
4689 =item C<< cache_dir => $path >>
4690  
4691 Overrides where C<data_dir>'s disposable cache is written (default:
4692 C<< $data_dir/cache >>). Useful for putting the regenerable cache on C<tmpfs>,
4693 or keeping a backed-up C<data_dir> free of it. A relative C<cache_dir> is
4694 resolved against the current directory (like C<data_dir>), B<not> nested inside
4695 C<data_dir>. Ignored -- and a croak -- unless C<data_dir> is given, since a
4696 cache dir with no data dir would leak cache to WebKit's shared location and
4697 defeat the isolation.
4698  
4699 =item C<< proxy => $uri >> or C<< proxy => { default => $uri, ignore => [@hosts] } >>
4700  
4701 Equivalent to calling C<set_proxy> right after construction (see
4702 L</"Network">). An invalid proxy URI croaks out of the constructor itself,
4703 same as calling C<set_proxy> directly.
4704  
4705 =item C<< fingerprint => 'windows-chrome' >> or C<< fingerprint => { profile => 'windows-chrome', ... } >>
4706  
4707 Present this instance as a coherent real device at the JavaScript layer, using
4708 NATIVE property getters (installed by a bundled web-process extension) that
4709 report C<[native code]> and so defeat the C<toString> detection a pure-JS
4710 override cannot. A preset name selects a shipped profile; a hashref takes a
4711 preset as its C<profile> base and overrides individual fields. Construct-time
4712 only (the device cannot change mid-session). Passing both C<fingerprint> and
4713 C<user_agent> croaks -- the profile sets the UA; override it via
4714 C<< fingerprint => { ..., user_agent => ... } >>.
4715  
4716 Requires the web-process extension, compiled at install if C<cc> + glib/gobject
4717 are present; check L</fingerprint_available>. Note: if the extension is present
4718 but fails to load inside the web process (an arch/symbol mismatch), the profile's
4719 User-Agent is still applied while the JS-property spoof is not -- an incoherent
4720 state the module cannot detect from the UI process. B<Coverage:> C<navigator>
4721 (platform, vendor, languages, hardwareConcurrency, deviceMemory, maxTouchPoints,
4722 and for a Gecko profile productSub, oscpu and buildID), C<screen>,
4723 C<devicePixelRatio>, C<window.mozInnerScreenX>/C<Y>, and the WebGL GPU
4724 vendor/renderer strings. The
4725 navigator/screen getters are installed natively, on the prototype and
4726 enumerable, so they read as the engine's own to everything except
4727 C<Function.prototype.toString> -- see the Ceiling below, which is where the
4728 remaining tells are enumerated honestly.
4729  
4730 C<windows-firefox> asks more of this than the others. The engine really is
4731 WebKit, so a Safari profile is a small lie and a Chrome one a larger one, but
4732 claiming Gecko means supplying a surface no WebKit build has: C<productSub>
4733 (Gecko reports C<20100101> where WebKit and Chromium report C<20030107>),
4734 C<oscpu> and C<buildID>, which exist in no other engine and whose ABSENCE
4735 identifies the engine as surely as a wrong value, and
4736 C<window.mozInnerScreenX>/C<Y>. Those are supplied. What is not, and cannot be
4737 without the engine, is CSS: C<CSS.supports('-moz-appearance', 'none')> is false
4738 here and true in Firefox, and no property override fixes that without breaking
4739 the styling it claims to support. Use C<windows-firefox> for the network-layer
4740 identity -- where it is exact -- and expect a determined JS-layer engine probe
4741 to see through it.
4742  
4743 A B<coherence layer> fills the gaps a bare navigator/screen spoof would leave: a
4744 Chrome profile also gets C<window.chrome> and a working C<navigator.userAgentData>
4745 (brands/platform plus an async C<getHighEntropyValues>); a mobile profile sizes
4746 the window to the profile's screen (so C<window.innerWidth E<lt>= screen.width>),
4747 adds C<ontouchstart>, and overrides the C<pointer>/C<hover>/C<resolution> media
4748 queries. Unlike the native navigator/screen getters, this layer -- and the WebGL
4749 C<getParameter> override -- is installed as JS (a native replacement cannot
4750 delegate the non-spoofed cases: a JSC C function receives no C<this>). The values
4751 are correct and consistent, but their getters/methods show JS source under a
4752 C<Function.prototype.toString.call> (or a getter-C<toString>) check, so a
4753 determined script can still detect the C<userAgentData>/C<matchMedia>/WebGL
4754 wrappers.
4755  
4756 WebGL spoofs the full per-profile B<capability set>, not only the UNMASKED
4757 vendor/renderer strings: the numeric parameters (C<MAX_TEXTURE_SIZE> and friends),
4758 the supported-extension list, and C<getShaderPrecisionFormat> all return the
4759 claimed GPU family's values on both WebGL1 and WebGL2, coherent with the renderer
4760 string. The advertised list is authoritative: C<getExtension> returns C<undef> for
4761 anything not on it, the real object when the host GL genuinely has it, and
4762 otherwise a minimal stub (carrying that extension's constants for the commonly
4763 probed ones, an empty object for the rest -- see the B<Ceiling> notes below).
4764 Extension names are
4765 matched case-insensitively, as the spec requires, and an extension's own pnames
4766 (the UNMASKED pair, C<MAX_TEXTURE_MAX_ANISOTROPY_EXT>) are answered only once
4767 C<getExtension> has enabled that extension on the context -- before that they
4768 report C<null> and raise C<INVALID_ENUM>, exactly as a real context does.
4769  
4770 The capability tables are a curated subset covering the parameters fingerprinters
4771 actually read; a pname not in the table falls through to the real host value.
4772  
4773 The B<DOM interface set> is aligned per profile too: a Chrome profile exposes
4774 C<navigator.connection>, C<usb>, C<bluetooth>, C<getBattery>, C<scheduling> and
4775 C<RTCPeerConnection> (the Android profile correctly omits C<hid>/C<serial>); a
4776 Safari profile exposes only C<storage> and C<RTCPeerConnection>. Every stub is
4777 installed only when the build lacks the real API, so a WebKitGTK that ships one
4778 keeps it.
4779  
4780 B<PDF viewer presence> follows the profile as well. The HTML specification
4781 hardcodes both states: a browser that displays PDFs inline reports
4782 C<navigator.pdfViewerEnabled> true and five fixed plugin names, one that does
4783 not reports false and B<empty> C<plugins>/C<mimeTypes> lists. WebKitGTK reports
4784 the viewer-present state, which is correct for desktop Chrome, desktop Safari
4785 and iOS Safari -- but B<not> for C<pixel-chrome>: Chrome for Android had no
4786 inline PDF viewer at 131 (it shipped 2024-11, the Android viewer appeared behind
4787 a flag in 2024-12 and became default-on only in Chrome 135, 2025-04), so that
4788 profile reports the empty state. Override per instance with
4789 C<< pdf_viewer => 0|1 >>. The empty lists are real C<PluginArray>/
4790 C<MimeTypeArray> objects, cached like a real browser's, with C<length> left on
4791 the prototype where it belongs.
4792  
4793 B<Ceiling:> the spoof is thorough but not perfect, and these residuals remain.
4794 B<Workers are not covered at all.> The extension hooks
4795 C<window-object-cleared>, which fires only for window globals, so a
4796 C<Worker>/C<SharedWorker>/C<ServiceWorker> global keeps the real
4797 C<navigator.platform>, C<languages> and hardware values and gets no readback
4798 noise -- while its C<userAgent> B<is> spoofed (that comes from the browser
4799 settings, not this extension). Reading C<navigator.platform> on both sides of a
4800 C<postMessage>, or hashing an C<OffscreenCanvas> inside a worker, defeats the
4801 whole layer; treat a page that uses workers as unprotected.
4802 The native navigator/screen getters are also still identifiable by the source
4803 B<text> C<Function.prototype.toString> reports for them: a real accessor renders
4804 as C<function E<lt>propE<gt>() { [native code] }> while these render as
4805 C<function get() { [native code] }>. The name and C<[native code]> marker are
4806 correct, but the embedded identifier is not, and it cannot be corrected without
4807 replacing the getter with JavaScript -- which costs far more than it saves.
4808 The JS-installed layers (C<userAgentData>/C<matchMedia>/WebGL/readback/feature
4809 stubs) show JS source under C<Function.prototype.toString.call> B<and> under a
4810 plain C<toString()>, so a determined script can still detect them. They
4811 deliberately carry no own C<toString> mask: such a mask defeats only the plain
4812 check -- C<Function.prototype.toString.call> bypasses an own property and reveals
4813 the wrapper anyway -- while leaving an artifact no real function has, which
4814 C<Object.keys> enumerates across the whole JS layer with no false positives.
4815 Trading a weak defence for a precise tell is a bad exchange, so the wrappers are
4816 left honest. Readback
4817 noise, when C<seed> is set, is content-independent, so a script that renders a
4818 known image and reads it back can recover and undo it. It is also applied at
4819 B<read> time rather than stored, so it does not survive a round trip: writing
4820 back what was just read (C<putImageData>), or encoding and re-decoding through
4821 C<toDataURL>/C<toBlob>, yields the un-noised pixels, and comparing the two
4822 detects that noise is active without knowing the content. B<Without> C<seed>,
4823 canvas/AudioContext/WebGL-pixel readback reflects the real host output (often
4824 software/llvmpipe) and is not disguised at all. The C<matchMedia> override
4825 answers JS queries (including compound and comma-separated ones), but B<CSS>
4826 C<@media> rules are evaluated by the engine and still reflect the real device, so
4827 a page that compares C<getComputedStyle> against C<matchMedia> sees a
4828 contradiction on a mobile or hi-DPI profile. The WebGL capability values are
4829 the canonical set for each GPU family, so a fingerprinter with a per-driver
4830 database could still find a mismatch, and any pname outside the curated tables
4831 still reports the host's real value. Stubbed extensions and C<RTCPeerConnection>
4832 have no real runtime behaviour (no ICE, no devices), so a script that exercises
4833 their functionality -- rather than merely detecting their presence -- can spot
4834 the stub; an advertised extension the host GL lacks is an object with the right
4835 constants but no working methods. C<navigator.languages> is a real array with
4836 the profile's tags, but B<not> a C<FrozenArray>: a real browser caches one
4837 frozen array and returns it every time, so C<navigator.languages ===
4838 navigator.languages> and C<Object.isFrozen(navigator.languages)> are both true
4839 there and false here. Closing that was built and then reverted -- caching one
4840 frozen array per JS context works, but a C<JSCValue> holds a strong reference to
4841 its C<JSCContext>, making cache/array/context a refcount cycle whose destroy
4842 notify never runs, which leaks an entire JS context per navigation; and
4843 anchoring the array on the JavaScript side instead would turn C<languages> into
4844 a B<data> property where every real browser has an accessor, a louder tell than
4845 the one being fixed. Encoding a large canvas through C<toDataURL>
4846 is markedly slower with C<seed> set, which is itself weakly timeable. And this is the JS layer only -- the
4847 network-layer fingerprint (TLS JA3/JA4, HTTP/2) is untouched unless you also
4848 enable C<network_fingerprint> (below). A self-consistent B<custom> profile is
4849 your responsibility.
4850  
4851 =item C<< fonts => \@dirs >>, C<< fonts => \%spec >> or C<< fonts => $conf_file >>
4852  
4853 Replace the font set the engine can see. The installed fonts are a platform
4854 tell in their own right, independent of anything C<fingerprint> spoofs: a
4855 profile claiming Windows on a box whose only sans-serif faces are DejaVu and
4856 Noto is answering "Linux" to anything that measures text.
4857  
4858 Three spellings, cheapest first:
4859  
4860 fonts => [ '/srv/fonts/win' ] # only these directories
4861  
4862 fonts => { dirs => [ '/srv/fonts/win' ],
4863 sans_serif => 'Arial',
4864 serif => 'Times New Roman',
4865 monospace => 'Courier New' } # ...and what the generics mean
4866  
4867 fonts => '/srv/fonts/win.conf' # your own fontconfig file
4868  
4869 The directory forms write a fontconfig file naming exactly those directories
4870 and nothing else, so the host's fonts are B<not> visible -- this changes what
4871 the engine B<has>, rather than lying about it in JavaScript, which is why it
4872 survives being measured rather than merely asked.
4873  
4874 Give the generic families if you can. Without them all three resolve to
4875 whichever face matches first, so C<sans-serif>, C<serif> and C<monospace>
4876 measure identically -- wrong on the page, and a fingerprint of its own. The
4877 system rules that normally supply them cannot be reused: F</etc/fonts/conf.d>
4878 carries C<< <dir> >> entries, and including it would put the host's fonts
4879 straight back.
4880  
4881 The file form is passed to fontconfig untouched; every absolute C<< <dir> >>
4882 and C<< <cachedir> >> in it that exists is made visible to the web process.
4883  
4884 Two things to know. The web process runs inside a sandbox, so the config and
4885 every directory it names are bound into it explicitly -- pointing
4886 C<FONTCONFIG_FILE> at a font set without that does nothing at all, silently.
4887 And fontconfig is configured per B<process>, not per view: this sets an
4888 environment variable read once by each web process as it starts, so one font
4889 set per program, not one per browser.
4890  
4891 What it cannot do is give you fonts you do not have. Metric-compatible
4892 substitutes exist for a few faces (Liberation for Arial, Times New Roman and
4893 Courier New; Carlito and Caladea for Calibri and Cambria), but the ones that
4894 identify an OS -- Segoe UI, SF Pro -- have none, so a page that measures those
4895 by name still sees a fallback. This narrows the gap; it does not close it.
4896  
4897 =item C<< seed => 12345 >>
4898  
4899 Enable seeded B<readback noise> on canvas, C<AudioContext>, and WebGL pixel
4900 readback (opt-in; requires C<fingerprint>). The seed is a non-negative integer.
4901 The perturbation is a content-independent function of the seed and the readback
4902 position -- absolute canvas or drawing-buffer coordinates for pixels, the frame
4903 index for audio samples -- so the same sample re-read through any API, rectangle
4904 or offset gives the same value. A fully opaque pixel gets an LSB flip. A
4905 partially transparent one is moved to an B<adjacent reachable value> instead:
4906 C<getImageData> returns un-premultiplied bytes, so only a lattice of values is
4907 producible at a given alpha and an LSB flip would land off it (the step is
4908 therefore larger than one LSB at low alpha). WebGL C<readPixels> returns the
4909 premultiplied value directly, so there the step is applied to that value. Only
4910 engine-B<rendered> audio buffers are touched, never one the page authored. The
4911 seed is reduced modulo 2**32, so seeds congruent mod 2**32 give identical noise.
4912 That makes the hardware-readback hash B<stable> within a session, yet
4913 different from the automation host's real output (hiding llvmpipe/software GL)
4914 and different across seeds -- so the same profile can present distinct machines.
4915 Wrapped: C<getImageData>, C<toDataURL>/C<toBlob> (via an offscreen copy, so the
4916 encoded image carries the noise and WebGL-backed canvases are covered too),
4917 C<AudioBuffer.getChannelData>/C<copyFromChannel>, the C<AnalyserNode> frequency and time-domain
4918 readers, and C<readPixels>. Without C<seed>, none of this is installed and
4919 readback behaves exactly as before. See the B<Ceiling> notes under
4920 C<fingerprint> above for the residuals.
4921  
4922 =item C<< network_fingerprint => 1 >> or C<< network_fingerprint => 'chrome124' >>
4923  
4924 Also match the B<connection> fingerprint (TLS JA3/JA4 + HTTP/2 Akamai) to the
4925 C<fingerprint> profile, so the origin sees one coherent device at the network
4926 layer too. Requires C<fingerprint>. It spins an in-process L<Proxy::Impersonate>
4927 on this instance's EV loop and routes the browser through it: the proxy
4928 terminates WebKit's TLS locally and re-originates each request as the matching
4929 real browser via C<libcurl-impersonate>. The curl target is derived from the
4930 profile (C<windows-chrome> -> C<chrome150>, C<macos-safari> -> C<safari26_0>,
4931 C<iphone-safari> -> C<safari26_0_ios>, C<windows-firefox> -> C<firefox147>,
4932 C<pixel-chrome> -> C<chrome131_android>); pass a string to override it.
4933  
4934 C<pixel-chrome> stays on Chrome 131 where the others track current stable,
4935 because C<chrome131_android> is the newest Android target C<libcurl-impersonate>
4936 ships and a profile must not claim a browser its TLS cannot back.
4937  
4938 The profile's identity headers (User-Agent + C<Sec-CH-UA>) are forced over the
4939 curl target's defaults, so even a Windows profile is coherent on the (macOS-built)
4940 C<chrome150> target -- Windows and macOS Chrome share the same TLS/HTTP2, so only
4941 the header values differ. WebKit is told to accept the proxy's self-signed cert
4942 (C<set_tls_errors_policy('ignore')>); this is safe because the browser-to-proxy
4943 hop is localhost and the proxy re-verifies the real origin upstream. WebKitGTK 6.0
4944 exposes no custom-CA path (a spike confirmed it honors neither C<SSL_CERT_FILE>
4945 nor a settable C<GTlsDatabase>), which is why the C<IGNORE> policy is used.
4946  
4947 Requires the optional L<Proxy::Impersonate> toolchain (which builds
4948 C<curl-impersonate> via L<Alien::curlimpersonate>); croaks if it is unavailable.
4949 Mutually exclusive with an explicit C<proxy>. Out of scope: WebSockets, HTTP/3.
4950 See L</network_fingerprint> and L</proxy_port>.
4951  
4952 =item C<on_error>, C<on_load>, C<on_navigate>, C<on_close>, C<on_console>, C<on_dialog>, C<on_policy>, C<on_file_chooser>, C<on_download>, C<on_authenticate>, C<on_request>, C<on_response>
4953  
4954 Event callbacks -- see L</"EVENTS">, which documents each one and what it is
4955 handed. (C<popups>, above, is documented there too: it is what happens when no
4956 C<on_policy> is set.)
4957  
4958 =back
4959  
4960 =head1 METHODS
4961  
4962 =head2 Navigation
4963  
4964 Load pages and read basic document state.
4965  
4966 =head3 go
4967  
4968 $b->go($uri, sub { my ($result, $err) = @_; ... });
4969  
4970 Loads C<$uri>. On success C<$result> is true; on failure (or timeout)
4971 C<$err> is set. If a previous navigation on this instance was still
4972 in-flight, its callback is immediately invoked with C<$err eq
4973 'superseded'>. The callback fires just after WebKit's own
4974 C<load-changed:finished> signal -- once the document C<title> has crossed
4975 from the web process, which it does a fraction of a millisecond later
4976 (C<uri> needs no such wait; it is set before C<finished>). A page with no
4977 C<< <title> >> never sends that notification, and settles on a 150ms
4978 deadline instead. C<on_load> (if configured) fires right after the
4979 callback. Returns C<$b> (chainable).
4980  
4981 B<Same-document navigation is not observable from here, and resolves with>
4982 C<$err eq 'timeout'>. A fragment-only C<< go("$here#section") >>, and
4983 C<back>/C<forward> across such a boundary, change the uri without loading
4984 anything -- and WebKitGTK emits B<no> load event for them, so nothing tells this
4985 module they happened. The uri does move (C<uri> reports it, and the page really
4986 did navigate); only the callback is left waiting.
4987  
4988 Predicting it instead of observing it was tried and abandoned: every rule for
4989 "this one will not reload" is falsifiable -- by the outgoing page touching its
4990 own hash while the new load is in flight, by C<history.pushState> having moved
4991 the uri out from under the guess, by a web-process crash -- and each
4992 falsification reports B<success for a page that never loaded>, which is worse
4993 than the wait it removes. So drive these from the page, where they are not a
4994 guess:
4995  
4996 $b->script('location.hash = "section"; return location.href;', $cb);
4997  
4998 and use C<wait_for>/C<wait_for_js> if the page reacts asynchronously.
4999  
5000 =head3 load_html
5001  
5002 $b->load_html($html, sub { my ($result, $err) = @_; ... });
5003  
5004 Loads a literal HTML string as the document, with the same completion
5005 semantics as C<go> (no URI, so it does not count toward C<save_cookies>'s
5006 default URI list). Returns C<$b>.
5007  
5008 =head2 Navigation history
5009  
5010 $b->back(sub { my ($ok, $err) = @_; ... }); # optional callback
5011 $b->forward($cb);
5012 $b->reload($cb);
5013 $b->stop;
5014 $b->can_go_back; # 1 or 0
5015 $b->can_go_forward; # 1 or 0
5016  
5017 back, forward and reload behave like go: the optional trailing callback is
5018 invoked as ($ok, $err) when the resulting navigation finishes (or fails or
5019 times out). Calling back/forward when the history has no entry in that
5020 direction invokes the callback with the error 'cannot go back' /
5021 'cannot go forward', and reload on an instance that has never navigated with
5022 'nothing to reload' (as go with no uri gives 'go: uri required'). stop aborts
5023 the current load and returns the browser object; it takes no callback. can_go_back / can_go_forward are synchronous
5024 and return 1 or 0.
5025  
5026 Note: load_html does not add entries to the back-forward list; only real
5027 navigations (go, links, redirects) do.
5028  
5029 =head3 uri
5030  
5031 my $uri = $b->uri;
5032  
5033 Current document URI. Synchronous.
5034  
5035 =head3 title
5036  
5037 my $title = $b->title;
5038  
5039 Current document title. Synchronous.
5040  
5041 =head3 is_loading
5042  
5043 my $bool = $b->is_loading;
5044  
5045 True while a navigation is in progress. Synchronous.
5046  
5047 =head3 status
5048  
5049 my $code = $b->status; # 200, 404, 500, ... or undef
5050  
5051 HTTP status of the current document, or C<undef> if the load had none.
5052 Synchronous, and available from the moment the document commits -- so reading it
5053 inside a C<go> callback works.
5054  
5055 B<You need this to detect a failed page, because the navigation callback will
5056 not tell you.> WebKit treats a 404 or a 500 as a perfectly successful load --
5057 they have bodies and it displays them -- so C<$ok> is true and C<$err> is
5058 C<undef> for both:
5059  
5060 $b->go($uri, sub {
5061 my ($ok, $err) = @_;
5062 # warn + break, not die: a die here only reaches $EV::DIED
5063 if ($err) { warn "navigation failed: $err\n"; return EV::break } # transport-level only
5064 my $st = $b->status // 0;
5065 if ($st >= 400) { warn "server said $st\n"; return EV::break } # what you actually meant
5066 });
5067  
5068 A redirect chain reports the B<final> response, not the redirect: a 301 that
5069 lands on a 200 reports 200.
5070  
5071 C<undef> means the load carried no HTTP status, which covers two cases worth
5072 telling apart in your head:
5073  
5074 =over 4
5075  
5076 =item *
5077  
5078 There was no HTTP transaction at all -- C<load_html>, and some custom schemes.
5079  
5080 =item *
5081  
5082 There was a transaction but no response line -- some custom schemes, and a
5083 connection the engine reports as reaching an error page rather than failing.
5084  
5085 =back
5086  
5087 A refused connection and a DNS failure do B<not> land here: they resolve the
5088 navigation with C<$ok> C<undef> and C<$err> set to a C<load failed: ...>
5089 string, so check C<$err> first and only then C<status>. (One exception is worth
5090 knowing because it looks like a counter-example: a connection to a port the
5091 host blocks outright, rather than refusing, can be reported by the engine as a
5092 completed load of its own error page -- C<$ok> true with C<undef> status.)
5093  
5094 =head3 html
5095  
5096 $b->html(sub { my ($html, $err) = @_; ... });
5097  
5098 Fetches the full serialized document markup as C<$html>
5099 (C<document.documentElement.outerHTML>), or C<undef> if there is no document
5100 element. Asynchronous, like C<script>.
5101  
5102 =head2 JavaScript Execution
5103  
5104 Run arbitrary JavaScript in the page and get JSON-marshalled results back.
5105 Strings crossing this bridge in either direction are full Unicode CHARACTER
5106 data, not bytes -- a Perl string with non-ASCII characters (e.g. built with
5107 C<\x{e9}> escapes, or read from a C<:utf8> filehandle) passed via
5108 C<script_async>'s C<\%args> or an element's C<type>/C<send_keys> arrives in
5109 JS as the same text, and a JS string returned from C<script> or read via an
5110 element accessor (C<text>, C<value>, ...) comes back as the same Perl
5111 character string. Do not C<utf8::encode> a string before handing it to any
5112 of these; that would turn it into a byte string and produce mojibake on the
5113 JS side instead.
5114  
5115 =head3 script
5116  
5117 $b->script($js, sub { my ($result, $err) = @_; ... });
5118  
5119 Runs C<$js> as the body of an C<async> function (so top-level C<await>
5120 works) and JSON-marshals its C<return> value back as C<$result> (a plain
5121 scalar, arrayref, or hashref; JS C<undefined> or no C<return> becomes Perl
5122 C<undef>). A thrown JS exception becomes C<$err>. Returns C<$b>.
5123  
5124 =head3 script_async
5125  
5126 $b->script_async($body, \%args, sub { my ($result, $err) = @_; ... });
5127 $b->script_async($body, sub { ... }); # no arguments to pass
5128  
5129 Same as C<script>, but C<\%args> is JSON-encoded and made available inside
5130 C<$body> as the const C<A> (e.g. C<A.foo>). This is the primitive
5131 C<find>/C<find_all>/element methods are built on. Returns C<$b>.
5132  
5133 C<\%args> may be omitted entirely, which spells this exactly like C<script>.
5134  
5135 =head3 press
5136  
5137 $b->press($key, %modifiers, $cb); # $cb->($not_cancelled, $err)
5138  
5139 Sends C<keydown>, optionally C<keypress>, then C<keyup> to whatever currently
5140 has focus (else C<document.body>). Modifiers: C<shift>, C<ctrl>, C<alt>,
5141 C<meta>. Resolves false if a handler called C<preventDefault> on the keydown.
5142  
5143 $b->press('Escape', sub { ... }); # close a modal
5144 $b->press('Enter', ctrl => 1, sub { ... });
5145  
5146 For keyboard B<handlers> -- Escape closing a dialog, Enter submitting a form
5147 that listens for it, arrows driving a widget.
5148  
5149 B<It does not type.> A synthetic C<KeyboardEvent> has C<isTrusted> false, and no
5150 engine performs the default text insertion for one, so C<< press('a') >> leaves
5151 an input's value untouched -- silently. Use L<EV::WebKit::Element/type> to edit
5152 a field.
5153  
5154 As in a real browser, C<keypress> is sent only for keys that produce a
5155 character -- which includes C<Enter>, so C<onkeypress> handlers testing for
5156 C<keyCode> 13 work -- and not at all if the keydown was cancelled. C<keyup>
5157 goes to whatever has focus when it is sent, not to whatever had it at
5158 C<keydown>, so a handler that moves focus (the usual thing for C<Tab> and
5159 C<Enter>) behaves as it does under a real key.
5160  
5161 C<keyCode> and C<event.code> both carry what a real browser sends, from one
5162 table so they cannot disagree:
5163  
5164 =over 4
5165  
5166 =item *
5167  
5168 Named keys (C<Enter>, C<Escape>, C<Tab>, C<Backspace>, C<Delete>, the arrows,
5169 C<Home>, C<End>, C<PageUp>, C<PageDown>) get their usual C<keyCode>, and the
5170 name itself as C<code>.
5171  
5172 =item *
5173  
5174 A letter gets its uppercase ordinal and C<KeyQ>; a digit its ordinal and
5175 C<Digit5>.
5176  
5177 =item *
5178  
5179 ASCII punctuation gets the legacy US-layout value -- C<.> is 190 and C<Period>,
5180 C<'> is 222 and C<Quote>, and so on for C<,> C<;> C</> C<-> C<=> C<[> C<]>
5181 C<\> C<`> and space.
5182  
5183 =item *
5184  
5185 A shifted character such as C<!>, or any non-ASCII one, names no physical key by
5186 itself -- which key produced it depends on the layout. Those report C<code>
5187 C<''> and C<keyCode> C<0>, the pair a browser uses for a key it cannot
5188 identify. (Deriving a number from the character instead would not merely be
5189 wrong, it would B<impersonate another key>: C<ord('.')> is 46, which is
5190 C<Delete>, and C<< ord("'") >> is 39, which is C<ArrowRight>.)
5191  
5192 =back
5193  
5194 =head3 scroll
5195  
5196 $b->scroll(y => 500, $cb); # absolute
5197 $b->scroll(x => 40, y => 500, $cb); # both axes
5198 $b->scroll(by => 1, y => 100, $cb); # relative to where you are
5199 $b->scroll(to => 'bottom', $cb); # the infinite-scroll case
5200 $b->scroll(y => 500, cb => $cb); # the callback, named
5201  
5202 Scrolls the page and resolves with the resulting C<< { x, y } >>. Options are
5203 C<x> and C<y> (absolute offsets in CSS pixels), C<< by => 1 >> to make them
5204 relative to the current position, and C<< to => 'top' >> / C<< to => 'bottom' >>.
5205 C<< to => 'bottom' >> computes the document height rather than guessing a large
5206 number, which is what makes it reliable for lazy-loading pages. C<< to => 'top' >>
5207 resets both axes; C<< to => 'bottom' >> moves only C<y> and leaves C<x> where it
5208 was.
5209  
5210 The callback may be passed as a trailing argument, like every other method here,
5211 or as the named C<cb> option (C<callback> is accepted as a synonym) -- this is
5212 the one method that takes both, because every other argument it takes is named.
5213 Passing it both ways at once croaks rather than silently using one of them.
5214  
5215 The scroll is B<instant>, and deliberately overrides the page's own CSS
5216 C<scroll-behavior: smooth> if it has one. Under that property the scroll is an
5217 animation: it has not happened yet when the callback runs, so the reported
5218 position would be the one you started from and anything you did next -- a
5219 screenshot, a L<EV::WebKit::Element/box> -- would see the old viewport.
5220 L<EV::WebKit::Element/scroll_into_view> does the same.
5221  
5222 =head3 resize
5223  
5224 $b->resize($width, $height, sub { my ($size, $err) = @_; ... });
5225  
5226 Resizes the window, and so the viewport. C<$size> is C<< { width, height } >> as
5227 the B<page> sees it (C<window.innerWidth>/C<innerHeight>), read back after the
5228 resize has actually landed rather than assumed from the request -- GTK round
5229 trips through the display server, and under a real window manager the request
5230 can be clamped or refused outright. A resize that never takes effect is
5231 therefore not an error: you get the size you actually have.
5232  
5233 The numbers are CSS pixels, so C<zoom> scales them: at C<< zoom(2) >> a
5234 400-pixel-wide window reports 200. C<< chrome => 1 >> takes its own share too --
5235 the header bar and GTK4's client-side decorations leave a 400x320 request with a
5236 390x264 viewport (measured) -- which is why this settles on the viewport holding
5237 still rather than on it reaching the numbers you asked for.
5238  
5239 C<window> at construction is the same setting; this is for changing it
5240 afterwards, e.g. to render a page at a mobile width without building a second
5241 instance.
5242  
5243 =head3 zoom
5244  
5245 my $level = $b->zoom; # get
5246 $b->zoom(2); # set, returns $b
5247  
5248 Page zoom as a multiplier; C<1> is unzoomed. Synchronous both ways. This is the
5249 browser's own zoom, so it changes C<devicePixelRatio> and the CSS pixel size of
5250 the viewport -- which is exactly what you want for a hi-dpi screenshot, and
5251 exactly what you do not want if a C<fingerprint> profile has already fixed
5252 C<devicePixelRatio> for you.
5253  
5254 =head2 Elements
5255  
5256 Locate DOM elements and hand back L<EV::WebKit::Element> handles.
5257  
5258 =head3 find
5259  
5260 $b->find($selector, sub { my ($el, $err) = @_; ... });
5261  
5262 Runs C<document.querySelector($selector)>. C<$el> is an
5263 L<EV::WebKit::Element> on a match, or C<undef> if nothing matched --
5264 not-found is not an error (C<$err> is C<undef> in that case too).
5265  
5266 =head3 Addressing an iframe
5267  
5268 C<find>, C<find_all> and C<wait_for> take an optional C<< frame => >> naming a
5269 frame to search inside, instead of the top-level document. There are two forms,
5270 and the frame's origin decides which one you can use.
5271  
5272 For a B<same-origin> frame, give a CSS selector for the C<< <iframe> >> element
5273 itself:
5274  
5275 $b->find('#card-number', frame => '#payment', sub { ... });
5276  
5277 Pass an arrayref to walk a chain of nested frames, outermost first:
5278  
5279 $b->find('#deep', frame => ['#outer', '#inner'], sub { ... });
5280  
5281 This form is page script walking C<contentDocument>, so it stops dead at a
5282 cross-origin boundary: such a frame fails with an error naming cross-origin as
5283 the reason rather than reporting the element as merely absent. For C<find> and
5284 C<find_all>, a frame selector that matches nothing is likewise an error, not a
5285 silent miss -- the two are worth telling apart when a page is still loading.
5286  
5287 C<wait_for> is the deliberate exception: a frame that is not there B<yet> is
5288 the ordinary case for a page that injects its iframe after load, so C<wait_for>
5289 polls through a missing frame rather than failing on it, and gives up only at
5290 its own timeout. With C<< gone => 1 >> a missing frame resolves true, since the
5291 selector inside it matches nothing -- which does mean a typo'd frame selector
5292 plus C<< gone => 1 >> succeeds immediately.
5293  
5294 A dead C<< { id => } >> is the one thing it will not wait for. An id names a
5295 frame that already existed, and once that frame is gone the id can never name
5296 anything again, so C<wait_for> fails on it at once with C<frame is gone>
5297 instead of polling to its timeout.
5298  
5299 For a B<cross-origin> frame -- a hosted payment form, a third-party widget --
5300 name it by URL instead:
5301  
5302 $b->find('#card-number', frame => { url => 'https://pay.example/form' }, sub { ... });
5303 $b->find('#card-number', frame => { url => qr{^https://pay\.} }, sub { ... });
5304  
5305 The URL is matched against the frame's current URL, exactly for a string or by
5306 pattern for a C<qr//>, and must identify B<one> frame: both no match and more
5307 than one are errors, because acting on the wrong payment iframe is worse than
5308 not acting at all. Only child frames are considered -- the main frame is what
5309 you get by leaving C<frame> out.
5310  
5311 Two frames on the B<same> URL are the one case this cannot resolve, and
5312 L</frames> will not resolve it either: it returns them in the web process's own
5313 order, which is stable within a run but is B<not> document order, and no field
5314 it gives you (id, url, is_main) says which is which. Sorting by id does not
5315 recover document order. So:
5316  
5317 =over 4
5318  
5319 =item *
5320  
5321 If they are same-origin, use the selector form -- C<< frame => '#checkout' >> --
5322 which addresses them positionally through the DOM.
5323  
5324 =item *
5325  
5326 If they are cross-origin, make the URLs distinguishable. A query parameter the
5327 page controls is enough, and you are usually the one embedding them.
5328  
5329 =back
5330  
5331 A C<< frame => { id => $id } >> is still the right thing when you have an id
5332 you trust -- one you kept from an earlier C<find> whose handle you still hold,
5333 say -- but do not derive it by position from L</frames>.
5334  
5335 C<url> and C<id> are alternatives: give exactly one.
5336  
5337 This form does not run in the page at all. It goes to the web-process
5338 extension, which sees every frame directly and is not bound by the same-origin
5339 policy, so it reaches what the selector form cannot. That means it needs the
5340 extension to have been built at install time (see L<EV::WebKit::Fingerprint>),
5341 and says so plainly rather than timing out if it was not.
5342  
5343 An element found through either form behaves like any other: its methods act on
5344 the node inside the frame.
5345  
5346 The two forms differ in where that happens, and C<< $el->frame_id >> says
5347 which. A handle from the C<< { url|id => } >> form carries the frame's id, and
5348 every later call on it -- and on anything C<find> returns from it -- is
5349 evaluated by the extension B<in that frame>. A handle from the selector form
5350 has C<frame_id> C<undef>, because it was reached by main-frame script walking
5351 C<contentDocument> and is operated on the same way; so is any handle from the
5352 main frame itself.
5353  
5354 Neither kind outlives its page, but they report that differently. Once the
5355 frame is removed or the page navigates away, a frame-bound handle fails with
5356 C<frame is gone>, while a selector-reached one fails with the ordinary
5357 C<stale element>. Either way, resolve the frame again after a navigation rather
5358 than holding onto anything across one.
5359  
5360 =head3 frames
5361  
5362 $b->frames(sub { my ($frames, $err) = @_; ... });
5363  
5364 The frames the page has right now, as an arrayref of C<< { id, url, main } >>.
5365 Use it to see what C<< frame => { url => ... } >> has to choose between. The
5366 C<id> is opaque, page-scoped and only meaningful while that frame lives, so
5367 pass it straight back as C<< frame => { id => $id } >> rather than writing it
5368 down and reusing it after a navigation.
5369  
5370 The order is the web process's own -- stable within a run, but B<not> document
5371 order, and not recoverable by sorting. So this does not tell apart two frames
5372 on the same URL either; see C<< frame => >> above for what to do instead.
5373  
5374 Like the C<< { url => } >> form above, this needs the web-process extension.
5375  
5376 =head3 find_all
5377  
5378 $b->find_all($selector, sub { my ($els, $err) = @_; ... });
5379  
5380 Like C<find>, but C<querySelectorAll>: C<$els> is a (possibly empty)
5381 arrayref of L<EV::WebKit::Element>.
5382  
5383 =head3 find_js / find_all_js
5384  
5385 $b->find_js($javascript, %opts, sub { my ($el, $err) = @_; ... });
5386 $b->find_all_js($javascript, %opts, sub { my ($els, $err) = @_; ... });
5387  
5388 Find elements with your own JavaScript instead of a CSS selector, and get the
5389 same L<EV::WebKit::Element> handles back. The snippet is a function body: it
5390 must C<return> a DOM node (or C<undef>/C<null> for no match) for C<find_js>, and
5391 an array or NodeList of nodes for C<find_all_js>.
5392  
5393 This is the way to reach what CSS cannot name:
5394  
5395 # XPath
5396 $b->find_js('return document.evaluate("//tr[td[contains(.,\'Invoice 42\')]]//a",
5397 document, null, 9, null).singleNodeValue;', $cb);
5398  
5399 # by visible text
5400 $b->find_js('return [...document.querySelectorAll("button")]
5401 .find(b => b.textContent.trim() === "Next");', $cb);
5402  
5403 # inside a shadow root, which querySelector does not cross at all
5404 $b->find_js('return document.querySelector("#host").shadowRoot.querySelector(".deep");', $cb);
5405  
5406 C<%opts>:
5407  
5408 =over 4
5409  
5410 =item C<< args => \%hash >>
5411  
5412 Values the snippet reads as C<A.name>, marshalled as JSON exactly as
5413 C<script_async>'s are.
5414  
5415 =item C<< frame => { url => ... } >> or C<< frame => { id => ... } >>
5416  
5417 Run the snippet in that frame (see L</"Addressing an iframe">). The selector
5418 chain form is B<not> accepted here -- it is a walk through C<contentDocument>
5419 that the snippet can do for itself, and rewriting the snippet's idea of
5420 C<document> is not something this can do behind your back.
5421  
5422 =back
5423  
5424 Unlike C<script>, the snippet runs in the module's own isolated world -- the
5425 same one the element registry lives in, which is what makes handing a node back
5426 possible at all. It therefore does B<not> see the page's own globals; use
5427 C<script> for those. A snippet that returns something other than a node (or a
5428 list of them) fails with an error saying so, rather than a handle to nothing.
5429  
5430 =head3 wait_for
5431  
5432 $b->wait_for($selector, %opts, sub { my ($el, $err) = @_; ... });
5433  
5434 Polls C<find($selector)> until it matches (and, if C<visible> is set, until
5435 it is also visible), or until C<timeout> elapses. C<%opts>:
5436  
5437 =over 4
5438  
5439 =item C<< timeout => $seconds >>
5440  
5441 Default: this instance's own C<timeout> (see C<new>).
5442  
5443 =item C<< interval => $seconds >>
5444  
5445 Poll interval. Default C<0.05>. A non-positive value (C<0> or negative) is
5446 meaningless for a poll and snaps to the default instead, so it can't stall
5447 the deadline check and busy-loop the EV loop.
5448  
5449 =item C<< visible => $bool >>
5450  
5451 Also wait for the matched element's C<is_visible> to become true before
5452 resolving.
5453  
5454 =item C<< gone => $bool >>
5455  
5456 Invert it: wait for the selector to match B<nothing>. The usual reason is a
5457 spinner or overlay that must disappear before the page is usable. There is no
5458 element to hand back, so the callback receives a plain true value rather than
5459 one -- and C<gone> with C<visible> croaks, since "wait for it to be visible"
5460 and "wait for it to not exist" cannot both be meant.
5461  
5462 =back
5463  
5464 On timeout, C<$el> is C<undef> and C<$err eq 'timeout'>. Returns C<$b>.
5465  
5466 =head3 wait_for_navigation
5467  
5468 $b->wait_for_navigation(%opts, sub { my ($uri, $err) = @_; ... });
5469 $el->click; # ...and only then start it
5470  
5471 Resolves when the B<next> navigation finishes, whoever started it -- a link
5472 click, a form submit, a script-driven redirect, or one of this module's own
5473 navigation methods. C<$uri> is where it landed.
5474  
5475 It waits for a navigation that B<loads a document>. A same-document one -- a
5476 hash-route link, C<history.pushState> -- loads nothing and emits no load event,
5477 so it is not seen here either; see L</go> for why that is not guessed at, and
5478 what to do instead.
5479  
5480 This is the other half of every multi-step flow. C<go>'s callback covers what
5481 you started yourself; a navigation the B<page> starts has no completion signal
5482 otherwise: C<on_load> deliberately does not fire for one, C<on_navigate> fires
5483 at commit rather than at finish, and C<is_loading> can read false for the whole
5484 of a fast load. So:
5485  
5486 $b->wait_for_navigation(sub {
5487 my ($uri, $err) = @_;
5488 return warn "submit went nowhere: $err\n" if $err;
5489 $b->find('#dashboard', $cb); # safe: this IS the next page
5490 });
5491 $b->find('#submit', sub { $_[0]->click });
5492  
5493 B<Arm it before you click>, as above. It waits for the next navigation, not the
5494 last one, so a fast page that finishes first is simply missed.
5495  
5496 Do not reach for C<wait_for($selector)> instead: armed before the click it runs
5497 against the page you are B<leaving>, so a selector present on both resolves at
5498 once, with the old document -- a wrong answer rather than an error.
5499  
5500 C<%opts>:
5501  
5502 =over 4
5503  
5504 =item C<< timeout => $seconds >>
5505  
5506 Default: this instance's own C<timeout>. On expiry C<$err> is C<'timeout'>.
5507 Passing a non-positive value here B<croaks>: there is nothing a zero deadline
5508 could mean, and unlike C<wait_for> -- which polls, so a zero timeout there means
5509 "probe once and give up" -- this has nothing to probe. An instance-wide
5510 C<< timeout => 0 >> is inherited as-is and means what it means everywhere else
5511 in this module: time out at once.
5512  
5513 =back
5514  
5515 An unknown option croaks, and so does a last argument that is not a code
5516 reference; both are caller mistakes visible at the call site.
5517  
5518 A navigation that fails resolves with that failure's C<$err> and no C<$uri>.
5519 That includes one this API started, so a C<go> and a waiter armed across it both
5520 report the same failure.
5521  
5522 =head3 wait_for_js
5523  
5524 $b->wait_for_js($expr, %opts, sub { my ($value, $err) = @_; ... });
5525  
5526 Polls a JavaScript expression until it is truthy, then resolves with its value.
5527 Takes the same C<timeout> and C<interval> options as C<wait_for>. For waiting on
5528 application state rather than on the DOM:
5529  
5530 $b->wait_for_js('window.app && window.app.ready', sub { ... });
5531  
5532 B<An expression that throws is not an error, it is "not yet".>
5533 C<window.app.ready> raises a C<TypeError> for as long as C<window.app> is
5534 undefined, which is exactly the state you are waiting through -- so a throw is
5535 treated as false and polling continues. The cost is that a genuine typo also
5536 just times out, so the timeout message carries both the expression and the last
5537 JavaScript error:
5538  
5539 timeout waiting for: no_such_fn() (last JS error: ReferenceError: ...)
5540  
5541 The expression is evaluated in the page's own world, as C<script> does, so it
5542 sees the page's globals.
5543  
5544 B<Truthiness is JavaScript's, not Perl's.> The verdict is reached in the page
5545 and sent back beside the value, so the two languages cannot disagree about it:
5546 the string C<"0"> is true here, as it is in JavaScript, and a function is true
5547 even though it has no JSON representation. That last point is what makes the
5548 most common form of this call work at all --
5549  
5550 $b->wait_for_js('window.jQuery', sub { ... }); # a function
5551  
5552 -- and the price is that C<$value> is C<undef> for such a value: the wait
5553 succeeds, but there is nothing meaningful to marshal back. The same holds for
5554 anything else JSON cannot carry -- a BigInt, or an object containing a cycle,
5555 which most framework objects do. Wait on the expression you care about, and
5556 read what you need afterwards.
5557  
5558 =head2 Downloads and file upload
5559  
5560 Fetch resources to disk, and drive file inputs.
5561  
5562 =head3 download
5563  
5564 $b->download($uri, $path, sub { my ($path, $err) = @_; ... });
5565  
5566 Fetches C<$uri> straight to C<$path> without navigating to it. C<$path> is a
5567 plain filesystem path. On success the callback receives that path; on failure,
5568 C<undef> and an error string. Returns C<$b>.
5569  
5570 Note that a custom scheme registered with C<mock_scheme> is B<not> reachable
5571 this way: C<mock_scheme> is registered on the web context, while downloads run
5572 on the network session, which has never heard of the scheme and reports
5573 C<"The URL can't be shown">.
5574  
5575 C<file://> URIs, on the other hand, B<do> work: C<download> copies the local
5576 file, and a missing one comes back as an ordinary error. This is worth knowing
5577 before you hand C<download> a URI from an untrusted source, and doubly so before
5578 you put a browser on a control socket -- C<download('file:///etc/passwd', $out)>
5579 reads any file the process can read, which page JavaScript cannot do. The socket
5580 is already a full-trust boundary (see L<EV::WebKit::Control/SECURITY>), but the
5581 reach is wider than a network fetch.
5582  
5583 A download still in flight when C<quit> is called resolves with
5584 C<'browser closed'>, like every other pending operation.
5585  
5586 =head3 on_authenticate
5587  
5588 Answer an HTTP (or proxy) authentication challenge:
5589  
5590 my $b = EV::WebKit->new(on_authenticate => sub {
5591 my ($auth) = @_;
5592 return $auth->cancel if $auth->is_retry; # wrong password: stop, don't loop
5593 $auth->login('alice', 'hunter2');
5594 });
5595  
5596 C<$auth> is an L<EV::WebKit::Auth|/"EV::WebKit::Auth">, valid only for the
5597 duration of the call.
5598  
5599 B<Without a handler the challenge is cancelled>, and the navigation fails
5600 immediately. That is deliberate: nobody answering a challenge means WebKit
5601 waits, so the navigation used to resolve C<'timeout'> after the full instance
5602 timeout with C<status> C<undef> -- indistinguishable from an unreachable host. A
5603 handler that dies is treated the same way, and so is one that returns without
5604 deciding.
5605  
5606 WebKit reports every refused challenge as a bare C<Load request cancelled>,
5607 which reads like you cancelled the navigation yourself, so the error is
5608 annotated with which route it took: C<no on_authenticate handler answered it>,
5609 C<the on_authenticate handler died>, C<the on_authenticate handler answered
5610 nothing>, or -- when you called C<< $auth->cancel >> deliberately -- C<the
5611 on_authenticate handler cancelled it>.
5612  
5613 Credentials embedded in a URI (C<< http://user:pass@host/ >>) are applied by
5614 WebKit itself and never reach this handler.
5615  
5616 =head3 on_download
5617  
5618 Called when the B<page> starts a download (a link with C<download>, a response
5619 WebKit will not display). The handler must name a destination:
5620  
5621 on_download => sub {
5622 my ($d) = @_;
5623 $d->save_to("/tmp/" . $d->suggested);
5624 $d->on_finish(sub { my ($path, $err) = @_; ... });
5625 }
5626  
5627 B<A download whose handler names no destination is cancelled>, deliberately:
5628 WebKit's own default writes into the user's Downloads directory, which an
5629 automation run must not do behind the caller's back. With no C<on_download> at
5630 all, every page-initiated download is cancelled.
5631  
5632 The object passed in offers C<uri>, C<suggested> (the server's suggested
5633 filename), C<destination>, C<progress>, C<received>, C<save_to($path,
5634 overwrite =E<gt> $bool)>, C<on_finish($cb)> and C<cancel>. It stays valid until
5635 the download finishes or fails, unlike the dialog and policy objects.
5636  
5637 =head3 on_file_chooser
5638  
5639 Called when the page opens a file chooser -- a click on C<< <input type=file> >>,
5640 which is the only way to populate one, since a file input's value cannot be set
5641 from JavaScript:
5642  
5643 on_file_chooser => sub { $_[0]->select('/tmp/photo.png') }
5644  
5645 The object offers C<mime_types> (the C<accept=> list), C<multiple>, C<selected>,
5646 C<select(@paths)> and C<cancel>. C<select> croaks on a path that does not exist,
5647 or on several paths when the input accepts only one -- WebKit itself would
5648 silently hand the page an unreadable entry.
5649  
5650 B<The selection is applied asynchronously.> Reading C<files.length> in the
5651 callback of the C<click> that opened the chooser still sees 0; it becomes
5652 correct a tick later. Poll for it (or wait) rather than reading once.
5653  
5654 Without an C<on_file_chooser> handler nothing changes: WebKit runs its own
5655 native GTK file chooser, exactly as before. A handler that dies, or that
5656 decides nothing, cancels the request rather than leaving the page waiting on a
5657 chooser that never resolves.
5658  
5659 =head3 on_request
5660  
5661 Intercept every request the browser makes -- rewrite it, answer it locally, or
5662 refuse it:
5663  
5664 my $b = EV::WebKit->new(on_request => sub {
5665 my ($req) = @_;
5666 return { status => 403, body => 'no ads here' } if $req->{host} =~ /ads\./;
5667 $req->{headers}{'x-trace'} = 'yes'; # rewrite in place
5668 return; # ...and let it proceed
5669 });
5670  
5671 C<$req> has C<method>, C<url>, C<headers>, C<body> and C<host>. Return nothing
5672 to proceed (carrying any rewrites), a hashref (C<status>, C<headers>, C<body>)
5673 to answer without touching the network, or the string C<'abort'> to drop the
5674 connection. A handler that dies refuses the request with a 502 and warns -- it
5675 fails closed, since this hook exists to block traffic and an exception must not
5676 let through exactly what you were stopping. Construct-time only.
5677  
5678 This works by routing the browser through the same in-process
5679 L<Proxy::Impersonate> that C<network_fingerprint> uses, because WebKitGTK 6.0
5680 offers nothing better: the UI process exposes only the observational
5681 C<sent-request>, the mutable C<send-request> lives solely in the web-process
5682 extension, and libsoup is unreachable since WebKit2 runs networking in a
5683 separate process. Interception therefore happens at the one place the plaintext
5684 exists. Requires L<Proxy::Impersonate> 0.01 (croaks otherwise, rather than
5685 silently not intercepting), and is mutually exclusive with C<proxy>.
5686  
5687 Two consequences worth knowing:
5688  
5689 =over 4
5690  
5691 =item Requests to local addresses are B<not> intercepted.
5692  
5693 WebKit routes localhost and private addresses directly, bypassing the proxy, so
5694 the hook never sees them. This is WebKit's own behaviour -- C<network_fingerprint>
5695 has always had it too -- and it cannot be turned off from here.
5696  
5697 =item Your connection fingerprint changes.
5698  
5699 The proxy always re-originates through C<libcurl-impersonate>; there is no
5700 passthrough. With C<fingerprint> set, the matching target is used; without one,
5701 a current Chrome. If that matters, set C<fingerprint> (or
5702 C<network_fingerprint>) explicitly rather than relying on the default.
5703  
5704 =back
5705  
5706 Headers are the set forced on top of the impersonation template (C<Cookie>,
5707 C<Referer>, C<Sec-Fetch-*>, ...), not the template's own (C<User-Agent>,
5708 C<Accept>, ...) -- see L<Proxy::Impersonate/on_request>. Setting those keys
5709 still overrides the template.
5710  
5711 =head3 on_response
5712  
5713 my $b = EV::WebKit->new(on_response => sub {
5714 my ($res) = @_;
5715 delete $res->{headers}{'content-security-policy'}; # the usual reason
5716 delete $res->{headers}{'x-frame-options'};
5717 return;
5718 });
5719  
5720 The counterpart to C<on_request>, called when each response's head arrives and
5721 before any of it reaches the page. C<$res> has C<status>, C<headers>, and the
5722 request's C<url>, C<method> and C<host>. Modify C<status> or C<headers> in
5723 place; the return value is ignored. Construct-time only, and it carries the same
5724 caveats as C<on_request> -- local addresses are not intercepted, and the
5725 connection fingerprint changes.
5726  
5727 Stripping a policy header is what this is usually for: a page that refuses to
5728 frame, or a C<Content-Security-Policy> that blocks the script you want to
5729 inject, can be relaxed here rather than worked around.
5730  
5731 Framing is not yours to change: C<Content-Length>, C<Connection> and the
5732 hop-by-hop headers are restored after the handler runs, because a handler that
5733 edits them desynchronises the browser's connection rather than its own.
5734  
5735 B<Response bodies are not available here at all> -- they stream through the
5736 proxy with backpressure, and buffering them to hand over would defeat that. To
5737 B<replace> a body, answer the request outright with C<on_request>'s synthetic
5738 response. To B<read> one -- the "what did that XHR return" case -- fetch it from
5739 the page instead, where it is already parsed:
5740  
5741 $b->script_async('const r = await fetch(A.url); return await r.json();',
5742 { url => $api }, $cb);
5743  
5744 That runs in the page's own origin and session, so it carries the cookies and
5745 headers the page would have sent.
5746  
5747 Unlike C<on_request>, a handler that B<dies> passes the response through and
5748 warns. It fails B<open> deliberately: the request has already been made, so
5749 there is no longer anything to protect by refusing, and breaking the page over
5750 a bug in an observer would be worse.
5751  
5752 =head2 Screenshots and PDF
5753  
5754 Capture the rendered page.
5755  
5756 =head3 screenshot
5757  
5758 $b->screenshot($path, sub { my ($result, $err) = @_; ... });
5759 $b->screenshot(\%opts, sub { my ($result, $err) = @_; ... });
5760 $b->screenshot($path, %opts, sub { my ($result, $err) = @_; ... });
5761  
5762 Captures a PNG of the current page. With a plain C<$path>, the PNG is
5763 written there and C<$result> is C<$path>. The C<\%opts>-only form has no
5764 C<$path>, so it requires C<< bytes => 1 >> (below) -- calling it with
5765 neither a path nor C<bytes> errors with
5766 C<< 'screenshot path required (or bytes => 1)' >>. C<%opts>:
5767  
5768 =over 4
5769  
5770 =item C<< full => $bool >>
5771  
5772 Capture the full scrollable document instead of just the visible viewport.
5773  
5774 =item C<< transparent => $bool >>
5775  
5776 Transparent background instead of opaque white.
5777  
5778 =item C<< bytes => $bool >>
5779  
5780 Return the raw PNG byte string as C<$result> instead of writing a file --
5781 no file is written even if C<$path> was also given.
5782  
5783 =back
5784  
5785 Returns C<$b>.
5786  
5787 =head3 pdf
5788  
5789 $b->pdf($path, %opts, sub { my ($result, $err) = @_; ... });
5790  
5791 Renders the current page to a PDF file at C<$path> via
5792 C<WebKit::PrintOperation>. C<%opts>: C<paper> (a B<PWG> paper-size name --
5793 C<iso_a4> (the default), C<na_letter>, C<na_legal>, C<iso_a3>; B<not> C<a4> or
5794 C<letter>, which GTK does not recognise and which render at the default size
5795 with only a warning on stderr), C<margin> (mm, all four sides, default C<0>),
5796 C<resolution>
5797 (dpi, default C<300>), C<timeout> (seconds, overriding the instance default
5798 for this call). C<$result> is C<$path> on success. Returns C<$b>.
5799  
5800 C<resolution> is passed through to the GTK print settings, but do not expect
5801 it to change anything: WebKitGTK's print-to-PDF path does not consult it
5802 (72, 300 and 1200 dpi produce byte-identical files), because the output is
5803 vector rather than rasterised. It is accepted for completeness.
5804 C<pdf($path)> errors with C<'pdf: no page loaded'> if called before the view
5805 has navigated anywhere.
5806  
5807 Calls are B<serialized>: two C<WebKit::PrintOperation>s running on one view
5808 at once race at the engine level (and crash it), so C<pdf()> queues each
5809 request and runs exactly one at a time. You may fire several C<pdf()> calls
5810 back-to-back; each resolves its own callback in turn, and their outcomes are
5811 deterministic.
5812  
5813 The C<timeout> bounds how long B<your callback> waits, counted from the
5814 C<pdf()> call itself -- not from the moment the job reaches the head of the
5815 queue. So it covers the time spent queued behind other prints as well as the
5816 printing, and a call made while an earlier print is stuck still resolves on
5817 its own deadline with C<$err eq 'timeout'>.
5818  
5819 What that error means depends on whether the print had started:
5820  
5821 =over 4
5822  
5823 =item *
5824  
5825 B<Still queued> at the deadline: it never runs. Nothing was printed and no
5826 file is written -- the job is dropped when its turn comes.
5827  
5828 =item *
5829  
5830 B<Already printing> at the deadline: the print is B<not> aborted.
5831 WebKit-6.0's C<WebKit::PrintOperation> has no cancel method at all, so
5832 nothing can stop one once it is under way. Treat C<'timeout'> here as "took
5833 too long, outcome unknown", not "did not happen": the operation may still
5834 complete afterwards and write its file to C<$path>.
5835  
5836 =back
5837  
5838 For that second case the queue does B<not> advance past a timed-out
5839 operation until the engine actually finishes it (starting the next print
5840 alongside a live one would crash the engine). A subsequent C<pdf()> to the
5841 same path is therefore safely queued behind it, never racing its write.
5842  
5843 =head2 Settings
5844  
5845 User-Agent and arbitrary WebKitSettings properties.
5846  
5847 =head3 set_user_agent
5848  
5849 $b->set_user_agent($ua_string);
5850  
5851 Sets the User-Agent. Synchronous, returns C<$b>.
5852  
5853 =head3 user_agent
5854  
5855 my $ua = $b->user_agent;
5856  
5857 Current User-Agent. Synchronous.
5858  
5859 =head3 settings
5860  
5861 $b->settings({ enable_javascript => 0, ... });
5862  
5863 Sets arbitrary C<WebKit::Settings> GObject properties: each key has its
5864 underscores turned into hyphens (C<enable_javascript> becomes the
5865 C<enable-javascript> property). Synchronous, returns C<$b>. A reference value,
5866 or a key naming a property that does not exist, croaks. Not transactional: a
5867 croak on an unknown property name may leave earlier keys in the same call
5868 already applied (reference values are all rejected up front, so a typed-value
5869 mistake is caught before anything is set).
5870  
5871 =head3 show_devtools
5872  
5873 $b->show_devtools;
5874  
5875 Enables C<enable-developer-extras> (if not already) and opens the Web
5876 Inspector window. Synchronous, returns C<$b>.
5877  
5878 =head2 Network
5879  
5880 Proxy configuration and custom URI-scheme handlers.
5881  
5882 =head3 set_proxy
5883  
5884 $b->set_proxy($uri);
5885 $b->set_proxy({ default => $uri, ignore => [@hosts] });
5886 $b->set_proxy(undef); # or 'no-proxy'
5887  
5888 Configures (or clears) this instance's proxy. Synchronous, no callback.
5889 Returns C<$b>. Equivalent to the constructor's C<proxy> option.
5890  
5891 Only C<undef> and the literal string C<'no-proxy'> clear the proxy; any other
5892 value is treated as a custom proxy to set, and its default URI is validated
5893 up front (must look like C<scheme://authority>). WebKit itself only prints a
5894 C-level CRITICAL and silently falls back to a direct connection for a
5895 malformed proxy URI -- not a Perl exception C<eval> could catch -- so an
5896 invalid or empty default URI (including a C<< { default => ... } >> hash
5897 with no C<default>) makes this method C<Carp::croak> instead, fail-fast
5898 rather than silently discarding the proxy.
5899  
5900 =head3 mock_scheme
5901  
5902 $b->mock_scheme($scheme, sub { my ($uri) = @_; return ($body, $content_type) });
5903  
5904 Registers a custom URI-scheme handler on this instance's private (not the
5905 shared default) C<WebKit::WebContext>. The producer callback is invoked
5906 once per request to C<$scheme>; C<$content_type> defaults to C<text/html>
5907 if omitted. Must be registered before the first navigation to C<$scheme>.
5908 Pass C<$body> as a character string (e.g. plain ASCII, or containing
5909 C<\x{e9}>-style non-ASCII text); it is served as its UTF-8 encoding. Do not
5910 pass pre-encoded octets -- a byte string that already holds UTF-8 bytes
5911 would be encoded a second time and corrupt the output. As with any HTTP
5912 response, WebKit's HTML parser still needs to be told the encoding: include
5913 C<charset=utf-8> in C<$content_type> (or a C<< <meta charset="utf-8"> >> tag
5914 in the body itself) whenever it isn't plain ASCII, the same as a real web
5915 server would. Synchronous, returns C<$b>.
5916  
5917 If the producer dies, the request fails cleanly instead of crashing the
5918 process. Whether anyone hears about it depends on what was being fetched: for
5919 the B<document> of a navigation this instance started, that navigation's
5920 callback receives a defined C<$err> describing the failure; for a subresource
5921 (an image, a script, an iframe) the page simply does not get it, exactly as a
5922 browser treats any failed subresource, and the navigation still succeeds. C<$err>'s exact wording is this module's own, not a
5923 native WebKit network error (C<finish_error>, WebKit's normal way to report
5924 this, is unusable with the currently supported C<Glib::Object::Introspection>
5925 -- see the source comment on C<mock_scheme>'s C<register_uri_scheme>
5926 callback for why).
5927  
5928 =head2 Cookie Management
5929  
5930 C<set_cookie>/C<cookies>/C<clear_cookies> operate on this instance's live
5931 session. C<cookie_jar> (see C<new>) gives native persistent storage for
5932 non-session cookies automatically; C<save_cookies>/C<load_cookies> below
5933 are an explicit, opt-in JSON snapshot mechanism -- see L</"LIMITATIONS">.
5934  
5935 =head3 set_cookie
5936  
5937 $b->set_cookie(\%spec, sub { my ($ok, $err) = @_; ... });
5938  
5939 C<%spec>: C<name>, C<value>, C<domain>, C<path> (default C</>), C<max_age>
5940 (seconds, default C<-1> = session cookie), C<secure> (bool), C<http_only>
5941 (bool). C<$ok> is true on success. Errors with
5942 C<< "set_cookie: missing '<key>'" >> if C<name>/C<value>/C<domain> is missing
5943 from C<%spec>. Returns C<$b>.
5944  
5945 =head3 cookies
5946  
5947 $b->cookies($uri, sub { my ($list, $err) = @_; ... });
5948  
5949 C<$list> is an arrayref of C<{ name, value, domain, path, secure,
5950 http_only }> hashrefs visible to C<$uri> (C<secure>/C<http_only> are 1 or
5951 0). Errors with C<'cookies: uri required'> if C<$uri> is missing/empty.
5952 Returns C<$b>.
5953  
5954 =head3 clear_cookies
5955  
5956 $b->clear_cookies(sub { my ($ok, $err) = @_; ... });
5957  
5958 Clears every cookie in this instance's session (not scoped to a single
5959 domain/URI). Returns C<$b>.
5960  
5961 =head3 save_cookies
5962  
5963 $b->save_cookies($file, sub { my ($count, $err) = @_; ... });
5964 $b->save_cookies($file, \@uris, sub { my ($count, $err) = @_; ... });
5965  
5966 Writes this instance's cookies to C<$file> as a JSON snapshot, enumerated
5967 per-URI (via the same path as C<cookies>) over C<\@uris>, or, if omitted,
5968 every URI this instance has C<go>ne to. C<$count> is the number of
5969 (deduplicated) cookies written. C<$file> is written as UTF-8 text, so
5970 cookie values containing non-ASCII characters round-trip correctly. This
5971 is an explicit, opt-in mechanism, distinct from C<cookie_jar>'s native
5972 persistence (see C<new>) -- it is the only way to capture SESSION cookies,
5973 which native persistence excludes by design. Errors with C<'snapshot file
5974 required'> if C<$file> is missing/empty, C<'no URIs to save ...'> if there
5975 is no URI list (navigate first, or pass C<\@uris> explicitly), or a
5976 filesystem error. Cookie I<expiry> is deliberately not part of the saved
5977 data -- see L</"LIMITATIONS">. Returns C<$b>.
5978  
5979 =head3 load_cookies
5980  
5981 $b->load_cookies($file, sub { my ($loaded, $err) = @_; ... });
5982  
5983 Reads C<$file> (as written by C<save_cookies>, UTF-8 text) and replays each
5984 row through C<set_cookie>. C<$loaded> is the number successfully
5985 re-applied. If the file doesn't exist, or exists but isn't valid JSON, this
5986 is not an error -- C<$loaded> is simply C<0>. Individual rows are treated
5987 the same way: a row that isn't a hashref, or is missing C<name>/C<value>/
5988 C<domain>, is silently skipped rather than failing the whole load --
5989 C<$loaded> only counts rows that were actually well-formed. Every cookie in a
5990 snapshot this module wrote is loaded back as a session cookie, even if it had
5991 an expiry when saved -- C<save_cookies> cannot read expiries back out of
5992 WebKit, so it never records one (see L</"LIMITATIONS">). A hand-written
5993 snapshot B<may> carry an C<expires> key (epoch seconds), and that one is
5994 honoured: the cookie is restored with its remaining lifetime and, in a
5995 C<cookie_jar> session, persists across restarts. Errors with
5996 C<'snapshot file required'> if C<$file> is missing/empty. Returns C<$b>.
5997  
5998 =head2 User content injection
5999  
6000 Inject your own JavaScript and CSS into the pages this instance loads.
6001  
6002 =head3 add_user_script
6003  
6004 my $h = $b->add_user_script($js, %opts);
6005  
6006 Inject C<$js> into every page this instance loads, from the B<next> navigation
6007 onward (WebKit injects user content at load time, so it does not affect the page
6008 already showing). Returns an L</EV::WebKit::UserContent> handle whose C<remove>
6009 takes just this script back out.
6010  
6011 Options:
6012  
6013 =over 4
6014  
6015 =item at => 'end' (default) | 'start'
6016  
6017 When the script runs relative to the page's own scripts. C<start> runs before
6018 any page script -- but the DOM does not exist yet (C<document.body> is C<undef>),
6019 so a script that touches the DOM should use C<end>.
6020  
6021 =item world => 'main' (default) | 'isolated'
6022  
6023 C<main> shares the page's JavaScript globals (what the page's own code sees).
6024 C<isolated> gets a private global scope the page cannot read or corrupt, while
6025 still sharing the one DOM -- use it to observe or rewrite a page without the page
6026 noticing your variables.
6027  
6028 =item frames => 'all' (default) | 'top'
6029  
6030 Inject into all frames, or only the top-level document.
6031  
6032 =item allow => [ globs ], deny => [ globs ]
6033  
6034 Optional URL-pattern allow/deny lists (WebKit C<UserContentURLPattern> syntax). A
6035 pattern is C<scheme://host/path> with C<*> wildcards and B<must> include a path
6036 component (C<'https://*.example.com/*'>, not C<'https://*.example.com'>). With
6037 C<allow>, the script runs only on matching URLs; C<deny> excludes matching URLs;
6038 C<deny> wins over C<allow>. Each entry must be a non-empty string (undef, empty,
6039 and non-string entries croak); a syntactically malformed pattern is not caught
6040 here and simply never matches. Omit a list to match every URL -- an empty list
6041 (C<< allow => [] >>) is rejected rather than silently meaning match-all.
6042  
6043 =back
6044  
6045 C<$js> should be a decoded Perl character string (not raw bytes): it is handed to
6046 WebKit as UTF-8, so a byte string with high bytes would be re-encoded (mojibake).
6047  
6048 Croaks on a source that is undef, a reference, or contains a NUL byte (which would
6049 silently truncate the injected content); on an invalid option value or an unknown
6050 option key; and -- unlike the quiet-no-op mutators (see L</Lifecycle>) -- on a
6051 call after the browser is closed (there is no handle it could meaningfully return).
6052  
6053 =head3 add_user_style
6054  
6055 my $h = $b->add_user_style($css, %opts);
6056  
6057 Like L</add_user_script> but injects a CSS stylesheet. Accepts C<frames>,
6058 C<allow>, and C<deny> as above (no C<world> -- a world does not change how a
6059 stylesheet affects the document, so it is not surfaced), plus:
6060  
6061 =over 4
6062  
6063 =item level => 'author' (default) | 'user'
6064  
6065 C<author> mixes with the page's own author styles. C<user> is a user-agent-level
6066 override that beats page CSS -- use it to reliably hide elements
6067 (C<< 'div.ad { display:none !important }' >>).
6068  
6069 =back
6070  
6071 Returns an L</EV::WebKit::UserContent> handle.
6072  
6073 =head3 remove_all_user_scripts
6074  
6075 $b->remove_all_user_scripts;
6076  
6077 Remove every script added with L</add_user_script>. Does not touch the module's
6078 own internal injection (the element registry that L</find> and L</html> rely on).
6079 Chainable.
6080  
6081 =head3 remove_all_user_styles
6082  
6083 $b->remove_all_user_styles;
6084  
6085 Remove every stylesheet added with L</add_user_style>. Chainable.
6086  
6087 =head2 Fingerprinting
6088  
6089 See the C<fingerprint> constructor option above for the device-profile spoofing
6090 this exposes.
6091  
6092 =head3 fingerprint
6093  
6094 my $profile = $b->fingerprint; # resolved hashref, or undef
6095  
6096 The resolved fingerprint profile for this instance (read-only), or C<undef>.
6097  
6098 =head3 network_fingerprint
6099  
6100 my $target = $b->network_fingerprint; # e.g. 'chrome131', or undef
6101  
6102 The active curl-impersonate target, or C<undef> when the in-process proxy is not
6103 running. Note that C<on_request>/C<on_response> start that proxy too, and it
6104 always re-originates, so this reports a target (C<chrome131> by default) under
6105 those options as well -- see the C<network_fingerprint> constructor option
6106 above.
6107  
6108 =head3 proxy_port
6109  
6110 my $port = $b->proxy_port; # or undef
6111  
6112 The localhost port of the in-process re-origination proxy, or C<undef> when it
6113 is not running. As with C<network_fingerprint> above, C<on_request> and
6114 C<on_response> start it too.
6115  
6116 =head3 fingerprint_profiles
6117  
6118 my @names = EV::WebKit->fingerprint_profiles;
6119  
6120 The names of the shipped presets.
6121  
6122 =head3 fingerprint_available
6123  
6124 EV::WebKit::fingerprint_available() or warn "no fingerprint support";
6125  
6126 Whether the web-process extension was built at install.
6127  
6128 =head2 Lifecycle
6129  
6130 Tear the instance down.
6131  
6132 =head3 quit
6133  
6134 $b->quit;
6135  
6136 Tears down this instance: resolves every in-flight callback -- including a
6137 still-pending navigation -- exactly once with C<$err eq 'browser closed'>,
6138 destroys the native GTK window (the X display itself is left alone -- see
6139 L</"LIMITATIONS">), and drops the view/session/etc. Idempotent -- safe to
6140 call more than once, and run automatically from C<DESTROY>: an instance holds
6141 only weak references to itself from its native signal handlers, so a plain
6142 C<undef $b> or a scope exit collects it and tears it down (calling C<quit>)
6143 without an explicit call. Calling C<quit> yourself is still useful to release
6144 the native window/session B<promptly> and deterministically rather than
6145 whenever the instance is next collected. After
6146 C<quit>, any method that would otherwise run JavaScript (C<script>,
6147 C<script_async>, C<find>, C<find_all>, C<html>, and all L<EV::WebKit::Element>
6148 methods) resolves immediately with C<$err eq 'browser closed'>.
6149 Synchronous accessors (C<uri>, C<title>, C<is_loading>, C<user_agent>)
6150 instead degrade quietly after C<quit>, returning C<undef> (C<0> for
6151 C<is_loading>), and synchronous mutators (C<set_user_agent>, C<settings>,
6152 C<set_proxy>, C<mock_scheme>, C<show_devtools>) become no-ops that just
6153 return C<$b>.
6154  
6155 An operation already in flight at the moment C<quit> is called is resolved
6156 deterministically, exactly once, rather than left dangling. Every pending
6157 C<script>/C<script_async>/C<find>/C<find_all>/C<html>/C<screenshot>/C<pdf>
6158 call, cookie call, outstanding C<wait_for>, and navigation resolves with
6159 C<$err eq 'browser closed'>. Any call made I<after> C<quit> has returned
6160 likewise resolves immediately with C<'browser closed'>.
6161  
6162 C<quit> never throws. It has to run your callbacks in order to resolve them,
6163 and one of them dying must not abort the teardown -- that would drop every
6164 callback still queued behind it and leak the window, view and session for the
6165 life of the process (nothing could retry: C<quit> is already marked done). An
6166 exception from a callback is caught and reported with C<warn>.
6167  
6168 Calling C<quit> from inside an event handler (C<on_dialog>, C<on_policy>,
6169 C<on_console>, C<on_file_chooser>, C<on_download>, C<on_authenticate>, or a
6170 C<mock_scheme> producer) is safe. Those run inside WebKit's own dispatch frame, so C<quit>
6171 defers the teardown -- and the callbacks it resolves -- to the next clean tick
6172 of the loop rather than running them nested inside that frame, where an
6173 C<EV::break> from one of them would wedge the loop (see
6174 L</"CALLBACK CONVENTION">).
6175  
6176 C<'browser closed'> reports how the B<callback> was resolved, not whether
6177 the operation's effect took place. A cookie B<mutation> already in flight
6178 when C<quit> lands -- C<set_cookie>, C<save_cookies> (which may still write
6179 its file), or C<clear_cookies> -- can still complete its native effect even
6180 though its callback reports C<'browser closed'>, because cancelling it
6181 mid-flight would risk a use-after-free during teardown. Treat
6182 C<'browser closed'> on an in-flight mutation as "outcome unknown", not
6183 "did not happen". (This does not apply to calls made I<after> C<quit>, which
6184 never start any native work.)
6185  
6186 =head2 Handler accessors
6187  
6188 my $cb = $b->on_console; # get
6189 $b->on_console(sub { ... }); # set, returns $b
6190 $b->on_console(undef); # clear
6191  
6192 Ten of the twelve C<on_*> handlers have a get/set accessor: C<on_load>,
6193 C<on_error>, C<on_close>, C<on_navigate>, C<on_console>, C<on_dialog>,
6194 C<on_policy>, C<on_file_chooser>, C<on_download> and C<on_authenticate>. The
6195 other two, C<on_request> and C<on_response>, are construct-time only -- they
6196 need the in-process proxy built during C<new> -- and have none.
6197  
6198 An accessor means code that did not construct the browser can still observe a
6199 handler, and can B<chain> an existing one rather than clobbering it:
6200  
6201 my $prev = $b->on_console;
6202 $b->on_console(sub { $prev->(@_) if $prev; ...also mine... });
6203  
6204 Croaks on a non-coderef. Enabling C<on_console> after a page has loaded takes
6205 effect from the B<next> navigation: the console proxy is a user script, and
6206 those are injected at document start.
6207  
6208 =head1 EVENTS
6209  
6210 Optional callbacks passed to C<new>, and the one option that shapes what the
6211 browser does when it has none (C<popups>):
6212  
6213 =over 4
6214  
6215 =item C<< on_error => sub { my ($err) = @_ } >>
6216  
6217 Called for a navigation failure that has no C<go>/C<load_html> callback
6218 waiting for it (e.g. a stray C<load-failed> signal). Ordinary navigation
6219 failures go to that call's own callback instead, not here.
6220  
6221 =item C<< on_load => sub { } >>
6222  
6223 Called with no arguments when a navigation started through this API
6224 (C<go>, C<load_html>, C<back>, C<forward>, or C<reload>) finishes
6225 successfully, right after that navigation's own callback (if any). It does
6226 NOT fire for user- or page-JS-initiated navigations (e.g. clicking a link,
6227 or a script-driven redirect) -- only for navigations this instance itself
6228 started through one of the methods above.
6229  
6230 =item C<< on_console => sub { my ($text) = @_ } >>
6231  
6232 Called for each C<console.log>/C<warn>/C<error>/C<info> from page
6233 JavaScript. C<$text> is a single string of the form C<"$level: $args">,
6234 e.g. C<"log: hi">. Implemented by monkey-patching C<console> via an
6235 injected user script plus a script-message handler, not WebKit's native
6236 console-message signal.
6237  
6238 =item C<< on_dialog => sub { my ($dialog) = @_ } >>
6239  
6240 Called for C<window.alert>/C<confirm>/C<prompt> and the beforeunload
6241 confirmation. C<$dialog> is an L</"EV::WebKit::Dialog"> object, valid only
6242 for the duration of this call. If C<on_dialog> is not given, every dialog
6243 is auto-dismissed so the page is never blocked.
6244  
6245 =item C<< on_navigate => sub { my ($uri) = @_ } >>
6246  
6247 Called for B<every> navigation that commits, whoever started it -- including one
6248 the page starts itself, which is what a human clicking a link in a visible
6249 window looks like.
6250  
6251 C<on_load> is not that. It fires only for a navigation this API started, so
6252 without C<on_navigate> a browser you are also using by hand can change page and
6253 tell you nothing at all. An API navigation fires both.
6254  
6255 Delivered on a clean EV tick, so C<EV::break> is safe from it.
6256  
6257 =item C<< on_close => sub { } >>
6258  
6259 Called when the B<user> closes the window (the titlebar close button, alt-F4,
6260 the window manager) -- not when you call C<quit> yourself. Only reachable in
6261 the visible mode (a real C<$DISPLAY>, usually with C<< chrome => 1 >>).
6262  
6263 The instance is torn down first: every in-flight callback resolves with
6264 C<'browser closed'>, the native window is destroyed, and only then is
6265 C<on_close> called. So by the time it runs, C<$b> is already closed -- it is a
6266 notification, not a veto.
6267  
6268 It does B<not> stop your C<EV::run> -- nothing in this module ever does; you
6269 own the loop. For a browser window whose closing should end the program, that
6270 is the whole handler:
6271  
6272 my $b = EV::WebKit->new(chrome => 1, on_close => sub { EV::break });
6273 ...
6274 EV::run; # returns when the window is closed
6275  
6276 Unlike C<on_console>/C<on_dialog>/C<on_policy>, C<on_close> is delivered on a
6277 clean EV tick, so calling C<EV::break> directly from it is safe.
6278  
6279 =item C<< popups => 'follow' | 'block' >>
6280  
6281 What to do with a navigation that asks for a new window -- a C<target="_blank">
6282 link, or C<window.open>. WebKit allows such a navigation and then asks for a
6283 window to put it in; a one-view browser has none to give, so the click would
6284 otherwise do nothing whatsoever: no navigation, no error, no event. The default
6285 C<'follow'> takes it in this view instead. C<'block'> keeps it dropped.
6286  
6287 The two arrive by different routes, which matters if you set C<on_policy>. A
6288 C<target="_blank"> link is a policy decision, so that handler sees it first,
6289 with C<< type => 'new-window-action' >>, and can refuse it outright with
6290 C<< $p->block >>.
6291  
6292 C<window.open> is B<not> a window request WebKitGTK asks about, so no
6293 C<new-window-action> ever arrives for it -- there is nothing to refuse at that
6294 stage. Under the default C<'follow'>, though, the popup is re-issued in this
6295 view as an ordinary navigation, and that B<does> reach C<on_policy> as a
6296 C<navigation-action> carrying the popup's own url. So selective filtering is
6297 possible for both mechanisms; only the decision C<type> differs. (Under
6298 C<'block'> the popup is dropped before any navigation, so C<on_policy> sees
6299 nothing at all.)
6300  
6301 One caveat if you are testing this: WebKit's own popup blocker drops a
6302 C<window.open> made from an inline script with no user gesture behind it, and
6303 then nothing reaches C<on_policy> either. Drive it from a real click --
6304 C<< $el->click >> counts -- as a page would.
6305  
6306 What C<on_policy> does not decide is B<where> an allowed one goes: WebKit asks
6307 for a window afterwards either way, and this option is what answers. So an
6308 C<on_policy> that allows a C<target="_blank"> link still lands it in this view
6309 under C<'follow'>, and still drops it under C<'block'>. If you want to route it
6310 yourself, C<< $p->block >> and navigate from a clean tick -- starting a
6311 navigation inside the handler runs it in WebKit's own dispatch frame.
6312  
6313 =item C<< on_policy => sub { my ($info) = @_ } >>
6314  
6315 Called for each navigation/new-window/response decision WebKit asks about.
6316 C<$info> is an L</"EV::WebKit::Policy"> object, valid only for the duration
6317 of this call. If C<on_policy> is not given, WebKit's own default (allow)
6318 applies; if the handler doesn't call C<allow>/C<block>, allow happens
6319 automatically once it returns.
6320  
6321 If the handler B<dies> before deciding, the navigation is B<blocked> and the
6322 exception reported with C<warn>. This handler is a gate, so it fails closed:
6323 a page that could provoke a die (a URI that breaks the handler's own parsing,
6324 say) would otherwise walk straight through it, since an exception escaping
6325 the handler leaves WebKit to apply its own default -- allow. A handler that
6326 already called C<allow> or C<block> keeps that decision even if it then dies.
6327  
6328 =item C<< on_download => sub { my ($download) = @_ } >>
6329  
6330 Called when the page starts a download. The handler must name a destination
6331 with C<save_to> or the download is cancelled -- see L</"on_download"> under
6332 L</"Downloads and file upload"> for the object's full interface and the
6333 reasoning.
6334  
6335 =item C<< on_file_chooser => sub { my ($chooser) = @_ } >>
6336  
6337 Called when the page opens a file chooser, which is the only way to populate
6338 an C<< <input type=file> >>. Without this handler WebKit runs its own native
6339 chooser, unchanged. See L</"on_file_chooser"> for the object it receives.
6340  
6341 =item C<< on_authenticate => sub { my ($auth) = @_ } >>
6342  
6343 Answer an HTTP or proxy authentication challenge. Without a handler the
6344 challenge is cancelled and the navigation fails at once rather than waiting.
6345 See L</"on_authenticate">.
6346  
6347 =item C<< on_request => sub { my ($req) = @_ } >>
6348  
6349 Intercept, rewrite, mock or block every request the browser makes. Routes
6350 through the in-process proxy, so it does not see local-address traffic and it
6351 sets a connection fingerprint -- see L</"on_request"> for both caveats.
6352  
6353 =item C<< on_response => sub { my ($res) = @_ } >>
6354  
6355 Observe or rewrite each response's status and headers before the page sees
6356 them -- stripping C<Content-Security-Policy> is the usual reason. Same proxy,
6357 same caveats. See L</"on_response">.
6358  
6359 =back
6360  
6361 =head1 EV::WebKit::Dialog
6362  
6363 Passed to C<on_dialog>. Valid only for the duration of that call.
6364  
6365 =over 4
6366  
6367 =item C<type>
6368  
6369 Nick string: C<alert>, C<confirm>, C<prompt>, or C<before-unload-confirm>.
6370  
6371 =item C<message>
6372  
6373 The dialog's message text.
6374  
6375 =item C<accept($text)>
6376  
6377 Accept the dialog. For C<prompt>, C<$text> (if defined) becomes the entered
6378 value; for C<confirm>/C<before-unload-confirm>, marks it confirmed;
6379 C<alert> has nothing to set and this just acknowledges it.
6380  
6381 =item C<dismiss>
6382  
6383 Cancel the dialog (C<confirm>/C<before-unload-confirm> resolve false;
6384 C<alert>/C<prompt> just close).
6385  
6386 =back
6387  
6388 =head1 EV::WebKit::Policy
6389  
6390 Passed to C<on_policy>. Valid only for the duration of that call.
6391  
6392 =over 4
6393  
6394 =item C<uri>
6395  
6396 The request URI for this decision (best-effort; may be C<undef>).
6397  
6398 =item C<type>
6399  
6400 Nick string: C<navigation-action>, C<new-window-action>, or C<response>.
6401  
6402 =item C<allow>
6403  
6404 Let the navigation/response proceed.
6405  
6406 =item C<block>
6407  
6408 Cancel the navigation/response.
6409  
6410 =back
6411  
6412 =head1 EV::WebKit::Auth
6413  
6414 Passed to C<on_authenticate>. Valid only for the duration of that call.
6415  
6416 =over 4
6417  
6418 =item C<host>, C<port>, C<realm>, C<scheme>
6419  
6420 What is being asked for. C<scheme> is WebKit's own nick for the authentication
6421 scheme (C<http-basic>, C<http-digest>, ...); C<realm> is the server's realm
6422 string, which is what distinguishes two challenges from the same host.
6423  
6424 =item C<for_proxy>
6425  
6426 True when the challenge came from a proxy rather than the origin server.
6427  
6428 =item C<is_retry>
6429  
6430 True when the credentials you last supplied were B<rejected>. WebKit re-asks
6431 after every rejection, so a handler that answers with the same pair regardless
6432 of this loops forever.
6433  
6434 =item C<< login($user, $password, persist =E<gt> $how) >>
6435  
6436 Answer the challenge. C<persist> is C<'for-session'> (the default -- remembered
6437 until this instance closes, so the same realm is not asked again on every
6438 request), C<'permanent'> (written to the platform credential store), or
6439 C<'none'>.
6440  
6441 =item C<cancel>
6442  
6443 Refuse the challenge. This is also what happens if the handler returns without
6444 deciding, dies, or was never set at all.
6445  
6446 =back
6447  
6448 =head1 EV::WebKit::Download
6449  
6450 Passed to C<on_download>. B<Unlike> the dialog and policy objects, this one
6451 outlives the handler that received it: WebKit reports progress and completion
6452 later, so it stays valid until the download finishes, fails, or the browser
6453 closes.
6454  
6455 =over 4
6456  
6457 =item C<uri>
6458  
6459 The URI being downloaded.
6460  
6461 =item C<suggested>
6462  
6463 The filename the server suggested (from C<Content-Disposition>, else derived
6464 from the URI). Only known once WebKit asks for a destination, which is when
6465 C<on_download> runs -- so it is available there, and C<undef> before.
6466  
6467 =item C<save_to($path, overwrite =E<gt> $bool)>
6468  
6469 Choose where the download lands. B<Required>: a download whose handler names no
6470 destination is cancelled, because WebKit's own default would write into the
6471 user's Downloads directory behind the caller's back. C<$path> is a plain
6472 filesystem path (a C<file://> URI is accepted and stripped).
6473  
6474 =item C<on_finish($cb)>
6475  
6476 Register the completion callback: C<< $cb->($path, $err) >>. C<$path> is where
6477 the file landed; on failure C<$path> is C<undef> and C<$err> a message. Fires
6478 exactly once. Registering after the download has already finished still
6479 delivers, so there is no race in setting it late.
6480  
6481 =item C<destination>
6482  
6483 The path chosen by C<save_to>, or C<undef>.
6484  
6485 =item C<progress>
6486  
6487 Estimated completion, 0 to 1.
6488  
6489 =item C<received>
6490  
6491 Bytes received so far.
6492  
6493 =item C<cancel>
6494  
6495 Abort the download. C<on_finish> then reports the cancellation.
6496  
6497 =back
6498  
6499 =head1 EV::WebKit::FileChooser
6500  
6501 Passed to C<on_file_chooser>. Valid only for the duration of that call.
6502  
6503 =over 4
6504  
6505 =item C<select(@paths)>
6506  
6507 Answer the chooser with these files. Croaks on a path that does not exist, or
6508 on several paths when the input accepts only one -- WebKit itself would
6509 silently hand the page an unreadable entry instead.
6510  
6511 Note the page does not see the files B<immediately>: WebKit applies the
6512 selection asynchronously, so C<files.length> read in the callback of the
6513 C<click> that opened the chooser is still 0, and correct a tick later.
6514  
6515 =item C<cancel>
6516  
6517 Refuse the chooser. This is also what happens automatically if the handler
6518 returns without deciding, or dies -- an unanswered request would leave the page
6519 waiting on a chooser that never resolves.
6520  
6521 =item C<mime_types>
6522  
6523 The C<accept=> list as a plain list of strings; empty means anything.
6524  
6525 =item C<multiple>
6526  
6527 True if the input accepts more than one file.
6528  
6529 =item C<selected>
6530  
6531 Files already selected on the input, as a list.
6532  
6533 =back
6534  
6535 =head1 EV::WebKit::UserContent
6536  
6537 The handle returned by L</add_user_script> and L</add_user_style>.
6538  
6539 =head2 remove
6540  
6541 $h->remove;
6542  
6543 Remove just this injected script or stylesheet. Takes effect from the next
6544 navigation. Idempotent and safe: calling it twice, or after the browser has been
6545 closed or collected, is a harmless no-op.
6546  
6547 =head1 LIMITATIONS
6548  
6549 =over 4
6550  
6551 =item A small, fixed per-call residue in long-running processes
6552  
6553 Glib::Object::Introspection does not release a C<GAsyncReadyCallback> closure
6554 after it fires, so every asynchronous call leaves one closure shell behind for
6555 the life of the process. EV::WebKit clears everything it owns from inside those
6556 closures on completion -- your callback, the C<Cancellable>, the watchdog timer
6557 -- so nothing you pass in is retained; but the shell itself is GI's and cannot
6558 be freed from Perl. Measured at roughly 2kB per call, against roughly 68kB per
6559 call before the release was added.
6560  
6561 This is invisible in ordinary use and matters only for a process making
6562 hundreds of thousands of calls -- a poller running for days, where C<wait_for>
6563 and C<wait_for_js> spend one call per tick. If that is you, recycle the
6564 instance periodically: C<quit> and construct a new one.
6565  
6566 =item Bring-your-own-display
6567  
6568 EV::WebKit never spawns or kills an X server. Run under C<xvfb-run -a
6569 your-script.pl> for headless use, or export a real C<$DISPLAY> for a
6570 visible, fully-interactive GTK4 window -- the C<display> constructor option
6571 only sets C<$ENV{DISPLAY}> before GTK initializes, it does not start Xvfb.
6572  
6573 =item Cookie persistence
6574  
6575 C<cookie_jar> gives WebKit-native persistent cookie storage: cookies with a
6576 real expiry round-trip correctly (expiry included) across instances and
6577 processes. SESSION cookies (no expiry) are permanently excluded from that
6578 store by design (RFC 6265) -- C<save_cookies>/C<load_cookies> are the only
6579 way to snapshot/restore those (or any cookie; snapshots lose expiry, so
6580 every cookie loaded back from one becomes a session cookie regardless of
6581 what it was when saved). C<clear_cookies> clears the whole session, not a
6582 single domain/URI. WebKitGTK's own bulk "all cookies" enumeration
6583 (C<get_all_cookies>) is avoided entirely: a real memory-safety bug was
6584 independently confirmed under valgrind when such a call is left in-flight
6585 at teardown, so this module never calls it, using per-URI C<get_cookies>
6586 throughout instead.
6587  
6588 =item GDK backend
6589  
6590 C<GDK_BACKEND> is forced to C<x11> (unless already set) since this module
6591 targets X11/Xvfb; it is not tested against a Wayland-native GDK backend.
6592  
6593 =item Single EV loop
6594  
6595 Native EV watchers, the GLib main context (bridged in by L<EV::Glib>), and
6596 WebKitGTK's own IPC to its web/network processes all share one C<EV::run>.
6597 EV::WebKit delivers its result callbacks on a clean tick, so C<EV::break> is
6598 safe from those -- and from C<on_load>, C<on_error>, C<on_close> and
6599 C<on_navigate>.
6600  
6601 It is B<not> safe from the seven handlers that run nested inside WebKit's own
6602 dispatch frame: C<on_console>, C<on_dialog>, C<on_policy>, C<on_file_chooser>,
6603 C<on_download>, C<on_authenticate>, and a C<mock_scheme> producer. Breaking
6604 from one of those does not raise an error. The C<EV::run> you are in returns,
6605 and then the B<next> one blocks forever -- at 0% CPU, with live watchers that
6606 never fire, so the symptom is a script stopped dead rather than one spinning.
6607 Schedule it instead:
6608  
6609 EV::timer(0, 0, sub { EV::break })
6610  
6611 Calling C<quit> from them B<is> safe; it detects the frame and defers its own
6612 teardown. See L</"CALLBACK CONVENTION">.
6613  
6614 =item Overlapping navigation identity
6615  
6616 When navigations overlap -- a C<go> superseded by another C<go>, or by
6617 C<back>/C<forward>/C<reload>/C<load_html>, including a C<mock_scheme> producer
6618 that reentrantly navigates -- each callback is resolved by the navigation that
6619 asked for it, not by whatever happens to be pending when a signal arrives. The
6620 superseded one gets C<'superseded'>; the survivor gets its own outcome. A
6621 per-navigation timeout can never fire against the wrong navigation. This holds
6622 for both the failure and the success path, is confirmed live, and the gates
6623 that implement it are described at C<_finished_is_stray> and the C<load-failed>
6624 handler in the source, with F<xt/66-nav-finished.t> covering the success side.
6625  
6626 Two cases are irreducible, and neither changes the outcome a caller sees.
6627  
6628 If the superseded navigation was headed to the B<same uri> the new one is
6629 headed to, or already showing, the two cannot be told apart from WebKit's
6630 signals alone: a callback may be resolved by the wrong-but-identical event
6631 rather than by its own navigation. Since the uri is the same either way, the
6632 result delivered is still truthful.
6633  
6634 And a navigation with B<no tracked target uri> -- C<back>, C<forward>,
6635 C<reload>, C<load_html> -- that genuinely fails before its own C<started>
6636 fires, for a uri that was never superseded, cannot be told apart from a stray.
6637 That one has not been reproduced live and is not believed reachable:
6638 C<back>/C<forward> only proceed past C<can_go_back>/C<can_go_forward>, and
6639 C<load_html> always reaches C<started> for any markup.
6640  
6641 A same-document navigation is a different matter entirely -- it produces no
6642 C<load-changed> cycle for identity to work on, and resolves C<'timeout'>. See
6643 L</go>.
6644  
6645 =item Element registry isolation
6646  
6647 The C<find>/C<find_all> element registry (C<window.__evwk>) lives in a
6648 dedicated named JavaScript B<isolated world>, not the page's own main world.
6649 An isolated world has its own global object and its own built-in prototypes
6650 and shares only the DOM with the page, so page script cannot see or
6651 overwrite C<window.__evwk>, and every internal DOM call (C<find>,
6652 C<find_all>, C<wait_for>, C<html>, and all L<EV::WebKit::Element> methods)
6653 marshals its result with the world's B<own> C<JSON.stringify> and
6654 C<Object.prototype>. A hostile or buggy page that redefines C<JSON.stringify>
6655 or pollutes C<Object.prototype.toJSON> therefore cannot corrupt an element
6656 handle into pointing at the wrong node, nor stall a callback: those calls
6657 keep returning correct results regardless of what the page does to its own
6658 world. (C<find>/C<find_all> additionally shape-check every decoded result
6659 and surface a clean error rather than dereferencing anything unexpected,
6660 as defence in depth.)
6661  
6662 C<script> and C<script_async> are the deliberate exception: they run I<your>
6663 JavaScript in the page's main world so it can reach the page's own globals
6664 and libraries, and so their results are marshalled by the page's (possibly
6665 tampered) C<JSON.stringify>. That is inherent to running code in the page;
6666 a page that has redefined C<JSON.stringify> can make your own C<script>
6667 return a wrong value or a plain marshal error (never a hang). If you need a
6668 trustworthy result from an untrusted page, prefer C<find>/C<find_all> and
6669 the element accessors, which run in the isolated world.
6670  
6671 Each navigation gets a brand new registry (ids restart at C<0>) stamped
6672 with a fresh per-document epoch; every L<EV::WebKit::Element> handle
6673 carries the epoch of the registry it was created from, so a handle from a
6674 page you have since navigated away from is correctly detected as stale even
6675 though the new page's registry happens to reuse the same numeric id --
6676 see L<EV::WebKit::Element/"DESCRIPTION">. C<id> and C<epoch> are therefore
6677 reserved argument names for any JavaScript run through an
6678 L<EV::WebKit::Element> method.
6679  
6680 =item Async completion closures
6681  
6682 Several operations (C<script>, C<find>, C<find_all>, C<wait_for>,
6683 C<screenshot>, and the cookie methods) register their completion with
6684 WebKitGTK's asynchronous (C<GAsyncReadyCallback>-style)
6685 GObject-Introspection methods, which do not release the Perl closure
6686 passed to them once it fires. EV::WebKit is deliberately written around
6687 this: each such closure holds only a weak reference to the browser (or
6688 element), so instances become collectable shortly after C<quit> instead of
6689 only at interpreter exit. This is an internal implementation detail and
6690 requires nothing from calling code.
6691  
6692 =back
6693  
6694 =head1 REQUIREMENTS
6695  
6696 WebKitGTK 6.0, GTK4, JavaScriptCore 6.0 and libsoup3, with their
6697 GObject-Introspection typelibs (C<WebKit-6.0>, C<Gtk-4.0>, C<Gdk-4.0>,
6698 C<JavaScriptCore-6.0>, C<Soup-3.0>); L<Glib::Object::Introspection>,
6699 L<Glib>, L<Glib::IO>, L<EV>, L<EV::Glib>, L<File::ShareDir> and
6700 L<Cpanel::JSON::XS>.
6701 Xvfb (or a real X server) to actually run anything. Linux only.
6702  
6703 =head2 Running in a container
6704  
6705 WebKitGTK sandboxes its web process with bubblewrap, which needs to create
6706 user and network namespaces. Where it cannot -- most containers, and hosts
6707 that restrict unprivileged user namespaces -- the web process dies as soon as
6708 a page is needed, and the API call B<aborts the whole program> with C<SIGABRT>
6709 from inside the introspection layer. There is nothing this module can catch:
6710 by the time it happens the process is already going down. The symptom is
6711  
6712 ERROR **: Failed to fully launch dbus-proxy: Child process exited with code 1
6713 Aborted
6714  
6715 Two ways out. Give the container what bubblewrap needs -- for Docker or
6716 Podman, C<< --cap-add SYS_ADMIN >> or C<< --security-opt seccomp=unconfined >>,
6717 depending on the host -- or, if you accept losing the sandbox for a browser
6718 you are driving yourself,
6719  
6720 WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS=1
6721  
6722 That variable is exactly as dangerous as its name says: it removes WebKit's
6723 own isolation of the process that parses untrusted web content. Set it only
6724 where the browser visits content you control, or where the container is
6725 already the isolation boundary. The test suite detects this case and skips
6726 rather than aborting, naming the same fix.
6727  
6728 This distribution has no XS. It does compile one small shared object at
6729 install time -- the web-process extension behind C<fingerprint> and frame
6730 addressing -- needing only a C compiler and the glib/gobject C<pkg-config>
6731 files, B<not> the WebKit headers. Where that toolchain is absent, the build
6732 says so and installs anyway; everything except those two features works, and
6733 both then fail with an error that names the missing extension rather than
6734 hanging. L<EV::WebKit::Fingerprint/available> reports which you have.
6735  
6736 =head1 EXAMPLES
6737  
6738 Runnable scripts ship in C<eg/>. Each is headless under C<xvfb-run -a> and
6739 visible with a real C<$DISPLAY>.
6740  
6741 =over 4
6742  
6743 =item C<eg/scrape.pl>
6744  
6745 The commonest shape: navigate, pull structured data out of the DOM, save a
6746 screenshot. Start here -- it also shows which accessors are synchronous
6747 (C<title>, C<uri>) and which take a callback (everything that touches the page).
6748  
6749 =item C<eg/fingerprint.pl>
6750  
6751 Present as another device, then print what the page actually sees, side by side
6752 with what the profile claims. Takes a profile name.
6753  
6754 =item C<eg/element-shot.pl>
6755  
6756 Screenshot a single element, by cropping a full-page capture to its
6757 L<EV::WebKit::Element/box>. Uses L<Imager> if it is installed and says what it
6758 skipped if not. This is a recipe rather than an API because cropping needs an
6759 image library and this distribution does not depend on one for a single method.
6760  
6761 Worth reading for one detail even if you never crop anything: the scale between
6762 CSS pixels and captured pixels is B<measured> (image width against
6763 C<window.innerWidth>) rather than read from C<window.devicePixelRatio> -- which
6764 C<fingerprint> spoofs in JavaScript while the real rendering scale is unchanged,
6765 so trusting it would put the crop in the wrong place on a spoofed profile.
6766  
6767 =item C<eg/intercept.pl>
6768  
6769 Log, block, mock and rewrite requests through C<on_request>. Needs
6770 L<Proxy::Impersonate> 0.01 and a real external URI (local addresses bypass the
6771 proxy -- see L</on_request>).
6772  
6773 =item C<eg/browser.pl>
6774  
6775 A real browser window with chrome, optionally listening on a control socket so
6776 another process can drive it while you watch.
6777  
6778 =item C<eg/control.pl>
6779  
6780 The other end of that socket: drives a running browser from a separate process.
6781  
6782 =back
6783  
6784 =head1 SEE ALSO
6785  
6786 L<EV::WebKit::Element>, L<EV>, L<EV::Glib>, L<Glib::Object::Introspection>.
6787  
6788 L<Firefox::Marionette> is a similar-spirited Perl browser-automation module
6789 (for Firefox, via the Marionette protocol) that was a source of API-design
6790 inspiration for this one. The WebKitGTK 6.0 API reference is at
6791 L<https://webkitgtk.org/reference/webkitgtk/stable/>.
6792  
6793 =head1 AUTHOR
6794  
6795 vividsnow
6796  
6797 =head1 LICENSE
6798  
6799 This library is free software; you can redistribute it and/or modify it
6800 under the same terms as Perl itself.
6801  
6802 =cut
« WebKit/Client/Element.pm ↑ Summary