vendor/github.com/go-rod/rod/element.go
754 lines · 19805 bytes
1package rod
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "reflect"
8 "strings"
9 "time"
10
11 "github.com/go-rod/rod/lib/cdp"
12 "github.com/go-rod/rod/lib/input"
13 "github.com/go-rod/rod/lib/js"
14 "github.com/go-rod/rod/lib/proto"
15 "github.com/go-rod/rod/lib/utils"
16 "github.com/ysmood/gson"
17)
18
19// Element implements these interfaces.
20var (
21 _ proto.Client = &Element{}
22 _ proto.Contextable = &Element{}
23 _ proto.Sessionable = &Element{}
24)
25
26// Element represents the DOM element.
27type Element struct {
28 Object *proto.RuntimeRemoteObject
29
30 e eFunc
31
32 ctx context.Context
33
34 sleeper func() utils.Sleeper
35
36 page *Page
37}
38
39// GetSessionID interface.
40func (el *Element) GetSessionID() proto.TargetSessionID {
41 return el.page.SessionID
42}
43
44// String interface.
45func (el *Element) String() string {
46 return fmt.Sprintf("<%s>", el.Object.Description)
47}
48
49// Page of the element.
50func (el *Element) Page() *Page {
51 return el.page
52}
53
54// Focus sets focus on the specified element.
55// Before the action, it will try to scroll to the element.
56func (el *Element) Focus() error {
57 err := el.ScrollIntoView()
58 if err != nil {
59 return err
60 }
61
62 _, err = el.Evaluate(Eval(`() => this.focus()`).ByUser())
63 return err
64}
65
66// ScrollIntoView scrolls the current element into the visible area of the browser
67// window if it's not already within the visible area.
68func (el *Element) ScrollIntoView() error {
69 defer el.tryTrace(TraceTypeInput, "scroll into view")()
70 el.page.browser.trySlowMotion()
71
72 err := el.WaitStableRAF()
73 if err != nil {
74 return err
75 }
76
77 return proto.DOMScrollIntoViewIfNeeded{ObjectID: el.id()}.Call(el)
78}
79
80// Hover the mouse over the center of the element.
81// Before the action, it will try to scroll to the element and wait until it's interactable.
82func (el *Element) Hover() error {
83 pt, err := el.WaitInteractable()
84 if err != nil {
85 return err
86 }
87
88 return el.page.Context(el.ctx).Mouse.MoveTo(*pt)
89}
90
91// MoveMouseOut of the current element.
92func (el *Element) MoveMouseOut() error {
93 shape, err := el.Shape()
94 if err != nil {
95 return err
96 }
97 box := shape.Box()
98 return el.page.Mouse.MoveTo(proto.NewPoint(box.X+box.Width, box.Y))
99}
100
101// Click will press then release the button just like a human.
102// Before the action, it will try to scroll to the element, hover the mouse over it,
103// wait until the it's interactable and enabled.
104func (el *Element) Click(button proto.InputMouseButton, clickCount int) error {
105 err := el.Hover()
106 if err != nil {
107 return err
108 }
109
110 err = el.WaitEnabled()
111 if err != nil {
112 return err
113 }
114
115 defer el.tryTrace(TraceTypeInput, string(button)+" click")()
116
117 return el.page.Context(el.ctx).Mouse.Click(button, clickCount)
118}
119
120// Tap will scroll to the button and tap it just like a human.
121// Before the action, it will try to scroll to the element and wait until it's interactable and enabled.
122func (el *Element) Tap() error {
123 err := el.ScrollIntoView()
124 if err != nil {
125 return err
126 }
127
128 err = el.WaitEnabled()
129 if err != nil {
130 return err
131 }
132
133 pt, err := el.WaitInteractable()
134 if err != nil {
135 return err
136 }
137
138 defer el.tryTrace(TraceTypeInput, "tap")()
139
140 return el.page.Context(el.ctx).Touch.Tap(pt.X, pt.Y)
141}
142
143// Interactable checks if the element is interactable with cursor.
144// The cursor can be mouse, finger, stylus, etc.
145// If not interactable err will be ErrNotInteractable, such as when covered by a modal,.
146func (el *Element) Interactable() (pt *proto.Point, err error) {
147 noPointerEvents, err := el.Eval(`() => getComputedStyle(this).pointerEvents === 'none'`)
148 if err != nil {
149 return nil, err
150 }
151
152 if noPointerEvents.Value.Bool() {
153 return nil, &NoPointerEventsError{el}
154 }
155
156 shape, err := el.Shape()
157 if err != nil {
158 return nil, err
159 }
160
161 pt = shape.OnePointInside()
162 if pt == nil {
163 err = &InvisibleShapeError{el}
164 return
165 }
166
167 scroll, err := el.page.root.Context(el.ctx).Eval(`() => ({ x: window.scrollX, y: window.scrollY })`)
168 if err != nil {
169 return
170 }
171
172 elAtPoint, err := el.page.Context(el.ctx).ElementFromPoint(
173 int(pt.X)+scroll.Value.Get("x").Int(),
174 int(pt.Y)+scroll.Value.Get("y").Int(),
175 )
176 if err != nil {
177 if errors.Is(err, cdp.ErrNodeNotFoundAtPos) {
178 err = &InvisibleShapeError{el}
179 }
180 return
181 }
182
183 isParent, err := el.ContainsElement(elAtPoint)
184 if err != nil {
185 return
186 }
187
188 if !isParent {
189 err = &CoveredError{elAtPoint}
190 }
191 return
192}
193
194// Shape of the DOM element content. The shape is a group of 4-sides polygons.
195// A 4-sides polygon is not necessary a rectangle. 4-sides polygons can be apart from each other.
196// For example, we use 2 4-sides polygons to describe the shape below:
197//
198// ____________ ____________
199// / ___/ = /___________/ + _________
200// /________/ /________/
201func (el *Element) Shape() (*proto.DOMGetContentQuadsResult, error) {
202 return proto.DOMGetContentQuads{ObjectID: el.id()}.Call(el)
203}
204
205// Type is similar with Keyboard.Type.
206// Before the action, it will try to scroll to the element and focus on it.
207func (el *Element) Type(keys ...input.Key) error {
208 err := el.Focus()
209 if err != nil {
210 return err
211 }
212 return el.page.Context(el.ctx).Keyboard.Type(keys...)
213}
214
215// KeyActions is similar with Page.KeyActions.
216// Before the action, it will try to scroll to the element and focus on it.
217func (el *Element) KeyActions() (*KeyActions, error) {
218 err := el.Focus()
219 if err != nil {
220 return nil, err
221 }
222
223 return el.page.Context(el.ctx).KeyActions(), nil
224}
225
226// SelectText selects the text that matches the regular expression.
227// Before the action, it will try to scroll to the element and focus on it.
228func (el *Element) SelectText(regex string) error {
229 err := el.Focus()
230 if err != nil {
231 return err
232 }
233
234 defer el.tryTrace(TraceTypeInput, "select text: "+regex)()
235 el.page.browser.trySlowMotion()
236
237 _, err = el.Evaluate(evalHelper(js.SelectText, regex).ByUser())
238 return err
239}
240
241// SelectAllText selects all text
242// Before the action, it will try to scroll to the element and focus on it.
243func (el *Element) SelectAllText() error {
244 err := el.Focus()
245 if err != nil {
246 return err
247 }
248
249 defer el.tryTrace(TraceTypeInput, "select all text")()
250 el.page.browser.trySlowMotion()
251
252 _, err = el.Evaluate(evalHelper(js.SelectAllText).ByUser())
253 return err
254}
255
256// Input focuses on the element and input text to it.
257// Before the action, it will scroll to the element, wait until it's visible, enabled and writable.
258// To empty the input you can use something like
259//
260// el.SelectAllText().MustInput("")
261func (el *Element) Input(text string) error {
262 err := el.Focus()
263 if err != nil {
264 return err
265 }
266
267 err = el.WaitEnabled()
268 if err != nil {
269 return err
270 }
271
272 err = el.WaitWritable()
273 if err != nil {
274 return err
275 }
276
277 err = el.page.Context(el.ctx).InsertText(text)
278 _, _ = el.Evaluate(evalHelper(js.InputEvent).ByUser())
279 return err
280}
281
282// InputTime focuses on the element and input time to it.
283// Before the action, it will scroll to the element, wait until it's visible, enabled and writable.
284// It will wait until the element is visible, enabled and writable.
285func (el *Element) InputTime(t time.Time) error {
286 err := el.Focus()
287 if err != nil {
288 return err
289 }
290
291 err = el.WaitEnabled()
292 if err != nil {
293 return err
294 }
295
296 err = el.WaitWritable()
297 if err != nil {
298 return err
299 }
300
301 defer el.tryTrace(TraceTypeInput, "input "+t.String())()
302
303 _, err = el.Evaluate(evalHelper(js.InputTime, t.UnixNano()/1e6).ByUser())
304 return err
305}
306
307// InputColor focuses on the element and inputs a color string to it.
308// Before the action, it will scroll to the element, wait until it's visible, enabled and writable.
309func (el *Element) InputColor(color string) error {
310 err := el.Focus()
311 if err != nil {
312 return err
313 }
314
315 err = el.WaitEnabled()
316 if err != nil {
317 return err
318 }
319
320 err = el.WaitWritable()
321 if err != nil {
322 return err
323 }
324
325 defer el.tryTrace(TraceTypeInput, "input "+color)()
326
327 _, err = el.Evaluate(evalHelper(js.InputColor, color))
328 return err
329}
330
331// Blur removes focus from the element.
332func (el *Element) Blur() error {
333 _, err := el.Evaluate(Eval("() => this.blur()").ByUser())
334 return err
335}
336
337// Select the children option elements that match the selectors.
338// Before the action, it will scroll to the element, wait until it's visible.
339// If no option matches the selectors, it will return [ErrElementNotFound].
340func (el *Element) Select(selectors []string, selected bool, t SelectorType) error {
341 err := el.Focus()
342 if err != nil {
343 return err
344 }
345
346 defer el.tryTrace(TraceTypeInput, fmt.Sprintf(`select "%s"`, strings.Join(selectors, "; ")))()
347 el.page.browser.trySlowMotion()
348
349 res, err := el.Evaluate(evalHelper(js.Select, selectors, selected, t).ByUser())
350 if err != nil {
351 return err
352 }
353 if !res.Value.Bool() {
354 return &ElementNotFoundError{}
355 }
356 return nil
357}
358
359// Matches checks if the element can be selected by the css selector.
360func (el *Element) Matches(selector string) (bool, error) {
361 res, err := el.Eval(`s => this.matches(s)`, selector)
362 if err != nil {
363 return false, err
364 }
365 return res.Value.Bool(), nil
366}
367
368// Attribute of the DOM object.
369// Attribute vs Property:
370// https://stackoverflow.com/questions/6003819/what-is-the-difference-between-properties-and-attributes-in-html
371func (el *Element) Attribute(name string) (*string, error) {
372 attr, err := el.Eval("(n) => this.getAttribute(n)", name)
373 if err != nil {
374 return nil, err
375 }
376
377 if attr.Value.Nil() {
378 return nil, nil //nolint: nilnil
379 }
380
381 s := attr.Value.Str()
382 return &s, nil
383}
384
385// Property of the DOM object.
386// Property vs Attribute:
387// https://stackoverflow.com/questions/6003819/what-is-the-difference-between-properties-and-attributes-in-html
388func (el *Element) Property(name string) (gson.JSON, error) {
389 prop, err := el.Eval("(n) => this[n]", name)
390 if err != nil {
391 return gson.New(nil), err
392 }
393
394 return prop.Value, nil
395}
396
397// Disabled checks if the element is disabled.
398func (el *Element) Disabled() (bool, error) {
399 prop, err := el.Property("disabled")
400 if err != nil {
401 return false, err
402 }
403 return prop.Bool(), nil
404}
405
406// SetFiles of the current file input element.
407func (el *Element) SetFiles(paths []string) error {
408 absPaths := utils.AbsolutePaths(paths)
409
410 defer el.tryTrace(TraceTypeInput, fmt.Sprintf("set files: %v", absPaths))()
411 el.page.browser.trySlowMotion()
412
413 err := proto.DOMSetFileInputFiles{
414 Files: absPaths,
415 ObjectID: el.id(),
416 }.Call(el)
417
418 return err
419}
420
421// Describe the current element. The depth is the maximum depth at which children should be retrieved, defaults to 1,
422// use -1 for the entire subtree or provide an integer larger than 0.
423// The pierce decides whether or not iframes and shadow roots should be traversed when returning the subtree.
424// The returned [proto.DOMNode.NodeID] will always be empty,
425// because NodeID is not stable (when [proto.DOMDocumentUpdated]
426// is fired all NodeID on the page will be reassigned to another value)
427// we don't recommend using the NodeID, instead, use the [proto.DOMBackendNodeID] to identify the element.
428func (el *Element) Describe(depth int, pierce bool) (*proto.DOMNode, error) {
429 val, err := proto.DOMDescribeNode{ObjectID: el.id(), Depth: gson.Int(depth), Pierce: pierce}.Call(el)
430 if err != nil {
431 return nil, err
432 }
433 return val.Node, nil
434}
435
436// ShadowRoot returns the shadow root of this element.
437func (el *Element) ShadowRoot() (*Element, error) {
438 node, err := el.Describe(1, false)
439 if err != nil {
440 return nil, err
441 }
442
443 // though now it's an array, w3c changed the spec of it to be a single.
444 if len(node.ShadowRoots) == 0 {
445 return nil, &NoShadowRootError{el}
446 }
447 id := node.ShadowRoots[0].BackendNodeID
448
449 shadowNode, err := proto.DOMResolveNode{BackendNodeID: id}.Call(el)
450 if err != nil {
451 return nil, err
452 }
453
454 return el.page.Context(el.ctx).ElementFromObject(shadowNode.Object)
455}
456
457// Frame creates a page instance that represents the iframe.
458func (el *Element) Frame() (*Page, error) {
459 node, err := el.Describe(1, false)
460 if err != nil {
461 return nil, err
462 }
463
464 clone := *el.page
465 clone.FrameID = node.FrameID
466 clone.jsCtxID = new(proto.RuntimeRemoteObjectID)
467 clone.element = el
468 clone.sleeper = el.sleeper
469
470 return &clone, nil
471}
472
473// ContainsElement check if the target is equal or inside the element.
474func (el *Element) ContainsElement(target *Element) (bool, error) {
475 res, err := el.Evaluate(evalHelper(js.ContainsElement, target.Object))
476 if err != nil {
477 return false, err
478 }
479 return res.Value.Bool(), nil
480}
481
482// Text that the element displays.
483func (el *Element) Text() (string, error) {
484 str, err := el.Evaluate(evalHelper(js.Text))
485 if err != nil {
486 return "", err
487 }
488 return str.Value.String(), nil
489}
490
491// HTML of the element.
492func (el *Element) HTML() (string, error) {
493 res, err := proto.DOMGetOuterHTML{ObjectID: el.Object.ObjectID}.Call(el)
494 if err != nil {
495 return "", err
496 }
497 return res.OuterHTML, nil
498}
499
500// Visible returns true if the element is visible on the page.
501func (el *Element) Visible() (bool, error) {
502 res, err := el.Evaluate(evalHelper(js.Visible))
503 if err != nil {
504 return false, err
505 }
506 return res.Value.Bool(), nil
507}
508
509// WaitLoad for element like <img>.
510func (el *Element) WaitLoad() error {
511 defer el.tryTrace(TraceTypeWait, "load")()
512 _, err := el.Evaluate(evalHelper(js.WaitLoad).ByPromise())
513 return err
514}
515
516// WaitStable waits until no shape or position change for d duration.
517// Be careful, d is not the max wait timeout, it's the least stable time.
518// If you want to set a timeout you can use the [Element.Timeout] function.
519func (el *Element) WaitStable(d time.Duration) error {
520 err := el.WaitVisible()
521 if err != nil {
522 return err
523 }
524
525 defer el.tryTrace(TraceTypeWait, "stable")()
526
527 shape, err := el.Shape()
528 if err != nil {
529 return err
530 }
531
532 t := time.NewTicker(d)
533 defer t.Stop()
534
535 for {
536 select {
537 case <-t.C:
538 case <-el.ctx.Done():
539 return el.ctx.Err()
540 }
541 current, err := el.Shape()
542 if err != nil {
543 return err
544 }
545 if reflect.DeepEqual(shape, current) {
546 break
547 }
548 shape = current
549 }
550 return nil
551}
552
553// WaitStableRAF waits until no shape or position change for 2 consecutive animation frames.
554// If you want to wait animation that is triggered by JS not CSS, you'd better use [Element.WaitStable].
555// About animation frame: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
556func (el *Element) WaitStableRAF() error {
557 err := el.WaitVisible()
558 if err != nil {
559 return err
560 }
561
562 defer el.tryTrace(TraceTypeWait, "stable RAF")()
563
564 var shape *proto.DOMGetContentQuadsResult
565 page := el.page.Context(el.ctx)
566
567 for {
568 err = page.WaitRepaint()
569 if err != nil {
570 return err
571 }
572
573 current, err := el.Shape()
574 if err != nil {
575 return err
576 }
577 if reflect.DeepEqual(shape, current) {
578 break
579 }
580 shape = current
581 }
582 return nil
583}
584
585// WaitInteractable waits for the element to be interactable.
586// It will try to scroll to the element on each try.
587func (el *Element) WaitInteractable() (pt *proto.Point, err error) {
588 defer el.tryTrace(TraceTypeWait, "interactable")()
589
590 err = utils.Retry(el.ctx, el.sleeper(), func() (bool, error) {
591 // For lazy loading page the element can be outside of the viewport.
592 // If we don't scroll to it, it will never be available.
593 err := el.ScrollIntoView()
594 if err != nil {
595 return true, err
596 }
597
598 pt, err = el.Interactable()
599 if errors.Is(err, &CoveredError{}) {
600 return false, nil
601 }
602 return true, err
603 })
604 return
605}
606
607// Wait until the js returns true.
608func (el *Element) Wait(opts *EvalOptions) error {
609 return el.page.Context(el.ctx).Sleeper(el.sleeper).Wait(opts.This(el.Object))
610}
611
612// WaitVisible until the element is visible.
613func (el *Element) WaitVisible() error {
614 defer el.tryTrace(TraceTypeWait, "visible")()
615 return el.Wait(evalHelper(js.Visible))
616}
617
618// WaitEnabled until the element is not disabled.
619// Doc for readonly: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/readonly
620func (el *Element) WaitEnabled() error {
621 defer el.tryTrace(TraceTypeWait, "enabled")()
622 return el.Wait(Eval(`() => !this.disabled`))
623}
624
625// WaitWritable until the element is not readonly.
626// Doc for disabled: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/disabled
627func (el *Element) WaitWritable() error {
628 defer el.tryTrace(TraceTypeWait, "writable")()
629 return el.Wait(Eval(`() => !this.readonly`))
630}
631
632// WaitInvisible until the element invisible.
633func (el *Element) WaitInvisible() error {
634 defer el.tryTrace(TraceTypeWait, "invisible")()
635 return el.Wait(evalHelper(js.Invisible))
636}
637
638// CanvasToImage get image data of a canvas.
639// The default format is image/png.
640// The default quality is 0.92.
641// doc: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL
642func (el *Element) CanvasToImage(format string, quality float64) ([]byte, error) {
643 res, err := el.Eval(`(format, quality) => this.toDataURL(format, quality)`, format, quality)
644 if err != nil {
645 return nil, err
646 }
647
648 _, bin := parseDataURI(res.Value.Str())
649 return bin, nil
650}
651
652// Resource returns the "src" content of current element. Such as the jpg of <img src="a.jpg">.
653func (el *Element) Resource() ([]byte, error) {
654 src, err := el.Evaluate(evalHelper(js.Resource).ByPromise())
655 if err != nil {
656 return nil, err
657 }
658
659 return el.page.Context(el.ctx).GetResource(src.Value.String())
660}
661
662// BackgroundImage returns the css background-image of the element.
663func (el *Element) BackgroundImage() ([]byte, error) {
664 res, err := el.Eval(`() => window.getComputedStyle(this).backgroundImage.replace(/^url\("/, '').replace(/"\)$/, '')`)
665 if err != nil {
666 return nil, err
667 }
668
669 u := res.Value.Str()
670
671 return el.page.Context(el.ctx).GetResource(u)
672}
673
674// Screenshot of the area of the element.
675func (el *Element) Screenshot(format proto.PageCaptureScreenshotFormat, quality int) ([]byte, error) {
676 err := el.ScrollIntoView()
677 if err != nil {
678 return nil, err
679 }
680
681 opts := &proto.PageCaptureScreenshot{
682 Quality: gson.Int(quality),
683 Format: format,
684 }
685
686 bin, err := el.page.Context(el.ctx).Screenshot(false, opts)
687 if err != nil {
688 return nil, err
689 }
690
691 // so that it won't clip the css-transformed element
692 shape, err := el.Shape()
693 if err != nil {
694 return nil, err
695 }
696
697 box := shape.Box()
698
699 // TODO: proto.PageCaptureScreenshot has a Clip option, but it's buggy, so now we do in Go.
700 return utils.CropImage(bin, quality,
701 int(box.X),
702 int(box.Y),
703 int(box.Width),
704 int(box.Height),
705 )
706}
707
708// Release is a shortcut for [Page.Release] current element.
709func (el *Element) Release() error {
710 return el.page.Context(el.ctx).Release(el.Object)
711}
712
713// Remove the element from the page.
714func (el *Element) Remove() error {
715 _, err := el.Eval(`() => this.remove()`)
716 if err != nil {
717 return err
718 }
719 return el.Release()
720}
721
722// Call implements the [proto.Client].
723func (el *Element) Call(ctx context.Context, sessionID, methodName string, params interface{}) (res []byte, err error) {
724 return el.page.Call(ctx, sessionID, methodName, params)
725}
726
727// Eval is a shortcut for [Element.Evaluate] with AwaitPromise, ByValue and AutoExp set to true.
728func (el *Element) Eval(js string, params ...interface{}) (*proto.RuntimeRemoteObject, error) {
729 return el.Evaluate(Eval(js, params...).ByPromise())
730}
731
732// Evaluate is just a shortcut of [Page.Evaluate] with This set to current element.
733func (el *Element) Evaluate(opts *EvalOptions) (*proto.RuntimeRemoteObject, error) {
734 return el.page.Context(el.ctx).Evaluate(opts.This(el.Object))
735}
736
737// Equal checks if the two elements are equal.
738func (el *Element) Equal(elm *Element) (bool, error) {
739 res, err := el.Eval(`elm => this === elm`, elm.Object)
740 return res.Value.Bool(), err
741}
742
743func (el *Element) id() proto.RuntimeRemoteObjectID {
744 return el.Object.ObjectID
745}
746
747// GetXPath returns the xpath of the element.
748func (el *Element) GetXPath(optimized bool) (string, error) {
749 str, err := el.Evaluate(evalHelper(js.GetXPath, optimized))
750 if err != nil {
751 return "", err
752 }
753 return str.Value.String(), nil
754}