Debian Codegraph @

query.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 package chromedp
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "strconv"
9 "strings"
10 "sync"
11 "time"
12
13 "github.com/chromedp/cdproto"
14 "github.com/chromedp/cdproto/cdp"
15 "github.com/chromedp/cdproto/css"
16 "github.com/chromedp/cdproto/dom"
17 "github.com/chromedp/cdproto/runtime"
18 )
19
20 // QueryAction are element query actions that select node elements from the
21 // browser's DOM for retrieval or manipulation.
22 //
23 // See [Query] for details on building element query selectors.
24 type QueryAction Action
25
26 // Selector holds information pertaining to an element selection query.
27 //
28 // See [Query] for information on building an element selector and relevant
29 // options.
30 type Selector struct {
31 sel any
32 fromNode *cdp.Node
33 retryInterval time.Duration
34 exp int
35 by func(context.Context, *cdp.Node) ([]cdp.NodeID, error)
36 wait func(context.Context, *cdp.Frame, runtime.ExecutionContextID, ...cdp.NodeID) ([]*cdp.Node, error)
37 after []func(context.Context, runtime.ExecutionContextID, ...*cdp.Node) error
38 }
39
40 // Query is a query action that queries the browser for specific element
41 // node(s) matching the criteria.
42 //
43 // Query actions that target a browser DOM element node (or nodes) make use of
44 // Query, in conjunction with the [After] option to retrieve data or
45 // to modify the element(s) selected by the query.
46 //
47 // For example:
48 //
49 // chromedp.Run(ctx, chromedp.SendKeys(`thing`, chromedp.ByID))
50 //
51 // The above will perform a [SendKeys] action on the first element matching a
52 // browser CSS query for "#thing".
53 //
54 // [Element] selection queries work in conjunction with specific actions and form
55 // the primary way of automating [Tasks] in the browser. They are typically
56 // written in the following form:
57 //
58 // Action(selector[, parameter1, ...parameterN][,result][, queryOptions...])
59 //
60 // Where:
61 //
62 // - Action - the action to perform
63 // - selector - element query selection (typically a string), that any matching node(s) will have the action applied
64 // - parameter[1-N] - parameter(s) needed for the individual action (if any)
65 // - result - pointer to a result (if any)
66 // - queryOptions - changes how queries are executed, or how nodes are waited for
67 //
68 // # Query Options
69 //
70 // By* options specify the type of element query used By the browser to perform
71 // the selection query. When not specified, element queries will use [BySearch]
72 // (a wrapper for DOM.performSearch).
73 //
74 // Node* options specify node conditions that cause the query to wait until the
75 // specified condition is true. When not specified, queries will use the
76 // [NodeReady] wait condition.
77 //
78 // The [AtLeast] option alters the minimum number of nodes that must be returned
79 // by the element query. If not specified, the default value is 1.
80 //
81 // The [After] option is used to specify a func that will be executed when
82 // element query has returned one or more elements, and after the node condition is
83 // true.
84 //
85 // # By Options
86 //
87 // The [BySearch] (default) option enables querying for elements by plain text,
88 // CSS selector or XPath query, wrapping DOM.performSearch.
89 //
90 // The [ByID] option enables querying for a single element with the matching CSS
91 // ID, wrapping DOM.querySelector. ByID is similar to calling
92 // document.querySelector('#' + ID) from within the browser.
93 //
94 // The [ByQuery] option enables querying for a single element using a CSS
95 // selector, wrapping DOM.querySelector. ByQuery is similar to calling
96 // document.querySelector() from within the browser.
97 //
98 // The [ByQueryAll] option enables querying for elements using a CSS selector,
99 // wrapping DOM.querySelectorAll. ByQueryAll is similar to calling
100 // document.querySelectorAll() from within the browser.
101 //
102 // The [ByJSPath] option enables querying for a single element using its "JS
103 // Path" value, wrapping Runtime.evaluate. ByJSPath is similar to executing a
104 // JavaScript snippet that returns an element from within the browser. ByJSPath
105 // should be used only with trusted element queries, as it is passed directly
106 // to Runtime.evaluate, and no attempt is made to sanitize the query. Useful
107 // for querying DOM elements that cannot be retrieved using other By* funcs,
108 // such as ShadowDOM elements.
109 //
110 // # Node Options
111 //
112 // The [NodeReady] (default) option causes the query to wait until all element
113 // nodes matching the selector have been retrieved from the browser.
114 //
115 // The [NodeVisible] option causes the query to wait until all element nodes
116 // matching the selector have been retrieved from the browser, and are visible.
117 //
118 // The [NodeNotVisible] option causes the query to wait until all element nodes
119 // matching the selector have been retrieved from the browser, and are not
120 // visible.
121 //
122 // The [NodeEnabled] option causes the query to wait until all element nodes
123 // matching the selector have been retrieved from the browser, and are enabled
124 // (i.e., do not have a 'disabled' attribute).
125 //
126 // The [NodeSelected] option causes the query to wait until all element nodes
127 // matching the selector have been retrieved from the browser, and are
128 // selected (i.e., has a 'selected' attribute).
129 //
130 // The [NodeNotPresent] option causes the query to wait until there are no
131 // element nodes matching the selector.
132 func Query(sel any, opts ...QueryOption) QueryAction {
133 s := &Selector{
134 sel: sel,
135 exp: 1,
136 retryInterval: 5 * time.Millisecond,
137 }
138
139 // apply options
140 for _, o := range opts {
141 o(s)
142 }
143
144 if s.by == nil {
145 BySearch(s)
146 }
147
148 if s.wait == nil {
149 NodeReady(s)
150 }
151
152 return s
153 }
154
155 // Do executes the selector, only finishing if the selector's by, wait, and
156 // after funcs succeed, or if the context is cancelled.
157 func (s *Selector) Do(ctx context.Context) error {
158 t := cdp.ExecutorFromContext(ctx).(*Target)
159 if t == nil {
160 return ErrInvalidTarget
161 }
162 return retryWithSleep(ctx, s.retryInterval, func(ctx context.Context) (bool, error) {
163 frame, root, execCtx, ok := t.ensureFrame()
164 if !ok {
165 return false, nil
166 }
167
168 fromNode := s.fromNode
169 if fromNode == nil {
170 fromNode = root
171 } else {
172 frameID := t.enclosingFrame(fromNode)
173 t.frameMu.RLock()
174 execCtx = t.execContexts[frameID]
175 t.frameMu.RUnlock()
176
177 // TODO: we probably want to use the nested frame
178 // instead, but note that util.go stores the nested
179 // frame's nodes in the root frame's Nodes map.
180 // frame = t.frames[fromNode.FrameID]
181 // if frame == nil {
182 // return fmt.Errorf("FromNode provided does not belong to any active frame")
183 // }
184 }
185
186 // If this is an iframe node, we want to run the query
187 // on its "content document" node instead. Otherwise,
188 // queries will return no results.
189 if doc := fromNode.ContentDocument; doc != nil {
190 fromNode = doc
191 }
192
193 ids, err := s.by(ctx, fromNode)
194 if err != nil {
195 var e *cdproto.Error
196 // When the selector is invalid (for example, "#a:b" or "#3"), it will
197 // always fail with "DOM Error while querying". It does not make sense
198 // to retry in this case.
199 // Maybe "DOM Error while querying" is also used for other errors other
200 // than invalid selector. But the response does not contain anything
201 // else that can be used to distinguish them. So we have to go with it.
202 if errors.As(err, &e) && e.Message == "DOM Error while querying" {
203 return true, err
204 }
205 return false, nil
206 }
207 if len(ids) < s.exp {
208 return false, nil
209 }
210 nodes, err := s.wait(ctx, frame, execCtx, ids...)
211 // if nodes==nil, we're not yet ready
212 if nodes == nil || err != nil {
213 return false, nil
214 }
215 for _, f := range s.after {
216 if err := f(ctx, execCtx, nodes...); err != nil {
217 return true, err
218 }
219 }
220 return true, nil
221 })
222 }
223
224 // selAsString forces sel into a string.
225 func (s *Selector) selAsString() string {
226 if sel, ok := s.sel.(string); ok {
227 return sel
228 }
229 return fmt.Sprintf("%s", s.sel)
230 }
231
232 // waitReady waits for the specified nodes to be ready.
233 func (s *Selector) waitReady(check func(context.Context, runtime.ExecutionContextID, *cdp.Node) error) func(context.Context, *cdp.Frame, runtime.ExecutionContextID, ...cdp.NodeID) ([]*cdp.Node, error) {
234 return func(ctx context.Context, cur *cdp.Frame, execCtx runtime.ExecutionContextID, ids ...cdp.NodeID) ([]*cdp.Node, error) {
235 nodes := make([]*cdp.Node, len(ids))
236 cur.RLock()
237 for i, id := range ids {
238 nodes[i] = cur.Nodes[id]
239 if nodes[i] == nil {
240 cur.RUnlock()
241 // not yet ready
242 return nil, nil
243 }
244 }
245 cur.RUnlock()
246
247 if check != nil {
248 errc := make(chan error, 1)
249 for _, n := range nodes {
250 go func(n *cdp.Node) {
251 select {
252 case <-ctx.Done():
253 errc <- ctx.Err()
254 case errc <- check(ctx, execCtx, n):
255 }
256 }(n)
257 }
258
259 var first error
260 for range nodes {
261 if err := <-errc; first == nil {
262 first = err
263 }
264 }
265 close(errc)
266 if first != nil {
267 return nil, first
268 }
269 }
270 return nodes, nil
271 }
272 }
273
274 // QueryAfter is an element query action that queries the browser for selector
275 // sel. Waits until the visibility conditions of the query have been met, after
276 // which executes f.
277 func QueryAfter(sel any, f func(context.Context, runtime.ExecutionContextID, ...*cdp.Node) error, opts ...QueryOption) QueryAction {
278 return Query(sel, append(opts, After(f))...)
279 }
280
281 // QueryOption is an element query action option.
282 type QueryOption = func(*Selector)
283
284 // FromNode is an element query action option where a query will be run. That
285 // is, the query will only look at the node's element sub-tree. By default, or
286 // when passed nil, the document's root element will be used.
287 //
288 // Note that, at present, BySearch and ByJSPath do not support FromNode; this
289 // option is mainly useful for ByQuery selectors.
290 func FromNode(node *cdp.Node) QueryOption {
291 return func(s *Selector) { s.fromNode = node }
292 }
293
294 // ByFunc is an element query action option to set the func used to select elements.
295 func ByFunc(f func(context.Context, *cdp.Node) ([]cdp.NodeID, error)) QueryOption {
296 return func(s *Selector) {
297 s.by = f
298 }
299 }
300
301 // ByQuery is an element query action option to select a single element by the
302 // DOM.querySelector command.
303 //
304 // Similar to calling document.querySelector() in the browser.
305 func ByQuery(s *Selector) {
306 ByFunc(func(ctx context.Context, n *cdp.Node) ([]cdp.NodeID, error) {
307 nodeID, err := dom.QuerySelector(n.NodeID, s.selAsString()).Do(ctx)
308 if err != nil {
309 return nil, err
310 }
311
312 if nodeID == cdp.EmptyNodeID {
313 return []cdp.NodeID{}, nil
314 }
315
316 return []cdp.NodeID{nodeID}, nil
317 })(s)
318 }
319
320 // ByQueryAll is an element query action option to select elements by the
321 // DOM.querySelectorAll command.
322 //
323 // Similar to calling document.querySelectorAll() in the browser.
324 func ByQueryAll(s *Selector) {
325 ByFunc(func(ctx context.Context, n *cdp.Node) ([]cdp.NodeID, error) {
326 return dom.QuerySelectorAll(n.NodeID, s.selAsString()).Do(ctx)
327 })(s)
328 }
329
330 // ByID is an element query option to select a single element by its CSS #id.
331 //
332 // Similar to calling document.querySelector('#' + ID) in the browser.
333 func ByID(s *Selector) {
334 s.sel = "#" + strings.TrimPrefix(s.selAsString(), "#")
335 ByQuery(s)
336 }
337
338 // BySearch is an element query option to select elements by the DOM.performSearch
339 // command. It matches nodes by plain text, CSS selector or XPath query.
340 func BySearch(s *Selector) {
341 ByFunc(func(ctx context.Context, n *cdp.Node) ([]cdp.NodeID, error) {
342 id, count, err := dom.PerformSearch(s.selAsString()).Do(ctx)
343 if err != nil {
344 return nil, err
345 }
346
347 defer func() {
348 _ = dom.DiscardSearchResults(id).Do(ctx)
349 }()
350
351 if count < 1 {
352 return []cdp.NodeID{}, nil
353 }
354
355 nodes, err := dom.GetSearchResults(id, 0, count).Do(ctx)
356 if err != nil {
357 return nil, err
358 }
359
360 return nodes, nil
361 })(s)
362 }
363
364 // ByJSPath is an element query option to select elements by the "JS Path"
365 // value (as shown in the Chrome DevTools UI).
366 //
367 // Allows for the direct querying of DOM elements that otherwise cannot be
368 // retrieved using the other By* funcs, such as ShadowDOM elements.
369 //
370 // Note: Do not use with an untrusted selector value, as any defined selector
371 // will be passed to runtime.Evaluate.
372 func ByJSPath(s *Selector) {
373 ByFunc(func(ctx context.Context, n *cdp.Node) ([]cdp.NodeID, error) {
374 // set up eval command
375 p := runtime.Evaluate(s.selAsString()).
376 WithAwaitPromise(true).
377 WithObjectGroup("console").
378 WithIncludeCommandLineAPI(true)
379
380 // execute
381 v, exp, err := p.Do(ctx)
382 if err != nil {
383 return nil, err
384 }
385 if exp != nil {
386 return nil, exp
387 }
388
389 // use the ObjectID from the evaluation to get the nodeID
390 nodeID, err := dom.RequestNode(v.ObjectID).Do(ctx)
391 if err != nil {
392 return nil, err
393 }
394
395 if nodeID == cdp.EmptyNodeID {
396 return []cdp.NodeID{}, nil
397 }
398
399 return []cdp.NodeID{nodeID}, nil
400 })(s)
401 }
402
403 // ByNodeID is an element query option to select elements by their node IDs.
404 //
405 // Uses DOM.requestChildNodes to retrieve elements with specific node IDs.
406 //
407 // Note: must be used with []cdp.NodeID.
408 func ByNodeID(s *Selector) {
409 ids, ok := s.sel.([]cdp.NodeID)
410 if !ok {
411 panic("ByNodeID can only work on []cdp.NodeID")
412 }
413
414 ByFunc(func(ctx context.Context, n *cdp.Node) ([]cdp.NodeID, error) {
415 for _, id := range ids {
416 err := dom.RequestChildNodes(id).WithPierce(true).Do(ctx)
417 if err != nil {
418 return nil, err
419 }
420 }
421
422 return ids, nil
423 })(s)
424 }
425
426 // WaitFunc is an element query option to set a custom node condition wait.
427 func WaitFunc(wait func(context.Context, *cdp.Frame, runtime.ExecutionContextID, ...cdp.NodeID) ([]*cdp.Node, error)) QueryOption {
428 return func(s *Selector) {
429 s.wait = wait
430 }
431 }
432
433 // NodeReady is an element query option to wait until all queried element nodes
434 // have been sent by the browser.
435 func NodeReady(s *Selector) {
436 WaitFunc(s.waitReady(nil))(s)
437 }
438
439 func callFunctionOnNode(ctx context.Context, node *cdp.Node, function string, res any, args ...any) error {
440 r, err := dom.ResolveNode().WithNodeID(node.NodeID).Do(ctx)
441 if err != nil {
442 return err
443 }
444 err = CallFunctionOn(function, res,
445 func(p *runtime.CallFunctionOnParams) *runtime.CallFunctionOnParams {
446 return p.WithObjectID(r.ObjectID)
447 },
448 args...,
449 ).Do(ctx)
450 if err != nil {
451 return err
452 }
453
454 // Try to release the remote object.
455 // It will fail if the page is navigated or closed,
456 // and it's okay to ignore the error in this case.
457 _ = runtime.ReleaseObject(r.ObjectID).Do(ctx)
458
459 return nil
460 }
461
462 // NodeVisible is an element query option to wait until all queried element
463 // nodes have been sent by the browser and are visible.
464 func NodeVisible(s *Selector) {
465 WaitFunc(s.waitReady(func(ctx context.Context, execCtx runtime.ExecutionContextID, n *cdp.Node) error {
466 // check box model
467 _, err := dom.GetBoxModel().WithNodeID(n.NodeID).Do(ctx)
468 if err != nil {
469 if isCouldNotComputeBoxModelError(err) {
470 return ErrNotVisible
471 }
472
473 return err
474 }
475
476 // check visibility
477 var res bool
478 err = callFunctionOnNode(ctx, n, visibleJS, &res)
479 if err != nil {
480 return err
481 }
482 if !res {
483 return ErrNotVisible
484 }
485 return nil
486 }))(s)
487 }
488
489 // NodeNotVisible is an element query option to wait until all queried element
490 // nodes have been sent by the browser and are not visible.
491 func NodeNotVisible(s *Selector) {
492 WaitFunc(s.waitReady(func(ctx context.Context, execCtx runtime.ExecutionContextID, n *cdp.Node) error {
493 // check box model
494 _, err := dom.GetBoxModel().WithNodeID(n.NodeID).Do(ctx)
495 if err != nil {
496 if isCouldNotComputeBoxModelError(err) {
497 return nil
498 }
499
500 return err
501 }
502
503 // check visibility
504 var res bool
505 err = callFunctionOnNode(ctx, n, visibleJS, &res)
506 if err != nil {
507 return err
508 }
509 if res {
510 return ErrVisible
511 }
512 return nil
513 }))(s)
514 }
515
516 // NodeEnabled is an element query option to wait until all queried element
517 // nodes have been sent by the browser and are enabled (i.e., do not have a
518 // 'disabled' attribute).
519 func NodeEnabled(s *Selector) {
520 WaitFunc(s.waitReady(func(ctx context.Context, execCtx runtime.ExecutionContextID, n *cdp.Node) error {
521 n.RLock()
522 defer n.RUnlock()
523
524 for i := 0; i < len(n.Attributes); i += 2 {
525 if n.Attributes[i] == "disabled" {
526 return ErrDisabled
527 }
528 }
529
530 return nil
531 }))(s)
532 }
533
534 // NodeSelected is an element query option to wait until all queried element
535 // nodes have been sent by the browser and are selected (i.e., has 'selected'
536 // attribute).
537 func NodeSelected(s *Selector) {
538 WaitFunc(s.waitReady(func(ctx context.Context, execCtx runtime.ExecutionContextID, n *cdp.Node) error {
539 n.RLock()
540 defer n.RUnlock()
541
542 for i := 0; i < len(n.Attributes); i += 2 {
543 if n.Attributes[i] == "selected" {
544 return nil
545 }
546 }
547
548 return ErrNotSelected
549 }))(s)
550 }
551
552 // NodeNotPresent is an element query option to wait until no elements are
553 // present that match the query.
554 //
555 // Note: forces the expected number of element nodes to be 0.
556 func NodeNotPresent(s *Selector) {
557 s.exp = 0
558 WaitFunc(func(ctx context.Context, cur *cdp.Frame, execCtx runtime.ExecutionContextID, ids ...cdp.NodeID) ([]*cdp.Node, error) {
559 if len(ids) != 0 {
560 return nil, ErrHasResults
561 }
562 return []*cdp.Node{}, nil
563 })(s)
564 }
565
566 // AtLeast is an element query option to set a minimum number of elements that
567 // must be returned by the query.
568 //
569 // By default, a query will have a value of 1.
570 func AtLeast(n int) QueryOption {
571 return func(s *Selector) {
572 s.exp = n
573 }
574 }
575
576 // RetryInterval is an element query action option to set the retry interval to specify
577 // how often it should retry when it failed to select the target element(s).
578 //
579 // The default value is 5ms.
580 func RetryInterval(interval time.Duration) QueryOption {
581 return func(s *Selector) {
582 s.retryInterval = interval
583 }
584 }
585
586 // After is an element query option that sets a func to execute after the
587 // matched nodes have been returned by the browser, and after the node
588 // condition is true.
589 func After(f func(context.Context, runtime.ExecutionContextID, ...*cdp.Node) error) QueryOption {
590 return func(s *Selector) {
591 s.after = append(s.after, f)
592 }
593 }
594
595 // Populate is an element query option that causes the queried nodes to be
596 // retrieved for later use. Use a depth of -1 to retrieve all child nodes. When
597 // pierce is true, will pierce child containers (e.g. iframes and the like)
598 //
599 // NOTE: this could be extremely resource intensive. Avoid doing this unless
600 // necessary.
601 func Populate(depth int64, pierce bool, opts ...PopulateOption) QueryOption {
602 return After(func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
603 var d time.Duration
604 for _, o := range opts {
605 o(&d)
606 }
607 for _, n := range nodes {
608 if err := dom.RequestChildNodes(n.NodeID).
609 WithDepth(depth).
610 WithPierce(pierce).
611 Do(ctx); err != nil {
612 return err
613 }
614 }
615 if d != 0 {
616 <-time.After(d)
617 }
618 return nil
619 })
620 }
621
622 // PopulateOption is an element populate action option.
623 type PopulateOption = func(*time.Duration)
624
625 // PopulateWait is populate option to set a wait interval after requesting
626 // child nodes.
627 func PopulateWait(wait time.Duration) PopulateOption {
628 return func(d *time.Duration) {
629 *d = wait
630 }
631 }
632
633 // WaitReady is an element query action that waits until the element matching
634 // the selector is ready (i.e., has been "loaded").
635 func WaitReady(sel any, opts ...QueryOption) QueryAction {
636 return Query(sel, opts...)
637 }
638
639 // WaitVisible is an element query action that waits until the element matching
640 // the selector is visible.
641 func WaitVisible(sel any, opts ...QueryOption) QueryAction {
642 return Query(sel, append(opts, NodeVisible)...)
643 }
644
645 // WaitNotVisible is an element query action that waits until the element
646 // matching the selector is not visible.
647 func WaitNotVisible(sel any, opts ...QueryOption) QueryAction {
648 return Query(sel, append(opts, NodeNotVisible)...)
649 }
650
651 // WaitEnabled is an element query action that waits until the element matching
652 // the selector is enabled (i.e., does not have attribute 'disabled').
653 func WaitEnabled(sel any, opts ...QueryOption) QueryAction {
654 return Query(sel, append(opts, NodeEnabled)...)
655 }
656
657 // WaitSelected is an element query action that waits until the element
658 // matching the selector is selected (i.e., has attribute 'selected').
659 func WaitSelected(sel any, opts ...QueryOption) QueryAction {
660 return Query(sel, append(opts, NodeSelected)...)
661 }
662
663 // WaitNotPresent is an element query action that waits until no elements are
664 // present matching the selector.
665 func WaitNotPresent(sel any, opts ...QueryOption) QueryAction {
666 return Query(sel, append(opts, NodeNotPresent)...)
667 }
668
669 // Nodes is an element query action that retrieves the document element nodes
670 // matching the selector.
671 func Nodes(sel any, nodes *[]*cdp.Node, opts ...QueryOption) QueryAction {
672 if nodes == nil {
673 panic("nodes cannot be nil")
674 }
675
676 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, n ...*cdp.Node) error {
677 *nodes = n
678 return nil
679 }, opts...)
680 }
681
682 // NodeIDs is an element query action that retrieves the element node IDs matching the
683 // selector.
684 func NodeIDs(sel any, ids *[]cdp.NodeID, opts ...QueryOption) QueryAction {
685 if ids == nil {
686 panic("nodes cannot be nil")
687 }
688
689 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
690 nodeIDs := make([]cdp.NodeID, len(nodes))
691 for i, n := range nodes {
692 nodeIDs[i] = n.NodeID
693 }
694
695 *ids = nodeIDs
696
697 return nil
698 }, opts...)
699 }
700
701 // Focus is an element query action that focuses the first element node matching the
702 // selector.
703 func Focus(sel any, opts ...QueryOption) QueryAction {
704 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
705 if len(nodes) < 1 {
706 return fmt.Errorf("selector %q did not return any nodes", sel)
707 }
708
709 return dom.Focus().WithNodeID(nodes[0].NodeID).Do(ctx)
710 }, opts...)
711 }
712
713 // Blur is an element query action that unfocuses (blurs) the first element node
714 // matching the selector.
715 func Blur(sel any, opts ...QueryOption) QueryAction {
716 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
717 if len(nodes) < 1 {
718 return fmt.Errorf("selector %q did not return any nodes", sel)
719 }
720
721 var res bool
722 err := callFunctionOnNode(ctx, nodes[0], blurJS, &res)
723 if err != nil {
724 return err
725 }
726
727 if !res {
728 return fmt.Errorf("could not blur node %d", nodes[0].NodeID)
729 }
730
731 return nil
732 }, opts...)
733 }
734
735 // Dimensions is an element query action that retrieves the box model dimensions for the
736 // first element node matching the selector.
737 func Dimensions(sel any, model **dom.BoxModel, opts ...QueryOption) QueryAction {
738 if model == nil {
739 panic("model cannot be nil")
740 }
741 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
742 if len(nodes) < 1 {
743 return fmt.Errorf("selector %q did not return any nodes", sel)
744 }
745 var err error
746 *model, err = dom.GetBoxModel().WithNodeID(nodes[0].NodeID).Do(ctx)
747 return err
748 }, opts...)
749 }
750
751 // Text is an element query action that retrieves the visible text of the first element
752 // node matching the selector.
753 func Text(sel any, text *string, opts ...QueryOption) QueryAction {
754 if text == nil {
755 panic("text cannot be nil")
756 }
757
758 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
759 if len(nodes) < 1 {
760 return fmt.Errorf("selector %q did not return any nodes", sel)
761 }
762
763 return callFunctionOnNode(ctx, nodes[0], textJS, text)
764 }, opts...)
765 }
766
767 // TextContent is an element query action that retrieves the text content of the first element
768 // node matching the selector.
769 func TextContent(sel any, text *string, opts ...QueryOption) QueryAction {
770 if text == nil {
771 panic("text cannot be nil")
772 }
773
774 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
775 if len(nodes) < 1 {
776 return fmt.Errorf("selector %q did not return any nodes", sel)
777 }
778
779 return callFunctionOnNode(ctx, nodes[0], textContentJS, text)
780 }, opts...)
781 }
782
783 // Clear is an element query action that clears the values of any input/textarea element
784 // nodes matching the selector.
785 func Clear(sel any, opts ...QueryOption) QueryAction {
786 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
787 if len(nodes) < 1 {
788 return fmt.Errorf("selector %q did not return any nodes", sel)
789 }
790
791 for _, n := range nodes {
792 if n.NodeType != cdp.NodeTypeElement || (n.NodeName != "INPUT" && n.NodeName != "TEXTAREA") {
793 return fmt.Errorf("selector %q matched node %d with name %s", sel, n.NodeID, strings.ToLower(n.NodeName))
794 }
795 }
796
797 errs := make([]error, len(nodes))
798 var wg sync.WaitGroup
799 for i, n := range nodes {
800 wg.Add(1)
801 go func(i int, n *cdp.Node) {
802 defer wg.Done()
803
804 var a Action
805 if n.NodeName == "INPUT" {
806 a = dom.SetAttributeValue(n.NodeID, "value", "")
807 } else {
808 // find textarea's child #text node
809 var textID cdp.NodeID
810 var found bool
811 for _, c := range n.Children {
812 if c.NodeType == cdp.NodeTypeText {
813 textID = c.NodeID
814 found = true
815 break
816 }
817 }
818
819 if !found {
820 errs[i] = fmt.Errorf("textarea node %d does not have child #text node", n.NodeID)
821 return
822 }
823
824 a = dom.SetNodeValue(textID, "")
825 }
826 errs[i] = a.Do(ctx)
827 }(i, n)
828 }
829 wg.Wait()
830
831 for _, err := range errs {
832 if err != nil {
833 return err
834 }
835 }
836
837 return nil
838 }, opts...)
839 }
840
841 // Value is an element query action that retrieves the JavaScript value field of the
842 // first element node matching the selector.
843 //
844 // Useful for retrieving an element's JavaScript value, namely form, input,
845 // textarea, select, or any other element with a '.value' field.
846 func Value(sel any, value *string, opts ...QueryOption) QueryAction {
847 if value == nil {
848 panic("value cannot be nil")
849 }
850
851 return JavascriptAttribute(sel, "value", value, opts...)
852 }
853
854 // SetValue is an element query action that sets the JavaScript value of the first
855 // element node matching the selector.
856 //
857 // Useful for setting an element's JavaScript value, namely form, input,
858 // textarea, select, or other element with a '.value' field.
859 func SetValue(sel any, value string, opts ...QueryOption) QueryAction {
860 return SetJavascriptAttribute(sel, "value", value, opts...)
861 }
862
863 // Attributes is an element query action that retrieves the element attributes for the
864 // first element node matching the selector.
865 func Attributes(sel any, attributes *map[string]string, opts ...QueryOption) QueryAction {
866 if attributes == nil {
867 panic("attributes cannot be nil")
868 }
869
870 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
871 if len(nodes) < 1 {
872 return fmt.Errorf("selector %q did not return any nodes", sel)
873 }
874
875 nodes[0].RLock()
876 defer nodes[0].RUnlock()
877
878 m := make(map[string]string)
879 attrs := nodes[0].Attributes
880 for i := 0; i < len(attrs); i += 2 {
881 m[attrs[i]] = attrs[i+1]
882 }
883
884 *attributes = m
885
886 return nil
887 }, opts...)
888 }
889
890 // AttributesAll is an element query action that retrieves the element attributes for
891 // all element nodes matching the selector.
892 //
893 // Note: this should be used with the ByQueryAll query option.
894 func AttributesAll(sel any, attributes *[]map[string]string, opts ...QueryOption) QueryAction {
895 if attributes == nil {
896 panic("attributes cannot be nil")
897 }
898
899 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
900 if len(nodes) < 1 {
901 return fmt.Errorf("selector %q did not return any nodes", sel)
902 }
903
904 for _, node := range nodes {
905 node.RLock()
906 m := make(map[string]string)
907 attrs := node.Attributes
908 for i := 0; i < len(attrs); i += 2 {
909 m[attrs[i]] = attrs[i+1]
910 }
911 *attributes = append(*attributes, m)
912 node.RUnlock()
913 }
914 return nil
915 }, opts...)
916 }
917
918 // SetAttributes is an element query action that sets the element attributes for the
919 // first element node matching the selector.
920 func SetAttributes(sel any, attributes map[string]string, opts ...QueryOption) QueryAction {
921 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
922 if len(nodes) < 1 {
923 return errors.New("expected at least one element")
924 }
925
926 i, attrs := 0, make([]string, len(attributes))
927 for k, v := range attributes {
928 attrs[i] = fmt.Sprintf(`%s=%s`, k, strconv.Quote(v))
929 i++
930 }
931
932 return dom.SetAttributesAsText(nodes[0].NodeID, strings.Join(attrs, " ")).Do(ctx)
933 }, opts...)
934 }
935
936 // AttributeValue is an element query action that retrieves the element attribute value
937 // for the first element node matching the selector.
938 func AttributeValue(sel any, name string, value *string, ok *bool, opts ...QueryOption) QueryAction {
939 if value == nil {
940 panic("value cannot be nil")
941 }
942
943 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
944 if len(nodes) < 1 {
945 return errors.New("expected at least one element")
946 }
947
948 nodes[0].RLock()
949 defer nodes[0].RUnlock()
950
951 attrs := nodes[0].Attributes
952 for i := 0; i < len(attrs); i += 2 {
953 if attrs[i] == name {
954 *value = attrs[i+1]
955 if ok != nil {
956 *ok = true
957 }
958 return nil
959 }
960 }
961
962 if ok != nil {
963 *ok = false
964 }
965
966 return nil
967 }, opts...)
968 }
969
970 // SetAttributeValue is an element query action that sets the element attribute with
971 // name to value for the first element node matching the selector.
972 func SetAttributeValue(sel any, name, value string, opts ...QueryOption) QueryAction {
973 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
974 if len(nodes) < 1 {
975 return fmt.Errorf("selector %q did not return any nodes", sel)
976 }
977
978 return dom.SetAttributeValue(nodes[0].NodeID, name, value).Do(ctx)
979 }, opts...)
980 }
981
982 // RemoveAttribute is an element query action that removes the element attribute with
983 // name from the first element node matching the selector.
984 func RemoveAttribute(sel any, name string, opts ...QueryOption) QueryAction {
985 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
986 if len(nodes) < 1 {
987 return fmt.Errorf("selector %q did not return any nodes", sel)
988 }
989
990 return dom.RemoveAttribute(nodes[0].NodeID, name).Do(ctx)
991 }, opts...)
992 }
993
994 // JavascriptAttribute is an element query action that retrieves the JavaScript
995 // attribute for the first element node matching the selector.
996 func JavascriptAttribute(sel any, name string, res any, opts ...QueryOption) QueryAction {
997 if res == nil {
998 panic("res cannot be nil")
999 }
1000 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
1001 if len(nodes) < 1 {
1002 return fmt.Errorf("selector %q did not return any nodes", sel)
1003 }
1004
1005 if err := callFunctionOnNode(ctx, nodes[0], attributeJS, res, name); err != nil {
1006 return fmt.Errorf("could not retrieve attribute %q: %w", name, err)
1007 }
1008
1009 return nil
1010 }, opts...)
1011 }
1012
1013 // SetJavascriptAttribute is an element query action that sets the JavaScript attribute
1014 // for the first element node matching the selector.
1015 func SetJavascriptAttribute(sel any, name, value string, opts ...QueryOption) QueryAction {
1016 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
1017 if len(nodes) < 1 {
1018 return fmt.Errorf("selector %q did not return any nodes", sel)
1019 }
1020
1021 var res string
1022 err := callFunctionOnNode(ctx, nodes[0], setAttributeJS, &res, name, value)
1023 if err != nil {
1024 return err
1025 }
1026 if res != value {
1027 return fmt.Errorf("could not set value on node %d", nodes[0].NodeID)
1028 }
1029
1030 return nil
1031 }, opts...)
1032 }
1033
1034 // OuterHTML is an element query action that retrieves the outer html of the first
1035 // element node matching the selector.
1036 func OuterHTML(sel any, html *string, opts ...QueryOption) QueryAction {
1037 if html == nil {
1038 panic("html cannot be nil")
1039 }
1040 return JavascriptAttribute(sel, "outerHTML", html, opts...)
1041 }
1042
1043 // InnerHTML is an element query action that retrieves the inner html of the first
1044 // element node matching the selector.
1045 func InnerHTML(sel any, html *string, opts ...QueryOption) QueryAction {
1046 if html == nil {
1047 panic("html cannot be nil")
1048 }
1049 return JavascriptAttribute(sel, "innerHTML", html, opts...)
1050 }
1051
1052 // Click is an element query action that sends a mouse click event to the first element
1053 // node matching the selector.
1054 func Click(sel any, opts ...QueryOption) QueryAction {
1055 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
1056 if len(nodes) < 1 {
1057 return fmt.Errorf("selector %q did not return any nodes", sel)
1058 }
1059
1060 return MouseClickNode(nodes[0]).Do(ctx)
1061 }, append(opts, NodeVisible)...)
1062 }
1063
1064 // DoubleClick is an element query action that sends a mouse double click event to the
1065 // first element node matching the selector.
1066 func DoubleClick(sel any, opts ...QueryOption) QueryAction {
1067 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
1068 if len(nodes) < 1 {
1069 return fmt.Errorf("selector %q did not return any nodes", sel)
1070 }
1071
1072 return MouseClickNode(nodes[0], ClickCount(2)).Do(ctx)
1073 }, append(opts, NodeVisible)...)
1074 }
1075
1076 // SendKeys is an element query action that synthesizes the key up, char, and down
1077 // events as needed for the runes in v, sending them to the first element node
1078 // matching the selector.
1079 //
1080 // See the [keys] for a complete example on how to use SendKeys.
1081 //
1082 // Note: when the element query matches an input[type="file"] node, then
1083 // dom.SetFileInputFiles is used to set the upload path of the input node to v.
1084 //
1085 // [keys]: https://github.com/chromedp/examples/tree/master/keys
1086 func SendKeys(sel any, v string, opts ...QueryOption) QueryAction {
1087 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
1088 if len(nodes) < 1 {
1089 return fmt.Errorf("selector %q did not return any nodes", sel)
1090 }
1091
1092 n := nodes[0]
1093
1094 // grab type attribute from node
1095 typ, attrs := "", n.Attributes
1096 n.RLock()
1097 for i := 0; i < len(attrs); i += 2 {
1098 if attrs[i] == "type" {
1099 typ = attrs[i+1]
1100 }
1101 }
1102 n.RUnlock()
1103
1104 // when working with input[type="file"], call dom.SetFileInputFiles
1105 if n.NodeName == "INPUT" && typ == "file" {
1106 return dom.SetFileInputFiles([]string{v}).WithNodeID(n.NodeID).Do(ctx)
1107 }
1108
1109 return KeyEventNode(n, v).Do(ctx)
1110 }, append(opts, NodeVisible)...)
1111 }
1112
1113 // SetUploadFiles is an element query action that sets the files to upload (i.e., for a
1114 // input[type="file"] node) for the first element node matching the selector.
1115 func SetUploadFiles(sel any, files []string, opts ...QueryOption) QueryAction {
1116 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
1117 if len(nodes) < 1 {
1118 return fmt.Errorf("selector %q did not return any nodes", sel)
1119 }
1120
1121 return dom.SetFileInputFiles(files).WithNodeID(nodes[0].NodeID).Do(ctx)
1122 }, opts...)
1123 }
1124
1125 // Submit is an element query action that submits the parent form of the first element
1126 // node matching the selector.
1127 func Submit(sel any, opts ...QueryOption) QueryAction {
1128 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
1129 if len(nodes) < 1 {
1130 return fmt.Errorf("selector %q did not return any nodes", sel)
1131 }
1132
1133 var res bool
1134 err := callFunctionOnNode(ctx, nodes[0], submitJS, &res)
1135 if err != nil {
1136 return err
1137 }
1138
1139 if !res {
1140 return fmt.Errorf("could not call submit on node %d", nodes[0].NodeID)
1141 }
1142
1143 return nil
1144 }, opts...)
1145 }
1146
1147 // Reset is an element query action that resets the parent form of the first element
1148 // node matching the selector.
1149 func Reset(sel any, opts ...QueryOption) QueryAction {
1150 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
1151 if len(nodes) < 1 {
1152 return fmt.Errorf("selector %q did not return any nodes", sel)
1153 }
1154
1155 var res bool
1156 err := callFunctionOnNode(ctx, nodes[0], resetJS, &res)
1157 if err != nil {
1158 return err
1159 }
1160
1161 if !res {
1162 return fmt.Errorf("could not call reset on node %d", nodes[0].NodeID)
1163 }
1164
1165 return nil
1166 }, opts...)
1167 }
1168
1169 // ComputedStyle is an element query action that retrieves the computed style of the
1170 // first element node matching the selector.
1171 func ComputedStyle(sel any, style *[]*css.ComputedStyleProperty, opts ...QueryOption) QueryAction {
1172 if style == nil {
1173 panic("style cannot be nil")
1174 }
1175
1176 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
1177 if len(nodes) < 1 {
1178 return fmt.Errorf("selector %q did not return any nodes", sel)
1179 }
1180
•1181 computed, err := css.GetComputedStyleForNode(nodes[0].NodeID).Do(ctx)
1182 if err != nil {
1183 return err
1184 }
1185
1186 *style = computed
1187
1188 return nil
1189 }, opts...)
1190 }
1191
1192 // MatchedStyle is an element query action that retrieves the matched style information
1193 // for the first element node matching the selector.
1194 func MatchedStyle(sel any, style **css.GetMatchedStylesForNodeReturns, opts ...QueryOption) QueryAction {
1195 if style == nil {
1196 panic("style cannot be nil")
1197 }
1198
1199 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
1200 if len(nodes) < 1 {
1201 return fmt.Errorf("selector %q did not return any nodes", sel)
1202 }
1203
1204 var err error
1205 ret := &css.GetMatchedStylesForNodeReturns{}
1206 p := css.GetMatchedStylesForNode(nodes[0].NodeID)
1207 err = cdp.Execute(ctx, css.CommandGetMatchedStylesForNode, p, ret)
1208 if err != nil {
1209 return err
1210 }
1211
1212 *style = ret
1213
1214 return nil
1215 }, opts...)
1216 }
1217
1218 // ScrollIntoView is an element query action that scrolls the window to the
1219 // first element node matching the selector.
1220 func ScrollIntoView(sel any, opts ...QueryOption) QueryAction {
1221 return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
1222 if len(nodes) < 1 {
1223 return fmt.Errorf("selector %q did not return any nodes", sel)
1224 }
1225
1226 return dom.ScrollIntoViewIfNeeded().WithNodeID(nodes[0].NodeID).Do(ctx)
1227 }, opts...)
1228 }
1229
1230 // DumpTo is an element query action that writes a readable tree of the first
1231 // element node matching the selector and its children, up to the specified
1232 // depth.
1233 //
1234 // See [Dump] for a simpler interface.
1235 func DumpTo(sel any, w io.Writer, prefix, indent string, nodeIDs bool, depth int64, pierce bool, wait time.Duration, opts ...QueryOption) QueryAction {
1236 return Query(sel, append(opts,
1237 Populate(depth, pierce, PopulateWait(wait)),
1238 After(func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error {
1239 var n *cdp.Node
1240 if len(nodes) > 0 {
1241 n = nodes[0]
1242 }
1243 _, err := n.WriteTo(w, prefix, indent, nodeIDs)
1244 return err
1245 }),
1246 )...)
1247 }
1248
1249 // Dump is an element query action that writes a readable tree of the first
1250 // element node matching the selector and its children, up to the specified
1251 // depth.
1252 //
1253 // See [DumpTo] for more configurable options, which includes the ability to
1254 // set the sleep wait timeout.
1255 func Dump(sel any, w io.Writer, opts ...QueryOption) QueryAction {
1256 return DumpTo(sel, w, "", " ", false, -1, true, 80*time.Millisecond, opts...)
1257 }