-
Notifications
You must be signed in to change notification settings - Fork 41
/
element_handle.go
1568 lines (1418 loc) · 46.2 KB
/
element_handle.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package common
import (
"context"
"errors"
"fmt"
"math"
"reflect"
"strings"
"time"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/dom"
cdppage "github.com/chromedp/cdproto/page"
"github.com/dop251/goja"
"go.opentelemetry.io/otel/attribute"
"github.com/grafana/xk6-browser/common/js"
"github.com/grafana/xk6-browser/k6ext"
)
const resultDone = "done"
type (
elementHandleActionFunc func(context.Context, *ElementHandle) (any, error)
elementHandlePointerActionFunc func(context.Context, *ElementHandle, *Position) (any, error)
retryablePointerActionFunc func(context.Context, *ScrollIntoViewOptions) (any, error)
// evalFunc is a common interface for both evalWithScript and eval.
// It helps abstracting these methods to aid with testing.
evalFunc func(ctx context.Context, opts evalOptions, js string, args ...any) (any, error)
)
// ElementHandle represents a HTML element JS object inside an execution context.
type ElementHandle struct {
BaseJSHandle
frame *Frame
}
func (h *ElementHandle) boundingBox() (*Rect, error) {
var box *dom.BoxModel
var err error
action := dom.GetBoxModel().WithObjectID(h.remoteObject.ObjectID)
if box, err = action.Do(cdp.WithExecutor(h.ctx, h.session)); err != nil {
return nil, fmt.Errorf("getting bounding box model of DOM node: %w", err)
}
quad := box.Border
x := math.Min(quad[0], math.Min(quad[2], math.Min(quad[4], quad[6])))
y := math.Min(quad[1], math.Min(quad[3], math.Min(quad[5], quad[7])))
width := math.Max(quad[0], math.Max(quad[2], math.Max(quad[4], quad[6]))) - x
height := math.Max(quad[1], math.Max(quad[3], math.Max(quad[5], quad[7]))) - y
position, err := h.frame.position()
if err != nil {
return nil, err
}
return &Rect{X: x + position.X, Y: y + position.Y, Width: width, Height: height}, nil
}
func (h *ElementHandle) checkHitTargetAt(apiCtx context.Context, point Position) (bool, error) {
frame := h.ownerFrame(apiCtx)
if frame != nil && frame.parentFrame != nil {
el, err := h.frame.FrameElement()
if err != nil {
return false, err
}
box, err := el.boundingBox()
if err != nil {
return false, err
}
if box == nil {
return false, errors.New("missing bounding box of element")
}
// Translate from viewport coordinates to frame coordinates.
point.X -= box.X
point.Y -= box.Y
}
fn := `
(node, injected, point) => {
return injected.checkHitTargetAt(node, point);
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: true,
}
result, err := h.evalWithScript(h.ctx, opts, fn, point)
if err != nil {
return false, err
}
// Either we're done or an error happened (returned as "error:..." from JS)
const done = "done"
v, ok := result.(goja.Value)
if !ok {
return false, fmt.Errorf("unexpected type %T", result)
}
if v.ExportType().Kind() != reflect.String {
// We got a { hitTargetDescription: ... } result
// Meaning: Another element is preventing pointer events.
//
// It's safe to count an object return as an interception.
// We just don't interpret what is intercepting with the target element
// because we don't need any more functionality from this JS function
// right now.
return false, errorFromDOMError("error:intercept")
} else if v.String() != done {
return false, errorFromDOMError(v.String())
}
return true, nil
}
func (h *ElementHandle) checkElementState(_ context.Context, state string) (*bool, error) {
fn := `
(node, injected, state) => {
return injected.checkElementState(node, state);
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: true,
}
result, err := h.evalWithScript(h.ctx, opts, fn, state)
if err != nil {
return nil, err
}
v, ok := result.(goja.Value)
if !ok {
return nil, fmt.Errorf("unexpected type %T", result)
}
//nolint:exhaustive
switch v.ExportType().Kind() {
case reflect.String: // An error happened (returned as "error:..." from JS)
return nil, errorFromDOMError(v.String())
case reflect.Bool:
returnVal := new(bool)
*returnVal = v.ToBoolean()
return returnVal, nil
}
return nil, fmt.Errorf(
"checking state %q of element %q", state, reflect.TypeOf(result))
}
func (h *ElementHandle) click(p *Position, opts *MouseClickOptions) error {
return h.frame.page.Mouse.click(p.X, p.Y, opts)
}
func (h *ElementHandle) clickablePoint() (*Position, error) {
var (
quads []dom.Quad
err error
)
getContentQuads := dom.GetContentQuads().WithObjectID(h.remoteObject.ObjectID)
if quads, err = getContentQuads.Do(cdp.WithExecutor(h.ctx, h.session)); err != nil {
return nil, fmt.Errorf("getting node content quads %T: %w", getContentQuads, err)
}
if len(quads) == 0 {
return nil, fmt.Errorf("node is either not visible or not an HTMLElement: %w", err)
}
// Filter out quads that have too small area to click into.
var layoutViewport *cdppage.LayoutViewport
getLayoutMetrics := cdppage.GetLayoutMetrics()
if _, _, _, layoutViewport, _, _, err = getLayoutMetrics.Do(cdp.WithExecutor(h.ctx, h.session)); err != nil {
return nil, fmt.Errorf("getting page layout metrics %T: %w", getLayoutMetrics, err)
}
return filterQuads(layoutViewport.ClientWidth, layoutViewport.ClientHeight, quads)
}
func filterQuads(viewportWidth, viewportHeight int64, quads []dom.Quad) (*Position, error) {
var filteredQuads []dom.Quad
for _, q := range quads {
// Keep the points within the viewport and positive.
nq := q
for i := 0; i < len(q); i += 2 {
nq[i] = math.Min(math.Max(q[i], 0), float64(viewportWidth))
nq[i+1] = math.Min(math.Max(q[i+1], 0), float64(viewportHeight))
}
// Compute sum of all directed areas of adjacent triangles
// https://en.wikipedia.org/wiki/Polygon#Area
var area float64
for i := 0; i < len(q); i += 2 {
p2 := (i + 2) % (len(q) / 2)
area += (q[i]*q[p2+1] - q[p2]*q[i+1]) / 2
}
// We don't want to click on something less than a pixel.
if math.Abs(area) > 0.99 {
filteredQuads = append(filteredQuads, q)
}
}
if len(filteredQuads) == 0 {
return nil, errors.New("node is either not visible or not an HTMLElement")
}
// Return the middle point of the first quad.
var (
first = filteredQuads[0]
l = len(first)
n = (float64(l) / 2)
p Position
)
for i := 0; i < l; i += 2 {
p.X += first[i] / n
p.Y += first[i+1] / n
}
p = compensateHalfIntegerRoundingError(p)
return &p, nil
}
// Firefox internally uses integer coordinates, so 8.5 is converted to 9 when clicking.
//
// This does not work nicely for small elements. For example, 1x1 square with corners
// (8;8) and (9;9) is targeted when clicking at (8;8) but not when clicking at (9;9).
// So, clicking at (8.5;8.5) will effectively click at (9;9) and miss the target.
//
// Therefore, we skew half-integer values from the interval (8.49, 8.51) towards
// (8.47, 8.49) that is rounded towards 8. This means clicking at (8.5;8.5) will
// be replaced with (8.48;8.48) and will effectively click at (8;8).
//
// Other browsers use float coordinates, so this change should not matter.
func compensateHalfIntegerRoundingError(p Position) Position {
if rx := p.X - math.Floor(p.X); rx > 0.49 && rx < 0.51 {
p.X -= 0.02
}
if ry := p.Y - math.Floor(p.Y); ry > 0.49 && ry < 0.51 {
p.Y -= 0.02
}
return p
}
func (h *ElementHandle) dblClick(p *Position, opts *MouseClickOptions) error {
return h.frame.page.Mouse.click(p.X, p.Y, opts)
}
func (h *ElementHandle) defaultTimeout() time.Duration {
return h.frame.manager.timeoutSettings.timeout()
}
func (h *ElementHandle) dispatchEvent(_ context.Context, typ string, eventInit goja.Value) (any, error) {
fn := `
(node, injected, type, eventInit) => {
injected.dispatchEvent(node, type, eventInit);
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: true,
}
_, err := h.evalWithScript(h.ctx, opts, fn, typ, eventInit)
return nil, err
}
func (h *ElementHandle) fill(_ context.Context, value string) error {
fn := `
(node, injected, value) => {
return injected.fill(node, value);
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: true,
}
result, err := h.evalWithScript(h.ctx, opts, fn, value)
if err != nil {
return err
}
v, ok := result.(goja.Value)
if !ok {
return fmt.Errorf("unexpected type %T", result)
}
if s := v.String(); s != resultDone {
// Either we're done or an error happened (returned as "error:..." from JS)
return errorFromDOMError(s)
}
return nil
}
func (h *ElementHandle) focus(apiCtx context.Context, resetSelectionIfNotFocused bool) error {
fn := `
(node, injected, resetSelectionIfNotFocused) => {
return injected.focusNode(node, resetSelectionIfNotFocused);
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: true,
}
result, err := h.evalWithScript(apiCtx, opts, fn, resetSelectionIfNotFocused)
if err != nil {
return err
}
switch result := result.(type) {
case string: // Either we're done or an error happened (returned as "error:..." from JS)
if result != "done" {
return errorFromDOMError(result)
}
}
return nil
}
func (h *ElementHandle) getAttribute(apiCtx context.Context, name string) (any, error) {
js := `
(element) => {
return element.getAttribute('` + name + `');
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: true,
}
return h.eval(apiCtx, opts, js)
}
func (h *ElementHandle) hover(apiCtx context.Context, p *Position) error {
return h.frame.page.Mouse.move(p.X, p.Y, NewMouseMoveOptions())
}
func (h *ElementHandle) innerHTML(apiCtx context.Context) (any, error) {
js := `
(element) => {
return element.innerHTML;
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: true,
}
return h.eval(apiCtx, opts, js)
}
func (h *ElementHandle) innerText(apiCtx context.Context) (any, error) {
js := `
(element) => {
return element.innerText;
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: true,
}
return h.eval(apiCtx, opts, js)
}
func (h *ElementHandle) inputValue(apiCtx context.Context) (any, error) {
js := `
(element) => {
if (element.nodeType !== Node.ELEMENT_NODE || (element.nodeName !== 'INPUT' && element.nodeName !== 'TEXTAREA' && element.nodeName !== 'SELECT')) {
throw Error('Node is not an <input>, <textarea> or <select> element');
}
return element.value;
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: true,
}
return h.eval(apiCtx, opts, js)
}
func (h *ElementHandle) isChecked(apiCtx context.Context, timeout time.Duration) (bool, error) {
return h.waitForElementState(apiCtx, []string{"checked"}, timeout)
}
func (h *ElementHandle) isDisabled(apiCtx context.Context, timeout time.Duration) (bool, error) {
return h.waitForElementState(apiCtx, []string{"disabled"}, timeout)
}
func (h *ElementHandle) isEditable(apiCtx context.Context, timeout time.Duration) (bool, error) {
return h.waitForElementState(apiCtx, []string{"editable"}, timeout)
}
func (h *ElementHandle) isEnabled(apiCtx context.Context, timeout time.Duration) (bool, error) {
return h.waitForElementState(apiCtx, []string{"enabled"}, timeout)
}
func (h *ElementHandle) isHidden(apiCtx context.Context) (bool, error) {
return h.waitForElementState(apiCtx, []string{"hidden"}, 0)
}
func (h *ElementHandle) isVisible(apiCtx context.Context) (bool, error) {
return h.waitForElementState(apiCtx, []string{"visible"}, 0)
}
func (h *ElementHandle) offsetPosition(apiCtx context.Context, offset *Position) (*Position, error) {
fn := `
(node, injected) => {
return injected.getElementBorderWidth(node);
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: true,
}
result, err := h.evalWithScript(apiCtx, opts, fn)
if err != nil {
return nil, err
}
rt := h.execCtx.vu.Runtime()
var border struct{ Top, Left float64 }
switch result := result.(type) {
case goja.Value:
if result != nil && !goja.IsUndefined(result) && !goja.IsNull(result) {
obj := result.ToObject(rt)
for _, k := range obj.Keys() {
switch k {
case "left":
border.Left = obj.Get(k).ToFloat()
case "top":
border.Top = obj.Get(k).ToFloat()
}
}
}
}
box := h.BoundingBox()
if box == nil || (border.Left == 0 && border.Top == 0) {
return nil, errorFromDOMError("error:notvisible")
}
// Make point relative to the padding box to align with offsetX/offsetY.
return &Position{
X: box.X + border.Left + offset.X,
Y: box.Y + border.Top + offset.Y,
}, nil
}
func (h *ElementHandle) ownerFrame(apiCtx context.Context) *Frame {
frameId := h.frame.page.getOwnerFrame(apiCtx, h)
if frameId == "" {
return nil
}
frame, ok := h.frame.page.frameManager.getFrameByID(frameId)
if ok {
return frame
}
for _, page := range h.frame.page.browserCtx.browser.pages {
frame, ok = page.frameManager.getFrameByID(frameId)
if ok {
return frame
}
}
return nil
}
func (h *ElementHandle) scrollRectIntoViewIfNeeded(apiCtx context.Context, rect *dom.Rect) error {
action := dom.ScrollIntoViewIfNeeded().WithObjectID(h.remoteObject.ObjectID).WithRect(rect)
err := action.Do(cdp.WithExecutor(apiCtx, h.session))
if err != nil {
if strings.Contains(err.Error(), "Node does not have a layout object") {
return errorFromDOMError("error:notvisible")
}
if strings.Contains(err.Error(), "Node is detached from document") {
return errorFromDOMError("error:notconnected")
}
return err
}
return nil
}
func (h *ElementHandle) press(apiCtx context.Context, key string, opts *KeyboardOptions) error {
err := h.focus(apiCtx, true)
if err != nil {
return err
}
err = h.frame.page.Keyboard.comboPress(key, opts)
if err != nil {
return err
}
return nil
}
//nolint:funlen,gocognit,cyclop
func (h *ElementHandle) selectOption(apiCtx context.Context, values goja.Value) (any, error) {
convertSelectOptionValues := func(values goja.Value) ([]any, error) {
if goja.IsNull(values) || goja.IsUndefined(values) {
return nil, nil
}
var (
opts []any
t = values.Export()
rt = h.execCtx.vu.Runtime()
)
switch values.ExportType().Kind() {
case reflect.Map:
s := reflect.ValueOf(t)
for i := 0; i < s.Len(); i++ {
item := s.Index(i)
switch item.Kind() {
case reflect.TypeOf(nil).Kind():
return nil, fmt.Errorf("options[%d]: expected object, got null", i)
case reflect.TypeOf(&ElementHandle{}).Kind():
opts = append(opts, t.(*ElementHandle))
case reflect.TypeOf(goja.Object{}).Kind():
obj := values.ToObject(rt)
opt := SelectOption{}
for _, k := range obj.Keys() {
switch k {
case "value":
opt.Value = new(string)
*opt.Value = obj.Get(k).String()
case "label":
opt.Label = new(string)
*opt.Label = obj.Get(k).String()
case "index":
opt.Index = new(int64)
*opt.Index = obj.Get(k).ToInteger()
}
}
opts = append(opts, &opt)
case reflect.String:
opt := SelectOption{Value: new(string)}
*opt.Value = item.String()
opts = append(opts, &opt)
}
}
case reflect.TypeOf(&ElementHandle{}).Kind():
opts = append(opts, t.(*ElementHandle))
case reflect.TypeOf(goja.Object{}).Kind():
obj := values.ToObject(rt)
opt := SelectOption{}
for _, k := range obj.Keys() {
switch k {
case "value":
opt.Value = new(string)
*opt.Value = obj.Get(k).String()
case "label":
opt.Label = new(string)
*opt.Label = obj.Get(k).String()
case "index":
opt.Index = new(int64)
*opt.Index = obj.Get(k).ToInteger()
}
}
opts = append(opts, &opt)
case reflect.String:
opt := SelectOption{Value: new(string)}
*opt.Value = t.(string)
opts = append(opts, &opt)
}
return opts, nil
}
convValues, err := convertSelectOptionValues(values)
if err != nil {
return nil, err
}
fn := `
(node, injected, values) => {
return injected.selectOptions(node, values);
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: false,
}
result, err := h.evalWithScript(apiCtx, opts, fn, convValues)
if err != nil {
return nil, err
}
switch result := result.(type) {
case string: // An error happened (returned as "error:..." from JS)
if result != "done" {
return nil, errorFromDOMError(result)
}
}
return result, nil
}
func (h *ElementHandle) selectText(apiCtx context.Context) error {
fn := `
(node, injected) => {
return injected.selectText(node);
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: true,
}
result, err := h.evalWithScript(apiCtx, opts, fn)
if err != nil {
return err
}
switch result := result.(type) {
case string: // Either we're done or an error happened (returned as "error:..." from JS)
if result != "done" {
return errorFromDOMError(result)
}
}
return nil
}
func (h *ElementHandle) tap(apiCtx context.Context, p *Position) error {
return h.frame.page.Touchscreen.tap(p.X, p.Y)
}
func (h *ElementHandle) textContent(apiCtx context.Context) (any, error) {
js := `
(element) => {
return element.textContent;
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: true,
}
return h.eval(apiCtx, opts, js)
}
func (h *ElementHandle) typ(apiCtx context.Context, text string, opts *KeyboardOptions) error {
err := h.focus(apiCtx, true)
if err != nil {
return err
}
err = h.frame.page.Keyboard.typ(text, opts)
if err != nil {
return err
}
return nil
}
func (h *ElementHandle) waitAndScrollIntoViewIfNeeded(apiCtx context.Context, force, noWaitAfter bool, timeout time.Duration) error {
fn := func(apiCtx context.Context, handle *ElementHandle) (any, error) {
fn := `
(element) => {
element.scrollIntoViewIfNeeded(true);
return [window.scrollX, window.scrollY];
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: true,
}
return h.eval(apiCtx, opts, fn)
}
actFn := h.newAction([]string{"visible", "stable"}, fn, force, noWaitAfter, timeout)
_, err := call(h.ctx, actFn, timeout)
return err
}
func (h *ElementHandle) waitForElementState(
apiCtx context.Context, states []string, timeout time.Duration,
) (bool, error) {
fn := `
(node, injected, states, timeout) => {
return injected.waitForElementStates(node, states, timeout);
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: true,
}
result, err := h.evalWithScript(apiCtx, opts, fn, states, timeout.Milliseconds())
if err != nil {
return false, errorFromDOMError(err)
}
v, ok := result.(goja.Value)
if !ok {
return false, fmt.Errorf("unexpected type %T", result)
}
//nolint:exhaustive
switch v.ExportType().Kind() {
case reflect.String: // Either we're done or an error happened (returned as "error:..." from JS)
if v.String() == "done" {
return true, nil
}
return false, errorFromDOMError(v.String())
case reflect.Bool:
return v.ToBoolean(), nil
}
return false, fmt.Errorf(
"waiting for states %v of element %q", states, reflect.TypeOf(result))
}
func (h *ElementHandle) waitForSelector(apiCtx context.Context, selector string, opts *FrameWaitForSelectorOptions) (*ElementHandle, error) {
parsedSelector, err := NewSelector(selector)
if err != nil {
return nil, err
}
fn := `
(node, injected, selector, strict, state, timeout, ...args) => {
return injected.waitForSelector(selector, node, strict, state, 'raf', timeout, ...args);
}
`
eopts := evalOptions{
forceCallable: true,
returnByValue: false,
}
result, err := h.evalWithScript(
apiCtx,
eopts, fn, parsedSelector,
opts.Strict, opts.State.String(), opts.Timeout.Milliseconds(),
)
if err != nil {
return nil, err
}
switch r := result.(type) {
case *ElementHandle:
return r, nil
default:
return nil, nil
}
}
// AsElement returns this element handle.
func (h *ElementHandle) AsElement() *ElementHandle {
return h
}
// BoundingBox returns this element's bounding box.
func (h *ElementHandle) BoundingBox() *Rect {
bbox, err := h.boundingBox()
if err != nil {
return nil // Don't panic here, just return nil
}
return bbox
}
// Click scrolls element into view and clicks in the center of the element
// TODO: look into making more robust using retries
// (see: https://github.com/microsoft/playwright/blob/master/src/server/dom.ts#L298)
func (h *ElementHandle) Click(opts goja.Value) error {
actionOpts := NewElementHandleClickOptions(h.defaultTimeout())
if err := actionOpts.Parse(h.ctx, opts); err != nil {
k6ext.Panic(h.ctx, "parsing element click options: %v", err)
}
click := h.newPointerAction(
func(apiCtx context.Context, handle *ElementHandle, p *Position) (any, error) {
return nil, handle.click(p, actionOpts.ToMouseClickOptions())
},
&actionOpts.ElementHandleBasePointerOptions,
)
if _, err := call(h.ctx, click, actionOpts.Timeout); err != nil {
return fmt.Errorf("clicking on element: %w", err)
}
applySlowMo(h.ctx)
return nil
}
// ContentFrame returns the frame that contains this element.
func (h *ElementHandle) ContentFrame() (*Frame, error) {
var (
node *cdp.Node
err error
)
action := dom.DescribeNode().WithObjectID(h.remoteObject.ObjectID)
if node, err = action.Do(cdp.WithExecutor(h.ctx, h.session)); err != nil {
return nil, fmt.Errorf("getting remote node %q: %w", h.remoteObject.ObjectID, err)
}
if node == nil || node.FrameID == "" {
return nil, fmt.Errorf("element is not an iframe")
}
frame, ok := h.frame.manager.getFrameByID(node.FrameID)
if !ok {
return nil, fmt.Errorf("frame not found for id %s", node.FrameID)
}
return frame, nil
}
func (h *ElementHandle) Dblclick(opts goja.Value) {
actionOpts := NewElementHandleDblclickOptions(h.defaultTimeout())
if err := actionOpts.Parse(h.ctx, opts); err != nil {
k6ext.Panic(h.ctx, "parsing element double click options: %w", err)
}
fn := func(apiCtx context.Context, handle *ElementHandle, p *Position) (any, error) {
return nil, handle.dblClick(p, actionOpts.ToMouseClickOptions())
}
pointerFn := h.newPointerAction(fn, &actionOpts.ElementHandleBasePointerOptions)
_, err := call(h.ctx, pointerFn, actionOpts.Timeout)
if err != nil {
k6ext.Panic(h.ctx, "double clicking on element: %w", err)
}
applySlowMo(h.ctx)
}
func (h *ElementHandle) DispatchEvent(typ string, eventInit goja.Value) {
fn := func(apiCtx context.Context, handle *ElementHandle) (any, error) {
return handle.dispatchEvent(apiCtx, typ, eventInit)
}
opts := NewElementHandleBaseOptions(h.defaultTimeout())
actFn := h.newAction([]string{}, fn, opts.Force, opts.NoWaitAfter, opts.Timeout)
_, err := call(h.ctx, actFn, opts.Timeout)
if err != nil {
k6ext.Panic(h.ctx, "dispatching element event: %w", err)
}
applySlowMo(h.ctx)
}
func (h *ElementHandle) Fill(value string, opts goja.Value) {
actionOpts := NewElementHandleBaseOptions(h.defaultTimeout())
if err := actionOpts.Parse(h.ctx, opts); err != nil {
k6ext.Panic(h.ctx, "parsing element fill options: %w", err)
}
fn := func(apiCtx context.Context, handle *ElementHandle) (any, error) {
return nil, handle.fill(apiCtx, value)
}
actFn := h.newAction([]string{"visible", "enabled", "editable"},
fn, actionOpts.Force, actionOpts.NoWaitAfter, actionOpts.Timeout)
_, err := call(h.ctx, actFn, actionOpts.Timeout)
if err != nil {
k6ext.Panic(h.ctx, "handling element fill action: %w", err)
}
applySlowMo(h.ctx)
}
// Focus scrolls element into view and focuses the element.
func (h *ElementHandle) Focus() {
fn := func(apiCtx context.Context, handle *ElementHandle) (any, error) {
return nil, handle.focus(apiCtx, false)
}
opts := NewElementHandleBaseOptions(h.defaultTimeout())
actFn := h.newAction([]string{}, fn, opts.Force, opts.NoWaitAfter, opts.Timeout)
_, err := call(h.ctx, actFn, opts.Timeout)
if err != nil {
k6ext.Panic(h.ctx, "focusing on element: %w", err)
}
applySlowMo(h.ctx)
}
// GetAttribute retrieves the value of specified element attribute.
func (h *ElementHandle) GetAttribute(name string) goja.Value {
fn := func(apiCtx context.Context, handle *ElementHandle) (any, error) {
return handle.getAttribute(apiCtx, name)
}
opts := NewElementHandleBaseOptions(h.defaultTimeout())
actFn := h.newAction([]string{}, fn, opts.Force, opts.NoWaitAfter, opts.Timeout)
v, err := call(h.ctx, actFn, opts.Timeout)
if err != nil {
k6ext.Panic(h.ctx, "getting attribute of %q: %q", name, err)
}
applySlowMo(h.ctx)
return asGojaValue(h.ctx, v)
}
// Hover scrolls element into view and hovers over its center point.
func (h *ElementHandle) Hover(opts goja.Value) {
actionOpts := NewElementHandleHoverOptions(h.defaultTimeout())
if err := actionOpts.Parse(h.ctx, opts); err != nil {
k6ext.Panic(h.ctx, "parsing element hover options: %w", err)
}
fn := func(apiCtx context.Context, handle *ElementHandle, p *Position) (any, error) {
return nil, handle.hover(apiCtx, p)
}
pointerFn := h.newPointerAction(fn, &actionOpts.ElementHandleBasePointerOptions)
_, err := call(h.ctx, pointerFn, actionOpts.Timeout)
if err != nil {
k6ext.Panic(h.ctx, "hovering on element: %w", err)
}
applySlowMo(h.ctx)
}
// InnerHTML returns the inner HTML of the element.
func (h *ElementHandle) InnerHTML() string {
fn := func(apiCtx context.Context, handle *ElementHandle) (any, error) {
return handle.innerHTML(apiCtx)
}
opts := NewElementHandleBaseOptions(h.defaultTimeout())
actFn := h.newAction([]string{}, fn, opts.Force, opts.NoWaitAfter, opts.Timeout)
v, err := call(h.ctx, actFn, opts.Timeout)
if err != nil {
k6ext.Panic(h.ctx, "getting element's inner HTML: %w", err)
}
applySlowMo(h.ctx)
return gojaValueToString(h.ctx, v)
}
// InnerText returns the inner text of the element.
func (h *ElementHandle) InnerText() string {
fn := func(apiCtx context.Context, handle *ElementHandle) (any, error) {
return handle.innerText(apiCtx)
}
opts := NewElementHandleBaseOptions(h.defaultTimeout())
actFn := h.newAction([]string{}, fn, opts.Force, opts.NoWaitAfter, opts.Timeout)
v, err := call(h.ctx, actFn, opts.Timeout)
if err != nil {
k6ext.Panic(h.ctx, "getting element's inner text: %w", err)
}
applySlowMo(h.ctx)
return gojaValueToString(h.ctx, v)
}
func (h *ElementHandle) InputValue(opts goja.Value) string {
actionOpts := NewElementHandleBaseOptions(h.defaultTimeout())
if err := actionOpts.Parse(h.ctx, opts); err != nil {
k6ext.Panic(h.ctx, "parsing element input value options: %w", err)
}
fn := func(apiCtx context.Context, handle *ElementHandle) (any, error) {
return handle.inputValue(apiCtx)
}
actFn := h.newAction([]string{}, fn, actionOpts.Force, actionOpts.NoWaitAfter, actionOpts.Timeout)
v, err := call(h.ctx, actFn, actionOpts.Timeout)
if err != nil {
k6ext.Panic(h.ctx, "getting element's input value: %w", err)
}
applySlowMo(h.ctx)
return gojaValueToString(h.ctx, v)
}
// IsChecked checks if a checkbox or radio is checked.
func (h *ElementHandle) IsChecked() bool {
result, err := h.isChecked(h.ctx, 0)
if err != nil && !errors.Is(err, ErrTimedOut) { // We don't care anout timeout errors here!
k6ext.Panic(h.ctx, "checking element is checked: %w", err)
}
return result
}
// IsDisabled checks if the element is disabled.
func (h *ElementHandle) IsDisabled() bool {
result, err := h.isDisabled(h.ctx, 0)
if err != nil && !errors.Is(err, ErrTimedOut) { // We don't care anout timeout errors here!
k6ext.Panic(h.ctx, "checking element is disabled: %w", err)
}
return result
}
// IsEditable checks if the element is editable.
func (h *ElementHandle) IsEditable() bool {
result, err := h.isEditable(h.ctx, 0)
if err != nil && !errors.Is(err, ErrTimedOut) { // We don't care anout timeout errors here!
k6ext.Panic(h.ctx, "checking element is editable: %w", err)
}
return result
}
// IsEnabled checks if the element is enabled.
func (h *ElementHandle) IsEnabled() bool {
result, err := h.isEnabled(h.ctx, 0)
if err != nil && !errors.Is(err, ErrTimedOut) { // We don't care anout timeout errors here!
k6ext.Panic(h.ctx, "checking element is enabled: %w", err)
}
return result
}
// IsHidden checks if the element is hidden.
func (h *ElementHandle) IsHidden() bool {
result, err := h.isHidden(h.ctx)
if err != nil && !errors.Is(err, ErrTimedOut) { // We don't care anout timeout errors here!
k6ext.Panic(h.ctx, "checking element is hidden: %w", err)
}
return result
}
// IsVisible checks if the element is visible.
func (h *ElementHandle) IsVisible() bool {
result, err := h.isVisible(h.ctx)
if err != nil && !errors.Is(err, ErrTimedOut) { // We don't care anout timeout errors here!
k6ext.Panic(h.ctx, "checking element is visible: %w", err)
}
return result
}
// OwnerFrame returns the frame containing this element.
func (h *ElementHandle) OwnerFrame() (*Frame, error) {
fn := `
(node, injected) => {
return injected.getDocumentElement(node);
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: false,
}
res, err := h.evalWithScript(h.ctx, opts, fn)
if err != nil {
return nil, fmt.Errorf("getting document element: %w", err)
}
if res == nil {
return nil, errors.New("getting document element: nil document")
}
documentHandle, ok := res.(*ElementHandle)
if !ok {
return nil, fmt.Errorf("unexpected result type while getting document element: %T", res)
}
defer documentHandle.Dispose()
if documentHandle.remoteObject.ObjectID == "" {
return nil, err
}