| 1 | package EV::WebKit::Element; | ||
| 2 | use v5.10; use strict; use warnings; | ||
| 3 | use Carp (); | ||
| 4 | our $VERSION = '0.05'; | ||
| 5 | |||
| 6 | # $frame is a web-process frame id when this element was found through a frame | ||
| 7 | # the main-frame script cannot reach; undef is the ordinary main-frame case. | ||
| 8 | # Every method routes on it (see _call_js), so a handle stays bound to the | ||
| 9 | # frame it came from. | ||
| 10 | sub _new { | ||
| 11 | my ($class, $browser, $id, $epoch, $frame) = @_; | ||
| 12 | bless { b => $browser, id => $id, epoch => $epoch, frame => $frame }, $class; | ||
| 13 | } | ||
| 14 | |||
| 15 | sub frame_id { $_[0]{frame} } | ||
| 16 | |||
| 17 | # attr/prop/type bind positionally (my ($s, $n, $cb) = @_), so a caller who omits | ||
| 18 | # the name leaves the CALLBACK sitting in the name slot -- and since a call with | ||
| 19 | # no callback is legal here, nothing complains: the coderef is quietly shipped to | ||
| 20 | # the JSON encoder, the encode dies inside a deferred timer where $EV::DIED only | ||
| 21 | # warns, and the caller waits forever for a result that is never coming. Croak | ||
| 22 | # instead, as every other method in this API does for a bad argument. | ||
| 23 | sub _need_name { | ||
| 24 | my ($what, $n) = @_; | ||
| 25 | Carp::croak("$what: a name is required") unless defined $n; | ||
| 26 | Carp::croak("$what: the name must be a plain string, not a " . ref($n) . ' reference' | ||
| 27 | . ($n && ref $n eq 'CODE' ? ' (did you omit the name and pass only a callback?)' : '')) | ||
| 28 | if ref $n; | ||
| 29 | return; | ||
| 30 | } | ||
| 31 | |||
| 32 | sub _call_js { | ||
| 33 | my ($self, $code, $args, $cb) = @_; | ||
| 34 | # Same synchronous croak every async EV::WebKit method makes, and for the | ||
| 35 | # same reason: a non-coderef callback would only blow up later, deep inside | ||
| 36 | # the completion, where the die is swallowed by $EV::DIED -- so the caller's | ||
| 37 | # EV::run just hangs, waiting for a callback that can never be invoked. | ||
| 38 | # Guarding here covers every method that reaches _call_js at once, rather | ||
| 39 | # than once per method. It matters most for find/find_all, which pass their | ||
| 40 | # OWN closure down, so the guard below would otherwise never see the | ||
| 41 | # caller's callback at all. (An omitted callback stays legal -- _defer no-ops.) | ||
| 42 | Carp::croak('callback must be a code reference') if defined $cb && ref $cb ne 'CODE'; | ||
| 43 | # 'id' and 'epoch' are reserved for this element's registry id/per- | ||
| 44 | # document epoch stamp and override any caller key -- epoch lets | ||
| 45 | # window.__evwk.get() detect a handle from a page that has since been | ||
| 46 | # navigated away from, even if the new page's registry reused the same | ||
| 47 | # numeric id (see EV::WebKit's $BOOT script). | ||
| 48 | my $a = { %{ $args // {} }, id => $self->{id}, epoch => $self->{epoch} }; | ||
| 49 | # An element found inside a frame must be operated on IN that frame: its | ||
| 50 | # registry entry lives in that frame's world, where the main frame cannot | ||
| 51 | # see it -- which is the whole reason the handle carries a frame id. | ||
| 52 | return $self->{b}->_call_js_frame($self->{frame}, $code, $a, $cb) if defined $self->{frame}; | ||
| 53 | $self->{b}->_call_js($code, $a, $cb); | ||
| 54 | } | ||
| 55 | |||
| 56 | sub text { $_[0]->_call_js('return window.__evwk.get(A.id, A.epoch).textContent;', {}, $_[1]) } | ||
| 57 | sub html { $_[0]->_call_js('return window.__evwk.get(A.id, A.epoch).innerHTML;', {}, $_[1]) } | ||
| 58 | sub value { $_[0]->_call_js('return window.__evwk.get(A.id, A.epoch).value;', {}, $_[1]) } | ||
| 59 | sub tag { $_[0]->_call_js('return window.__evwk.get(A.id, A.epoch).tagName.toLowerCase();', {}, $_[1]) } | ||
| 60 | sub attr { my ($s,$n,$cb)=@_; _need_name(attr => $n); $s->_call_js('return window.__evwk.get(A.id, A.epoch).getAttribute(A.name);', {name=>$n}, $cb) } | ||
| 61 | sub prop { my ($s,$n,$cb)=@_; _need_name(prop => $n); $s->_call_js('return window.__evwk.get(A.id, A.epoch)[A.name];', {name=>$n}, $cb) } | ||
| 62 | |||
| 63 | sub is_visible { | ||
| 64 | $_[0]->_call_js( | ||
| 65 | 'const el = window.__evwk.get(A.id, A.epoch); const s = getComputedStyle(el);' | ||
| 66 | . 'return s.display !== "none" && s.visibility !== "hidden" && el.getClientRects().length > 0;', | ||
| 67 | {}, $_[1]); | ||
| 68 | } | ||
| 69 | |||
| 70 | sub find { | ||
| 71 | my ($s, $sel, $cb) = @_; | ||
| 72 | # These two pass their OWN closure to _call_js, so its callback guard sees a | ||
| 73 | # coderef either way and cannot check the caller's -- guard here too, or a | ||
| 74 | # non-coderef $cb dies inside the completion below, where $EV::DIED eats it | ||
| 75 | # and the caller's EV::run hangs forever. | ||
| 76 | Carp::croak('find: last argument must be a callback') if ref $cb ne 'CODE'; | ||
| 77 | # The same guard the browser's own find() has. Without it a JSON null (or an | ||
| 78 | # omitted selector) marshalled through to querySelector, which coerces it to | ||
| 79 | # the TYPE selector "null" -- so find(undef) answered "not found" instead of | ||
| 80 | # complaining, indistinguishable from a selector that simply did not match. | ||
| 81 | # Reachable over the control socket too: el.find with a:[null] is one | ||
| 82 | # argument, so the arity guard passes it. | ||
| 83 | EV::WebKit::_need_selector(find => $sel); | ||
| 84 | # This wrapper closure is captured strongly by the (permanently | ||
| 85 | # GI-retained) _call_js completion closure -- but UNLIKE _call_js/ | ||
| 86 | # EV::WebKit::find's own $self (the browser, always independently held | ||
| 87 | # by the caller's own long-lived variable in practice), $s (an Element) | ||
| 88 | # is frequently held ONLY via this closure's own capture -- e.g. several | ||
| 89 | # sibling calls issued off the same $el, where none of the sibling | ||
| 90 | # closures happen to mention $el by name, so nothing else keeps it | ||
| 91 | # reachable during the async gap (confirmed: weakening $s here, mirroring | ||
| 92 | # the find()/wait_for() fix, broke exactly that pattern -- t/41's 9 | ||
| 93 | # concurrent $d->... calls). So $s must stay STRONGLY captured while the | ||
| 94 | # call is in flight; instead, break the retention at a single resolution | ||
| 95 | # point, explicitly undef'ing our OWN copy the instant we're done needing | ||
| 96 | # it (same "single resolution point" shape as wait_for's $finish) -- this | ||
| 97 | # releases $s (and transitively $s->{b}, the browser) from THIS closure | ||
| 98 | # without affecting any sibling closure's own (still-strong) copy. | ||
| 99 | $s->_call_js('const el = window.__evwk.get(A.id, A.epoch).querySelector(A.sel); return el ? { evwk_id: window.__evwk.put(el), evwk_epoch: window.__evwk.epoch } : null;', | ||
| 100 | { sel => $sel }, | ||
| 101 | sub { | ||
| 102 | my ($r, $err) = @_; | ||
| 103 | # A hostile/buggy page can make ANY JS value come back here (e.g. | ||
| 104 | # Object.prototype.toJSON polluted to return something else | ||
| 105 | # entirely) -- never trust the decoded shape before dereferencing | ||
| 106 | # it: an unvalidated $r->{evwk_id} below would die inside | ||
| 107 | # _defer's bare EV::timer(0,0,...), which EV's default $EV::DIED | ||
| 108 | # swallows to stderr, permanently dropping this callback (a | ||
| 109 | # silent hang, not an error) instead of ever reaching the caller. | ||
| 110 | if (!$err && defined $r && !(ref $r eq 'HASH' && defined $r->{evwk_id})) { | ||
| 111 | $err = 'find: unexpected result from page (registry tampered?)'; | ||
| 112 | } | ||
| 113 | my $result = (!$err && defined $r) ? EV::WebKit::Element->_new($s->{b}, $r->{evwk_id}, $r->{evwk_epoch}, $s->{frame}) : undef; | ||
| 114 | undef $s; | ||
| 115 | $cb->($result, $err); | ||
| 116 | }); | ||
| 117 | } | ||
| 118 | |||
| 119 | sub find_all { | ||
| 120 | my ($s, $sel, $cb) = @_; | ||
| 121 | Carp::croak('find_all: last argument must be a callback') if ref $cb ne 'CODE'; | ||
| 122 | EV::WebKit::_need_selector(find_all => $sel); | ||
| 123 | # same reasoning as find() above. | ||
| 124 | $s->_call_js('return [...window.__evwk.get(A.id, A.epoch).querySelectorAll(A.sel)].map(e => ({ evwk_id: window.__evwk.put(e), evwk_epoch: window.__evwk.epoch }));', | ||
| 125 | { sel => $sel }, | ||
| 126 | sub { | ||
| 127 | my ($r, $err) = @_; | ||
| 128 | # same shape distrust as find() above -- a tampered result (e.g. | ||
| 129 | # the whole array replaced, or containing non-descriptor | ||
| 130 | # elements) must degrade to a clean error, never dereference | ||
| 131 | # blind and die inside _defer's unguarded timer. | ||
| 132 | if (!$err && !(ref $r eq 'ARRAY' && !grep { ref $_ ne 'HASH' || !defined $_->{evwk_id} } @$r)) { | ||
| 133 | $err = 'find_all: unexpected result from page (registry tampered?)'; | ||
| 134 | } | ||
| 135 | my $result = $err ? undef : [ map { EV::WebKit::Element->_new($s->{b}, $_->{evwk_id}, $_->{evwk_epoch}, $s->{frame}) } @$r ]; | ||
| 136 | undef $s; | ||
| 137 | $cb->($result, $err); | ||
| 138 | }); | ||
| 139 | } | ||
| 140 | |||
| 141 | # A bare el.click() dispatches ONLY a click event, so a control whose handler is | ||
| 142 | # on mousedown/pointerdown -- custom dropdowns, menus, sliders, most | ||
| 143 | # design-system widgets -- did not respond at all, and this still reported | ||
| 144 | # success. Press first, then click, using hover's dictionary so the two agree | ||
| 145 | # about pointerType/isPrimary. Skipped for a disabled control, because no engine | ||
| 146 | # dispatches mouse events to one and firing them here would let a test drive | ||
| 147 | # something a person could not. | ||
| 148 | sub click { | ||
| 149 | $_[0]->_call_js( | ||
| 150 | 'const el = window.__evwk.get(A.id, A.epoch);' | ||
| 151 | . 'const r = el.getBoundingClientRect();' | ||
| 152 | . 'const at = { bubbles:true, cancelable:true, composed:true, view:window,' | ||
| 153 | . ' pointerType:"mouse", pointerId:1, isPrimary:true, button:0,' | ||
| 154 | . ' clientX: r.left + r.width/2, clientY: r.top + r.height/2 };' | ||
| 155 | . 'const off = el.disabled === true' | ||
| 156 | . ' || !!(el.closest && el.closest("fieldset[disabled]") && !el.closest("legend"));' | ||
| 157 | . 'if (!off) {' | ||
| 158 | . ' const P = window.PointerEvent || MouseEvent;' | ||
| 159 | . ' el.dispatchEvent(new P("pointerdown", {...at, buttons:1}));' | ||
| 160 | . ' el.dispatchEvent(new MouseEvent("mousedown", {...at, buttons:1}));' | ||
| 161 | . ' el.dispatchEvent(new P("pointerup", {...at, buttons:0}));' | ||
| 162 | . ' el.dispatchEvent(new MouseEvent("mouseup", {...at, buttons:0}));' | ||
| 163 | . '}' | ||
| 164 | # click() last, and unconditionally: it is what activates a link or submits | ||
| 165 | # a form, and on a disabled control the engine makes it the no-op it should be. | ||
| 166 | . 'el.click();' | ||
| 167 | . 'return true;', | ||
| 168 | {}, $_[1]); | ||
| 169 | } | ||
| 170 | |||
| 171 | sub focus { $_[0]->_call_js('window.__evwk.get(A.id, A.epoch).focus(); return true;', {}, $_[1]) } | ||
| 172 | |||
| 173 | sub type { | ||
| 174 | my ($s, $text, $cb) = @_; | ||
| 175 | _need_name(type => $text); # same positional-binding trap as attr/prop -- see there | ||
| 176 | $s->_call_js( | ||
| 177 | 'const el = window.__evwk.get(A.id, A.epoch); const tag = el.tagName;' | ||
| 178 | . 'if (tag === "INPUT" || tag === "TEXTAREA") {' | ||
| 179 | . ' el.focus(); el.value = (el.value || "") + A.text;' | ||
| 180 | . ' el.dispatchEvent(new Event("input", {bubbles:true}));' | ||
| 181 | . ' el.dispatchEvent(new Event("change", {bubbles:true}));' | ||
| 182 | . '} else if (el.isContentEditable) {' | ||
| 183 | . ' el.focus(); el.textContent = (el.textContent || "") + A.text;' | ||
| 184 | . ' el.dispatchEvent(new InputEvent("input", {bubbles:true}));' | ||
| 185 | . '} else { throw new Error("element is not editable"); }' | ||
| 186 | . 'return true;', | ||
| 187 | { text => $text }, $cb); | ||
| 188 | } | ||
| 189 | *send_keys = \&type; | ||
| 190 | |||
| 191 | sub clear { | ||
| 192 | $_[0]->_call_js( | ||
| 193 | 'const el = window.__evwk.get(A.id, A.epoch); const tag = el.tagName;' | ||
| 194 | . 'if (tag === "INPUT" || tag === "TEXTAREA") {' | ||
| 195 | . ' el.value = "";' | ||
| 196 | . ' el.dispatchEvent(new Event("input", {bubbles:true}));' | ||
| 197 | . '} else if (el.isContentEditable) {' | ||
| 198 | . ' el.textContent = "";' | ||
| 199 | . ' el.dispatchEvent(new InputEvent("input", {bubbles:true}));' | ||
| 200 | . '} else { throw new Error("element is not editable"); }' | ||
| 201 | . 'return true;', | ||
| 202 | {}, $_[1]); | ||
| 203 | } | ||
| 204 | |||
| 205 | sub submit { | ||
| 206 | $_[0]->_call_js( | ||
| 207 | 'const el = window.__evwk.get(A.id, A.epoch); const f = el.form || el;' | ||
| 208 | . 'const W = el.ownerDocument.defaultView;' | ||
| 209 | . 'if (f instanceof W.HTMLFormElement) W.HTMLFormElement.prototype.submit.call(f);' | ||
| 210 | . 'return true;', | ||
| 211 | {}, $_[1]); | ||
| 212 | } | ||
| 213 | |||
| 214 | # Bring the element into the viewport. Not merely a convenience: click() on an | ||
| 215 | # off-screen element works in the DOM but a page that reacts to scroll position | ||
| 216 | # (lazy images, sticky headers, infinite scroll) will not have done its work | ||
| 217 | # yet, so a subsequent read sees the pre-scroll state. | ||
| 218 | # | ||
| 219 | # behavior:"instant" is load-bearing: under a page's own CSS | ||
| 220 | # `scroll-behavior: smooth` the scroll ANIMATES, and this would resolve with the | ||
| 221 | # viewport still travelling -- so the reads it exists to make correct happen at | ||
| 222 | # the wrong offset. | ||
| 223 | sub scroll_into_view { | ||
| 224 | $_[0]->_call_js( | ||
| 225 | 'const el = window.__evwk.get(A.id, A.epoch);' | ||
| 226 | . 'el.scrollIntoView({block:"center", inline:"center", behavior:"instant"});' | ||
| 227 | . 'return true;', | ||
| 228 | {}, $_[1]); | ||
| 229 | } | ||
| 230 | |||
| 231 | # Hover. A real pointer entering an element produces pointerover/mouseover (which | ||
| 232 | # bubble) AND pointerenter/mouseenter (which do NOT), then a move; menus and | ||
| 233 | # tooltips variously listen for any of them, so sending only mouseover leaves a | ||
| 234 | # menu that opens on mouseenter shut. isTrusted is false for all of these -- a | ||
| 235 | # page checking it is not fooled (documented in the Ceiling). | ||
| 236 | sub hover { | ||
| 237 | $_[0]->_call_js( | ||
| 238 | 'const el = window.__evwk.get(A.id, A.epoch);' | ||
| 239 | . 'const r = el.getBoundingClientRect();' | ||
| 240 | # A PointerEvent built without these reports pointerType "" and isPrimary | ||
| 241 | # false, so a menu branching on the device takes the wrong branch -- which | ||
| 242 | # is the class of menu this method exists to open. MouseEventInit has no | ||
| 243 | # such members and WebIDL ignores unknown ones, so one dictionary serves | ||
| 244 | # both constructors. | ||
| 245 | . 'const at = { bubbles:true, cancelable:true, view:window,' | ||
| 246 | . ' pointerType:"mouse", pointerId:1, isPrimary:true,' | ||
| 247 | . ' clientX: r.left + r.width/2, clientY: r.top + r.height/2 };' | ||
| 248 | . 'for (const t of ["pointerover","mouseover"]) {' | ||
| 249 | . ' el.dispatchEvent(new (window.PointerEvent && t[0] === "p" ? PointerEvent : MouseEvent)(t, at)); }' | ||
| 250 | . 'for (const t of ["pointerenter","mouseenter"]) {' | ||
| 251 | . ' el.dispatchEvent(new (window.PointerEvent && t[0] === "p" ? PointerEvent : MouseEvent)(t, {...at, bubbles:false})); }' | ||
| 252 | . 'el.dispatchEvent(new MouseEvent("mousemove", at));' | ||
| 253 | . 'return true;', | ||
| 254 | {}, $_[1]); | ||
| 255 | } | ||
| 256 | |||
| 257 | # Select an <option> by value, or by visible label when no value matches. Setting | ||
| 258 | # el.value alone is not enough: every framework binds to input/change, so a | ||
| 259 | # silent assignment updates the DOM and leaves the application state stale. | ||
| 260 | sub select_option { | ||
| 261 | my ($s, $value, $cb) = @_; | ||
| 262 | _need_name(select_option => $value); # same positional-binding trap as attr/prop | ||
| 263 | # Stringify before the JSON bridge: an option's value is always a string in | ||
| 264 | # the DOM and the match below is ===, so an integer crossed as a JSON number | ||
| 265 | # and select_option(5) failed to find <option value="5">. | ||
| 266 | $value = "$value"; | ||
| 267 | $s->_call_js( | ||
| 268 | 'const el = window.__evwk.get(A.id, A.epoch);' | ||
| 269 | . 'if (!(el instanceof HTMLSelectElement || el instanceof el.ownerDocument.defaultView.HTMLSelectElement)) throw new Error("element is not a <select>");' | ||
| 270 | . 'const opts = [...el.options];' | ||
| 271 | . 'let i = opts.findIndex(o => o.value === A.value);' | ||
| 272 | . 'if (i < 0) i = opts.findIndex(o => (o.label || o.textContent || "").trim() === A.value);' | ||
| 273 | . 'if (i < 0) throw new Error("no option with value or label " + JSON.stringify(A.value));' | ||
| 274 | . 'el.selectedIndex = i;' | ||
| 275 | . 'el.dispatchEvent(new Event("input", {bubbles:true}));' | ||
| 276 | . 'el.dispatchEvent(new Event("change", {bubbles:true}));' | ||
| 277 | . 'return opts[i].value;', | ||
| 278 | { value => $value }, $cb); | ||
| 279 | } | ||
| 280 | |||
| 281 | # Set a checkbox/radio to $on (default true). click() would TOGGLE, so calling it | ||
| 282 | # twice to "make sure" silently undoes itself; this is idempotent by construction | ||
| 283 | # and a no-op (no events) when the box is already in the requested state, which is | ||
| 284 | # also what a real user clicking an already-checked radio produces. | ||
| 285 | sub check { | ||
| 286 | my ($s, @arg) = @_; | ||
| 287 | my $cb = (@arg && ref $arg[-1] eq 'CODE') ? pop @arg : undef; | ||
| 288 | # Two leftover arguments means a mistyped callback in the state position | ||
| 289 | # followed by the real one. A SINGLE leftover is the state, whatever it is: | ||
| 290 | # decoded-JSON booleans are blessed scalar refs, and croaking on those would | ||
| 291 | # reject the most ordinary source of a boolean this API has. | ||
| 292 | Carp::croak('check: takes at most a state and a callback') if @arg > 1; | ||
| 293 | my $on = @arg ? ($arg[0] ? 1 : 0) : 1; | ||
| 294 | $s->_call_js( | ||
| 295 | 'const el = window.__evwk.get(A.id, A.epoch);' | ||
| 296 | . 'if (!(el instanceof HTMLInputElement || el instanceof el.ownerDocument.defaultView.HTMLInputElement) || !/^(checkbox|radio)$/.test(el.type))' | ||
| 297 | . ' throw new Error("element is not a checkbox or radio");' | ||
| 298 | . 'if (el.checked === !!A.on) return !!A.on;' | ||
| 299 | . 'el.checked = !!A.on;' | ||
| 300 | . 'el.dispatchEvent(new Event("input", {bubbles:true}));' | ||
| 301 | . 'el.dispatchEvent(new Event("change", {bubbles:true}));' | ||
| 302 | . 'return !!A.on;', | ||
| 303 | { on => $on }, $cb); | ||
| 304 | } | ||
| 305 | sub uncheck { | ||
| 306 | my ($s, $cb) = @_; | ||
| 307 | Carp::croak('uncheck: callback must be a code reference') if defined $cb && ref $cb ne 'CODE'; | ||
| 308 | $s->check(0, $cb ? ($cb) : ()); | ||
| 309 | } | ||
| 310 | |||
| 311 | # Geometry, as a hashref: x/y/width/height/top/left/bottom/right plus the | ||
| 312 | # page-relative page_x/page_y. Viewport-relative like getBoundingClientRect | ||
| 313 | # itself, which is what a caller comparing against a screenshot wants; page_x/y | ||
| 314 | # add the scroll offset for anyone who needs absolute document coordinates. | ||
| 315 | # | ||
| 316 | # An element that is not rendered at all (display:none, or detached) has a rect | ||
| 317 | # of all zeros in every browser. Reporting that as a box would be a lie a caller | ||
| 318 | # could easily divide by, so it comes back undef instead, with is_visible left as | ||
| 319 | # the way to ask the question directly. | ||
| 320 | sub box { | ||
| 321 | $_[0]->_call_js( | ||
| 322 | 'const el = window.__evwk.get(A.id, A.epoch);' | ||
| 323 | . 'const r = el.getBoundingClientRect();' | ||
| 324 | . 'if (!r.width && !r.height && !r.x && !r.y) return null;' | ||
| 325 | . 'return { x: r.x, y: r.y, width: r.width, height: r.height,' | ||
| 326 | . ' top: r.top, left: r.left, bottom: r.bottom, right: r.right,' | ||
| 327 | . ' page_x: r.x + window.scrollX, page_y: r.y + window.scrollY };', | ||
| 328 | {}, $_[1]); | ||
| 329 | } | ||
| 330 | |||
| 331 | 1; | ||
| 332 | |||
| 333 | =pod | ||
| 334 | |||
| 335 | =head1 NAME | ||
| 336 | |||
| 337 | EV::WebKit::Element - a handle to a DOM element found by EV::WebKit | ||
| 338 | |||
| 339 | =head1 SYNOPSIS | ||
| 340 | |||
| 341 | $b->find('#login', sub { | ||
| 342 | my ($el, $err) = @_; | ||
| 343 | # A die inside an EV callback only reaches $EV::DIED, which warns and | ||
| 344 | # keeps going -- break instead. | ||
| 345 | if ($err) { warn "find failed: $err\n"; return EV::break } | ||
| 346 | if (!$el) { warn "no #login on this page\n"; return EV::break } | ||
| 347 | |||
| 348 | $el->type('alice', sub { | ||
| 349 | my (undef, $err) = @_; | ||
| 350 | if ($err) { warn "type failed: $err\n"; return EV::break } | ||
| 351 | $el->submit(sub { | ||
| 352 | my (undef, $err) = @_; | ||
| 353 | warn "submit failed: $err\n" if $err; | ||
| 354 | EV::break; | ||
| 355 | }); | ||
| 356 | }); | ||
| 357 | }); | ||
| 358 | |||
| 359 | =head1 DESCRIPTION | ||
| 360 | |||
| 361 | An EV::WebKit::Element is a handle to a single DOM node discovered via | ||
| 362 | L<EV::WebKit>'s C<find>, C<find_all>, C<find_js>, C<find_all_js> or | ||
| 363 | C<wait_for>, or (scoped to that element's descendants) its own C<find>/ | ||
| 364 | C<find_all> below. Internally it is just a | ||
| 365 | small page-side registry id, the per-document epoch stamp of the registry | ||
| 366 | it was created from, and a back-reference to the owning L<EV::WebKit> | ||
| 367 | browser -- not a live DOM reference held on the Perl side. Every method | ||
| 368 | runs JavaScript against that node asynchronously, on the same L<EV> loop as | ||
| 369 | the browser, and follows the browser's own callback convention: a trailing | ||
| 370 | C<sub { my ($result, $err) = @_; ... }>, C<$err> undef on success. See | ||
| 371 | L<EV::WebKit/"CALLBACK CONVENTION">. | ||
| 372 | |||
| 373 | Instances are only ever returned by L<EV::WebKit> methods; there is no | ||
| 374 | public constructor. | ||
| 375 | |||
| 376 | If the underlying DOM node has since been removed from the document, any | ||
| 377 | method call on that handle fails with a script error whose message | ||
| 378 | mentions "stale element". The same happens if navigation has replaced the | ||
| 379 | page entirely, even though the new page's own registry happens to reuse | ||
| 380 | the same numeric id the old handle had: each navigation re-injects a fresh | ||
| 381 | registry with a new epoch stamp, every handle carries the epoch it was | ||
| 382 | created with, and a mismatch is treated exactly like a removed node. | ||
| 383 | C<id> and C<epoch> are reserved argument names, always set by this class | ||
| 384 | internally, for every JavaScript snippet run through these methods. | ||
| 385 | |||
| 386 | A handle found through the C<< frame => { url => ... } >> form remembers B<which | ||
| 387 | frame> it came from, and every call on it runs there -- see | ||
| 388 | L<EV::WebKit/"Addressing an iframe">. A handle found through the selector form | ||
| 389 | (C<< frame => '#f' >>) does not: main-frame script walked C<contentDocument> to | ||
| 390 | reach it, and every call is made the same way. | ||
| 391 | |||
| 392 | Neither outlives its frame, but they say so differently: once the frame is | ||
| 393 | removed or the page navigates away, the first kind fails with C<frame is gone> | ||
| 394 | and the second with the ordinary C<stale element>. | ||
| 395 | |||
| 396 | =head1 METHODS | ||
| 397 | |||
| 398 | All methods below take a trailing C<sub { my ($result, $err) = @_; ... }> | ||
| 399 | callback. | ||
| 400 | |||
| 401 | =head2 text | ||
| 402 | |||
| 403 | $el->text($cb); | ||
| 404 | |||
| 405 | C<$result> is the node's C<textContent>. | ||
| 406 | |||
| 407 | =head2 html | ||
| 408 | |||
| 409 | $el->html($cb); | ||
| 410 | |||
| 411 | C<$result> is the node's C<innerHTML>. | ||
| 412 | |||
| 413 | =head2 value | ||
| 414 | |||
| 415 | $el->value($cb); | ||
| 416 | |||
| 417 | C<$result> is the form control's current C<value>. | ||
| 418 | |||
| 419 | =head2 tag | ||
| 420 | |||
| 421 | $el->tag($cb); | ||
| 422 | |||
| 423 | C<$result> is the node's lower-cased tag name, e.g. C<"div">. | ||
| 424 | |||
| 425 | =head2 attr | ||
| 426 | |||
| 427 | $el->attr($name, $cb); | ||
| 428 | |||
| 429 | C<$result> is the HTML attribute C<$name> (via C<getAttribute>), or | ||
| 430 | C<undef> if the attribute is not present. | ||
| 431 | |||
| 432 | =head2 prop | ||
| 433 | |||
| 434 | $el->prop($name, $cb); | ||
| 435 | |||
| 436 | C<$result> is the live JavaScript/DOM property C<$name> (e.g. | ||
| 437 | C<< prop('checked') >>), as opposed to C<attr>'s raw HTML attribute -- | ||
| 438 | useful when the two differ (checkbox C<checked> state, current vs default | ||
| 439 | C<value>, and so on). | ||
| 440 | |||
| 441 | =head2 is_visible | ||
| 442 | |||
| 443 | $el->is_visible($cb); | ||
| 444 | |||
| 445 | C<$result> is true if the element's computed C<display> is not C<none>, | ||
| 446 | its computed C<visibility> is not C<hidden>, and it has at least one client | ||
| 447 | rect (roughly: it takes up visible space in the rendered page). | ||
| 448 | |||
| 449 | =head2 find | ||
| 450 | |||
| 451 | $el->find($selector, $cb); | ||
| 452 | |||
| 453 | Scoped C<querySelector> under this element. C<$result> is an | ||
| 454 | L<EV::WebKit::Element> on a match, or C<undef> if nothing matched -- | ||
| 455 | not-found is not an error. | ||
| 456 | |||
| 457 | =head2 find_all | ||
| 458 | |||
| 459 | $el->find_all($selector, $cb); | ||
| 460 | |||
| 461 | Scoped C<querySelectorAll> under this element. C<$result> is a (possibly | ||
| 462 | empty) arrayref of L<EV::WebKit::Element>. | ||
| 463 | |||
| 464 | =head2 click | ||
| 465 | |||
| 466 | $el->click($cb); | ||
| 467 | |||
| 468 | Presses the element the way a pointer does: C<pointerdown>, C<mousedown>, | ||
| 469 | C<pointerup>, C<mouseup>, then the node's own C<click()>. The press matters -- | ||
| 470 | plenty of controls (custom dropdowns, menus, sliders) act on C<mousedown> and | ||
| 471 | never see a bare C<click()> at all. A B<disabled> control gets the C<click()> | ||
| 472 | only, with no synthetic press, because no engine dispatches mouse events to one | ||
| 473 | and firing them here would drive something a person could not. | ||
| 474 | |||
| 475 | Visibility is not checked: an off-screen or C<display:none> element is clicked | ||
| 476 | as asked, and reports success. Ask L</is_visible> first if that matters, and | ||
| 477 | L</scroll_into_view> if the page reacts to scroll position. | ||
| 478 | |||
| 479 | =head2 type | ||
| 480 | |||
| 481 | $el->type($text, $cb); | ||
| 482 | |||
| 483 | On an C<< <input> >> or C<< <textarea> >>, appends C<$text> to the | ||
| 484 | element's current C<value> and dispatches C<input> and C<change> events. | ||
| 485 | On a contenteditable element (C<isContentEditable>), appends C<$text> to | ||
| 486 | its C<textContent> instead (there is no native C<value> to set) and | ||
| 487 | dispatches an C<input> event. Either way this sets the content directly and | ||
| 488 | fires the event(s) once -- it does not simulate individual keydown/keyup | ||
| 489 | events per character. On anything else (not a form control, not | ||
| 490 | contenteditable), C<$err> is set to an error mentioning "not editable" | ||
| 491 | rather than silently doing nothing. | ||
| 492 | |||
| 493 | =head2 send_keys | ||
| 494 | |||
| 495 | An alias for C<type> above (identical behavior, including the "not really | ||
| 496 | per-key" caveat and the contenteditable/not-editable handling). | ||
| 497 | |||
| 498 | =head2 clear | ||
| 499 | |||
| 500 | $el->clear($cb); | ||
| 501 | |||
| 502 | On an C<< <input> >> or C<< <textarea> >>, empties C<value> and dispatches | ||
| 503 | an C<input> event. On a contenteditable element, empties C<textContent> | ||
| 504 | instead and dispatches an C<input> event. On anything else, C<$err> is set | ||
| 505 | to an error mentioning "not editable". | ||
| 506 | |||
| 507 | =head2 focus | ||
| 508 | |||
| 509 | $el->focus($cb); | ||
| 510 | |||
| 511 | Calls the node's C<focus()>. | ||
| 512 | |||
| 513 | =head2 submit | ||
| 514 | |||
| 515 | $el->submit($cb); | ||
| 516 | |||
| 517 | Calls the native C<submit()> of the element's owning C<< <form> >>, or of | ||
| 518 | the element itself if it has no C<form> (e.g. calling C<submit> directly on | ||
| 519 | a C<< <form> >> element). This bypasses any C<onsubmit> handler and may | ||
| 520 | navigate the page. Resolves successfully even if there was nothing to | ||
| 521 | submit (a silent no-op). | ||
| 522 | |||
| 523 | =head2 select_option | ||
| 524 | |||
| 525 | $el->select_option($value, $cb); # $cb->($selected_value, $err) | ||
| 526 | |||
| 527 | Selects an C<< <option> >> of a C<< <select> >> by its C<value>, falling back | ||
| 528 | to matching the visible label when no value matches -- so an option whose | ||
| 529 | C<value> differs from what the page displays, such as | ||
| 530 | C<< <option value="b">Beta</option> >>, is still reachable by the text the | ||
| 531 | user sees. (An option with no C<value> attribute at all takes its value from | ||
| 532 | its own text, so it already matches on the first pass.) Fires C<input> and C<change> so page code bound to | ||
| 533 | those actually runs; assigning C<el.value> alone updates the DOM and leaves | ||
| 534 | application state stale. Errors if the element is not a C<< <select> >>, or if | ||
| 535 | no option matches. | ||
| 536 | |||
| 537 | =head2 check / uncheck | ||
| 538 | |||
| 539 | $el->check($cb); # ensure checked | ||
| 540 | $el->check(0, $cb); # ensure UNchecked | ||
| 541 | $el->uncheck($cb); # the same thing, spelled out | ||
| 542 | |||
| 543 | Sets a checkbox or radio to a definite state and resolves with that state. | ||
| 544 | Deliberately not C<click>: clicking B<toggles>, so calling it twice "to be | ||
| 545 | sure" silently undoes itself. These are idempotent -- already in the requested | ||
| 546 | state means no change and, like a real browser, B<no> C<change> event. Errors | ||
| 547 | if the element is not a checkbox or radio. | ||
| 548 | |||
| 549 | The single-argument form is read as a B<callback> if it is a code reference and | ||
| 550 | as the B<state> otherwise -- evaluated for truth, so a decoded-JSON boolean | ||
| 551 | works as well as a plain C<1> or C<0>. C<uncheck> has no state argument, so a | ||
| 552 | non-coderef there is a mistyped callback and croaks. | ||
| 553 | |||
| 554 | =head2 hover | ||
| 555 | |||
| 556 | $el->hover($cb); | ||
| 557 | |||
| 558 | Dispatches the pointer/mouse sequence an entering cursor produces: | ||
| 559 | C<pointerover>/C<mouseover> (which bubble), then C<pointerenter>/C<mouseenter> | ||
| 560 | (which do not), then C<mousemove>, positioned at the element's centre. Menus | ||
| 561 | and tooltips listen for various of these, so dispatching only C<mouseover> | ||
| 562 | leaves a menu that opens on C<mouseenter> shut. These are synthetic events: | ||
| 563 | C<isTrusted> is false, so a page that checks it is not fooled. | ||
| 564 | |||
| 565 | =head2 box | ||
| 566 | |||
| 567 | $el->box($cb); # $cb->($box, $err) | ||
| 568 | |||
| 569 | The element's geometry as a hashref: C<x>, C<y>, C<width>, C<height>, C<top>, | ||
| 570 | C<left>, C<bottom>, C<right> -- viewport-relative, exactly as | ||
| 571 | C<getBoundingClientRect> gives them, which is what you want when comparing | ||
| 572 | against a screenshot -- plus C<page_x> and C<page_y>, the same origin with the | ||
| 573 | scroll offset added, for absolute document coordinates. | ||
| 574 | |||
| 575 | C<$box> is C<undef> for an element that is not rendered (C<display:none>, or | ||
| 576 | detached from the document). Such an element has an all-zero rect in every | ||
| 577 | browser, and returning that as a box would be a plausible-looking lie a caller | ||
| 578 | could divide by; ask L</is_visible> if that is the question. | ||
| 579 | |||
| 580 | For an element inside a frame the rect is relative to B<that frame's> viewport, | ||
| 581 | not the top-level one, since that is the only coordinate space the element's | ||
| 582 | own document has. Offsetting it into page coordinates would need the frame's | ||
| 583 | position, which is the parent document's to know. | ||
| 584 | |||
| 585 | =head2 frame_id | ||
| 586 | |||
| 587 | my $id = $el->frame_id; | ||
| 588 | |||
| 589 | The id of the frame this handle is B<bound> to, or C<undef> if it is not bound | ||
| 590 | to one. Synchronous; the id itself is opaque and lives only as long as the frame | ||
| 591 | does. | ||
| 592 | |||
| 593 | Note what C<undef> does B<not> mean. Only the C<< frame => { url => ... } >> | ||
| 594 | form binds a handle to a frame; a handle reached through the selector form | ||
| 595 | (C<< frame => '#f' >>) is inside an iframe but reports C<undef>, exactly as a | ||
| 596 | main-frame handle does. So this tells you how the handle will be operated on, | ||
| 597 | not where the element lives -- it is not a test for "is this inside an iframe". | ||
| 598 | See L<EV::WebKit/"Addressing an iframe">. | ||
| 599 | |||
| 600 | =head2 scroll_into_view | ||
| 601 | |||
| 602 | $el->scroll_into_view($cb); | ||
| 603 | |||
| 604 | Scrolls the element to the centre of the viewport. Worth doing before reading | ||
| 605 | around it: C<click> works on an off-screen element, but a page that reacts to | ||
| 606 | scroll position (lazy images, infinite scroll, sticky headers) will not have | ||
| 607 | done that work yet. | ||
| 608 | |||
| 609 | =head1 SEE ALSO | ||
| 610 | |||
| 611 | L<EV::WebKit> | ||
| 612 | |||
| 613 | =head1 AUTHOR | ||
| 614 | |||
| 615 | vividsnow | ||
| 616 | |||
| 617 | =head1 LICENSE | ||
| 618 | |||
| 619 | This library is free software; you can redistribute it and/or modify it | ||
| 620 | under the same terms as Perl itself. | ||
| 621 | |||
| 622 | =cut |