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