-
Notifications
You must be signed in to change notification settings - Fork 41
/
frame.go
2000 lines (1673 loc) · 58.5 KB
/
frame.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"
"sync"
"time"
"github.com/grafana/xk6-browser/api"
"github.com/grafana/xk6-browser/k6ext"
"github.com/grafana/xk6-browser/log"
k6modules "go.k6.io/k6/js/modules"
k6metrics "go.k6.io/k6/metrics"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/cdproto/runtime"
"github.com/dop251/goja"
)
// maxRetry controls how many times to retry if an action fails.
const maxRetry = 1
// Ensure frame implements the Frame interface.
var _ api.Frame = &Frame{}
type DocumentInfo struct {
documentID string
request *Request
}
// Frame represents a frame in an HTML document.
type Frame struct {
BaseEventEmitter
ctx context.Context
page *Page
manager *FrameManager
parentFrame *Frame
childFramesMu sync.RWMutex
childFrames map[api.Frame]bool
propertiesMu sync.RWMutex
id cdp.FrameID
loaderID string
name string
url string
detached bool
vu k6modules.VU
initTime time.Time
// A life cycle event is only considered triggered for a frame if the entire
// frame subtree has also had the life cycle event triggered.
lifecycleEventsMu sync.RWMutex
lifecycleEvents map[LifecycleEvent]bool
documentHandle *ElementHandle
executionContextMu sync.RWMutex
executionContexts map[executionWorld]frameExecutionContext
loadingStartedTime time.Time
inflightRequestsMu sync.RWMutex
inflightRequests map[network.RequestID]bool
currentDocument *DocumentInfo
pendingDocumentMu sync.RWMutex
pendingDocument *DocumentInfo
log *log.Logger
}
// NewFrame creates a new HTML document frame.
func NewFrame(
ctx context.Context, m *FrameManager, parentFrame *Frame, frameID cdp.FrameID, log *log.Logger,
) *Frame {
if log.DebugMode() {
var pfid string
if parentFrame != nil {
pfid = parentFrame.ID()
}
var sid string
if m != nil && m.session != nil {
sid = string(m.session.ID())
}
log.Debugf("NewFrame", "sid:%s fid:%s pfid:%s", sid, frameID, pfid)
}
return &Frame{
BaseEventEmitter: NewBaseEventEmitter(ctx),
ctx: ctx,
page: m.page,
manager: m,
parentFrame: parentFrame,
childFrames: make(map[api.Frame]bool),
id: frameID,
vu: k6ext.GetVU(ctx),
lifecycleEvents: make(map[LifecycleEvent]bool),
inflightRequests: make(map[network.RequestID]bool),
executionContexts: make(map[executionWorld]frameExecutionContext),
currentDocument: &DocumentInfo{},
log: log,
}
}
func (f *Frame) addChildFrame(child *Frame) {
f.log.Debugf("Frame:addChildFrame",
"fid:%s cfid:%s furl:%q cfurl:%q",
f.ID(), child.ID(), f.URL(), child.URL())
f.childFramesMu.Lock()
defer f.childFramesMu.Unlock()
f.childFrames[child] = true
}
func (f *Frame) addRequest(id network.RequestID) {
f.log.Debugf("Frame:addRequest", "fid:%s furl:%q rid:%s", f.ID(), f.URL(), id)
f.inflightRequestsMu.Lock()
defer f.inflightRequestsMu.Unlock()
f.inflightRequests[id] = true
}
func (f *Frame) deleteRequest(id network.RequestID) {
f.log.Debugf("Frame:deleteRequest", "fid:%s furl:%q rid:%s", f.ID(), f.URL(), id)
f.inflightRequestsMu.Lock()
defer f.inflightRequestsMu.Unlock()
delete(f.inflightRequests, id)
}
func (f *Frame) inflightRequestsLen() int {
f.inflightRequestsMu.RLock()
defer f.inflightRequestsMu.RUnlock()
return len(f.inflightRequests)
}
func (f *Frame) cloneInflightRequests() map[network.RequestID]bool {
f.inflightRequestsMu.RLock()
defer f.inflightRequestsMu.RUnlock()
ifr := make(map[network.RequestID]bool)
for k, v := range f.inflightRequests {
ifr[k] = v
}
return ifr
}
func (f *Frame) clearLifecycle() {
f.log.Debugf("Frame:clearLifecycle", "fid:%s furl:%q", f.ID(), f.URL())
// clear lifecycle events
f.lifecycleEventsMu.Lock()
f.lifecycleEvents = make(map[LifecycleEvent]bool)
f.lifecycleEventsMu.Unlock()
// keep the request related to the document if present
// in f.inflightRequests
f.inflightRequestsMu.Lock()
{
// currentDocument may not always have a request
// associated with it. see: frame_manager.go
cdr := f.currentDocument.request
inflightRequests := make(map[network.RequestID]bool)
for req := range f.inflightRequests {
if cdr != nil && req != cdr.requestID {
continue
}
inflightRequests[req] = true
}
f.inflightRequests = inflightRequests
}
f.inflightRequestsMu.Unlock()
}
func (f *Frame) detach() {
f.log.Debugf("Frame:detach", "fid:%s furl:%q", f.ID(), f.URL())
f.setDetached(true)
if f.parentFrame != nil {
f.parentFrame.removeChildFrame(f)
}
f.parentFrame = nil
// detach() is called by the same frame Goroutine that manages execution
// context switches. so this should be safe.
// we don't need to protect the following with executionContextMu.
if f.documentHandle != nil {
f.documentHandle.Dispose()
}
}
func (f *Frame) defaultTimeout() time.Duration {
return time.Duration(f.manager.timeoutSettings.timeout()) * time.Second
}
func (f *Frame) document() (*ElementHandle, error) {
f.log.Debugf("Frame:document", "fid:%s furl:%q", f.ID(), f.URL())
if cdh, ok := f.cachedDocumentHandle(); ok {
return cdh, nil
}
f.waitForExecutionContext(mainWorld)
dh, err := f.newDocumentHandle()
if err != nil {
return nil, fmt.Errorf("getting new document handle: %w", err)
}
// each execution context switch modifies documentHandle.
// see: nullContext().
f.executionContextMu.Lock()
defer f.executionContextMu.Unlock()
f.documentHandle = dh
return dh, nil
}
func (f *Frame) cachedDocumentHandle() (*ElementHandle, bool) {
// each execution context switch modifies documentHandle.
// see: nullContext().
f.executionContextMu.RLock()
defer f.executionContextMu.RUnlock()
return f.documentHandle, f.documentHandle != nil
}
func (f *Frame) emitMetric(m *k6metrics.Metric, t time.Time) {
value := k6metrics.D(t.Sub(f.initTime))
f.log.Debugf("Frame:emitMetric", "fid:%s furl:%q m:%s init:%q t:%q v:%f",
f.ID(), f.URL(), m.Name, f.initTime, t, value)
if f.initTime.IsZero() {
// Internal race condition: we haven't processed the init/commit event
// yet, so the value will be wrong and emitting the metric would skew
// the results (i.e. the value would be in the order of years). Choose
// the lesser of 2 wrongs for now and ignore it instead.
// See https://github.com/grafana/xk6-browser/discussions/142#discussioncomment-2416943
return
}
state := f.vu.State()
tags := state.Tags.GetCurrentValues().Tags
if state.Options.SystemTags.Has(k6metrics.TagURL) {
tags = tags.With("url", f.URL())
}
k6metrics.PushIfNotDone(f.ctx, state.Samples, k6metrics.ConnectedSamples{
Samples: []k6metrics.Sample{
{
TimeSeries: k6metrics.TimeSeries{Metric: m, Tags: tags},
Value: value,
Time: time.Now(),
},
},
})
}
func (f *Frame) newDocumentHandle() (*ElementHandle, error) {
result, err := f.evaluate(
f.ctx,
mainWorld,
evalOptions{
forceCallable: false,
returnByValue: false,
},
f.vu.Runtime().ToValue("document"),
)
if err != nil {
return nil, fmt.Errorf("getting document element handle: %w", err)
}
if result == nil {
return nil, fmt.Errorf("document element handle is nil")
}
dh, ok := result.(*ElementHandle)
if !ok {
return nil, fmt.Errorf("unexpected document handle type: %T", result)
}
return dh, nil
}
func (f *Frame) hasContext(world executionWorld) bool {
f.executionContextMu.RLock()
defer f.executionContextMu.RUnlock()
return f.executionContexts[world] != nil
}
func (f *Frame) hasLifecycleEventFired(event LifecycleEvent) bool {
f.lifecycleEventsMu.RLock()
defer f.lifecycleEventsMu.RUnlock()
return f.lifecycleEvents[event]
}
func (f *Frame) navigated(name string, url string, loaderID string) {
f.log.Debugf("Frame:navigated", "fid:%s furl:%q lid:%s name:%q url:%q", f.ID(), f.URL(), loaderID, name, url)
f.propertiesMu.Lock()
defer f.propertiesMu.Unlock()
f.name = name
f.url = url
f.loaderID = loaderID
f.page.emit(EventPageFrameNavigated, f)
}
func (f *Frame) nullContext(execCtxID runtime.ExecutionContextID) {
f.log.Debugf("Frame:nullContext", "fid:%s furl:%q ectxid:%d ", f.ID(), f.URL(), execCtxID)
f.executionContextMu.Lock()
defer f.executionContextMu.Unlock()
if ec := f.executionContexts[mainWorld]; ec != nil && ec.ID() == execCtxID {
f.executionContexts[mainWorld] = nil
f.documentHandle = nil
return
}
if ec := f.executionContexts[utilityWorld]; ec != nil && ec.ID() == execCtxID {
f.executionContexts[utilityWorld] = nil
}
}
func (f *Frame) onLifecycleEvent(event LifecycleEvent) {
f.log.Debugf("Frame:onLifecycleEvent", "fid:%s furl:%q event:%s", f.ID(), f.URL(), event)
f.lifecycleEventsMu.Lock()
f.lifecycleEvents[event] = true
f.lifecycleEventsMu.Unlock()
f.emit(EventFrameAddLifecycle, event)
}
func (f *Frame) onLoadingStarted() {
f.log.Debugf("Frame:onLoadingStarted", "fid:%s furl:%q", f.ID(), f.URL())
f.loadingStartedTime = time.Now()
}
func (f *Frame) onLoadingStopped() {
f.log.Debugf("Frame:onLoadingStopped", "fid:%s furl:%q", f.ID(), f.URL())
// TODO: We should start a timer here and allow the user
// to set how long to wait until after onLoadingStopped
// has occurred. The reason we may want a timeout here
// are for websites where they perform many network
// requests so it may take a long time for us to see
// a networkIdle event or we may never see one if the
// website never stops performing network requests.
}
func (f *Frame) position() (*Position, error) {
frame := f.manager.getFrameByID(cdp.FrameID(f.page.targetID))
if frame == nil {
return nil, fmt.Errorf("could not find frame with id %s", f.page.targetID)
}
if frame == f.page.frameManager.MainFrame() {
return &Position{X: 0, Y: 0}, nil
}
element, err := frame.FrameElement()
if err != nil {
return nil, err
}
box := element.BoundingBox()
return &Position{X: box.X, Y: box.Y}, nil
}
func (f *Frame) removeChildFrame(child *Frame) {
f.log.Debugf("Frame:removeChildFrame", "fid:%s furl:%q cfid:%s curl:%q",
f.ID(), f.URL(), child.ID(), child.URL())
f.childFramesMu.Lock()
defer f.childFramesMu.Unlock()
delete(f.childFrames, child)
}
func (f *Frame) requestByID(reqID network.RequestID) *Request {
frameSession := f.page.getFrameSession(cdp.FrameID(f.ID()))
if frameSession == nil {
frameSession = f.page.mainFrameSession
}
return frameSession.networkManager.requestFromID(reqID)
}
func (f *Frame) setContext(world executionWorld, execCtx frameExecutionContext) {
f.executionContextMu.Lock()
defer f.executionContextMu.Unlock()
f.log.Debugf("Frame:setContext", "fid:%s furl:%q ectxid:%d world:%s",
f.ID(), f.URL(), execCtx.ID(), world)
if !world.valid() {
err := fmt.Errorf("unknown world: %q, it should be either main or utility", world)
panic(err)
}
if f.executionContexts[world] != nil {
f.log.Debugf("Frame:setContext", "fid:%s furl:%q ectxid:%d world:%s, world exists",
f.ID(), f.URL(), execCtx.ID(), world)
return
}
f.executionContexts[world] = execCtx
f.log.Debugf("Frame:setContext", "fid:%s furl:%q ectxid:%d world:%s, world set",
f.ID(), f.URL(), execCtx.ID(), world)
}
func (f *Frame) setID(id cdp.FrameID) {
f.propertiesMu.Lock()
defer f.propertiesMu.Unlock()
f.id = id
}
func (f *Frame) waitForExecutionContext(world executionWorld) {
f.log.Debugf("Frame:waitForExecutionContext", "fid:%s furl:%q world:%s",
f.ID(), f.URL(), world)
t := time.NewTicker(50 * time.Millisecond)
defer t.Stop()
for {
select {
case <-t.C:
if f.hasContext(world) {
return
}
case <-f.ctx.Done():
return
}
}
}
func (f *Frame) waitForSelectorRetry(
selector string, opts *FrameWaitForSelectorOptions, retry int,
) (h *ElementHandle, err error) {
for ; retry >= 0; retry-- {
if h, err = f.waitForSelector(selector, opts); err == nil {
return h, nil
}
}
return nil, err
}
func (f *Frame) waitForSelector(selector string, opts *FrameWaitForSelectorOptions) (*ElementHandle, error) {
f.log.Debugf("Frame:waitForSelector", "fid:%s furl:%q sel:%q", f.ID(), f.URL(), selector)
document, err := f.document()
if err != nil {
return nil, err
}
handle, err := document.waitForSelector(f.ctx, selector, opts)
if err != nil {
return nil, err
}
if handle == nil {
// Handle can be nil only for selectors waiting for 'detached' state,
// as there is no longer an ElementHandle representing that element
// in the DOM. Otherwise return error.
if opts.State != DOMElementStateDetached {
return nil, fmt.Errorf("waiting for selector %q did not result in any nodes", selector)
}
return nil, nil //nolint:nilnil
}
// We always return ElementHandles in the main execution context (aka "DOM world")
f.executionContextMu.RLock()
defer f.executionContextMu.RUnlock()
ec := f.executionContexts[mainWorld]
if ec == nil {
return nil, fmt.Errorf("waiting for selector %q: execution context %q not found", selector, mainWorld)
}
// an element should belong to the current execution context.
// otherwise, we should adopt it to this execution context.
if ec != handle.execCtx {
defer handle.Dispose()
if handle, err = ec.adoptElementHandle(handle); err != nil {
return nil, fmt.Errorf("adopting element handle while waiting for selector %q: %w", selector, err)
}
}
return handle, nil
}
// AddScriptTag is not implemented.
func (f *Frame) AddScriptTag(opts goja.Value) {
k6ext.Panic(f.ctx, "Frame.AddScriptTag() has not been implemented yet")
applySlowMo(f.ctx)
}
// AddStyleTag is not implemented.
func (f *Frame) AddStyleTag(opts goja.Value) {
k6ext.Panic(f.ctx, "Frame.AddStyleTag() has not been implemented yet")
applySlowMo(f.ctx)
}
// ChildFrames returns a list of child frames.
func (f *Frame) ChildFrames() []api.Frame {
f.childFramesMu.RLock()
defer f.childFramesMu.RUnlock()
l := make([]api.Frame, 0, len(f.childFrames))
for child := range f.childFrames {
l = append(l, child)
}
return l
}
// Click clicks the first element found that matches selector.
func (f *Frame) Click(selector string, opts goja.Value) error {
f.log.Debugf("Frame:Click", "fid:%s furl:%q sel:%q", f.ID(), f.URL(), selector)
popts := NewFrameClickOptions(f.defaultTimeout())
if err := popts.Parse(f.ctx, opts); err != nil {
k6ext.Panic(f.ctx, "parsing click options %q: %w", selector, err)
}
if err := f.click(selector, popts); err != nil {
return fmt.Errorf("clicking on %q: %w", selector, err)
}
applySlowMo(f.ctx)
return nil
}
func (f *Frame) click(selector string, opts *FrameClickOptions) error {
click := func(apiCtx context.Context, handle *ElementHandle, p *Position) (any, error) {
return nil, handle.click(p, opts.ToMouseClickOptions())
}
act := f.newPointerAction(
selector, DOMElementStateAttached, opts.Strict, click, &opts.ElementHandleBasePointerOptions,
)
if _, err := call(f.ctx, act, opts.Timeout); err != nil {
return errorFromDOMError(err)
}
return nil
}
// Check clicks the first element found that matches selector.
func (f *Frame) Check(selector string, opts goja.Value) {
f.log.Debugf("Frame:Check", "fid:%s furl:%q sel:%q", f.ID(), f.URL(), selector)
popts := NewFrameCheckOptions(f.defaultTimeout())
if err := popts.Parse(f.ctx, opts); err != nil {
k6ext.Panic(f.ctx, "parsing new frame check options: %w", err)
}
if err := f.check(selector, popts); err != nil {
k6ext.Panic(f.ctx, "checking %q: %w", selector, err)
}
applySlowMo(f.ctx)
}
func (f *Frame) check(selector string, opts *FrameCheckOptions) error {
check := func(apiCtx context.Context, handle *ElementHandle, p *Position) (any, error) {
return nil, handle.setChecked(apiCtx, true, p)
}
act := f.newPointerAction(
selector, DOMElementStateAttached, opts.Strict, check, &opts.ElementHandleBasePointerOptions,
)
if _, err := call(f.ctx, act, opts.Timeout); err != nil {
return errorFromDOMError(err)
}
return nil
}
// Uncheck the first found element that matches the selector.
func (f *Frame) Uncheck(selector string, opts goja.Value) {
f.log.Debugf("Frame:Uncheck", "fid:%s furl:%q sel:%q", f.ID(), f.URL(), selector)
popts := NewFrameUncheckOptions(f.defaultTimeout())
if err := popts.Parse(f.ctx, opts); err != nil {
k6ext.Panic(f.ctx, "parsing frame uncheck options %q: %w", selector, err)
}
if err := f.uncheck(selector, popts); err != nil {
k6ext.Panic(f.ctx, "unchecking %q: %w", selector, err)
}
applySlowMo(f.ctx)
}
func (f *Frame) uncheck(selector string, opts *FrameUncheckOptions) error {
uncheck := func(apiCtx context.Context, handle *ElementHandle, p *Position) (any, error) {
return nil, handle.setChecked(apiCtx, false, p)
}
act := f.newPointerAction(
selector, DOMElementStateAttached, opts.Strict, uncheck, &opts.ElementHandleBasePointerOptions,
)
if _, err := call(f.ctx, act, opts.Timeout); err != nil {
return errorFromDOMError(err)
}
return nil
}
// IsChecked returns true if the first element that matches the selector
// is checked. Otherwise, returns false.
func (f *Frame) IsChecked(selector string, opts goja.Value) bool {
f.log.Debugf("Frame:IsChecked", "fid:%s furl:%q sel:%q", f.ID(), f.URL(), selector)
popts := NewFrameIsCheckedOptions(f.defaultTimeout())
if err := popts.Parse(f.ctx, opts); err != nil {
k6ext.Panic(f.ctx, "parsing is checked options: %w", err)
}
checked, err := f.isChecked(selector, popts)
if err != nil {
k6ext.Panic(f.ctx, "checking element is checked %q: %w", selector, err)
}
return checked
}
func (f *Frame) isChecked(selector string, opts *FrameIsCheckedOptions) (bool, error) {
isChecked := func(apiCtx context.Context, handle *ElementHandle) (any, error) {
v, err := handle.isChecked(apiCtx, 0) // Zero timeout when checking state
if errors.Is(err, ErrTimedOut) { // We don't care about timeout errors here!
return v, nil
}
return v, err
}
act := f.newAction(
selector, DOMElementStateAttached, opts.Strict, isChecked, []string{}, false, true, opts.Timeout,
)
v, err := call(f.ctx, act, opts.Timeout)
if err != nil {
return false, errorFromDOMError(err)
}
bv, ok := v.(bool)
if !ok {
return false, fmt.Errorf("checking is %q checked: unexpected type %T", selector, v)
}
return bv, nil
}
// Content returns the HTML content of the frame.
func (f *Frame) Content() string {
f.log.Debugf("Frame:Content", "fid:%s furl:%q", f.ID(), f.URL())
rt := f.vu.Runtime()
js := `() => {
let content = '';
if (document.doctype) {
content = new XMLSerializer().serializeToString(document.doctype);
}
if (document.documentElement) {
content += document.documentElement.outerHTML;
}
return content;
}`
return gojaValueToString(f.ctx, f.Evaluate(rt.ToValue(js)))
}
// Dblclick double clicks an element matching provided selector.
func (f *Frame) Dblclick(selector string, opts goja.Value) {
f.log.Debugf("Frame:DblClick", "fid:%s furl:%q sel:%q", f.ID(), f.URL(), selector)
popts := NewFrameDblClickOptions(f.defaultTimeout())
if err := popts.Parse(f.ctx, opts); err != nil {
k6ext.Panic(f.ctx, "parsing double click options: %w", err)
}
if err := f.dblclick(selector, popts); err != nil {
k6ext.Panic(f.ctx, "double clicking on %q: %w", selector, err)
}
applySlowMo(f.ctx)
}
// dblclick is like Dblclick but takes parsed options and neither throws
// an error, or applies slow motion.
func (f *Frame) dblclick(selector string, opts *FrameDblclickOptions) error {
dblclick := func(apiCtx context.Context, eh *ElementHandle, p *Position) (any, error) {
return nil, eh.dblClick(p, opts.ToMouseClickOptions())
}
act := f.newPointerAction(
selector, DOMElementStateAttached, opts.Strict, dblclick, &opts.ElementHandleBasePointerOptions,
)
if _, err := call(f.ctx, act, opts.Timeout); err != nil {
return errorFromDOMError(err)
}
return nil
}
// DispatchEvent dispatches an event for the first element matching the selector.
func (f *Frame) DispatchEvent(selector, typ string, eventInit, opts goja.Value) {
f.log.Debugf("Frame:DispatchEvent", "fid:%s furl:%q sel:%q typ:%q", f.ID(), f.URL(), selector, typ)
popts := NewFrameDispatchEventOptions(f.defaultTimeout())
if err := popts.Parse(f.ctx, opts); err != nil {
k6ext.Panic(f.ctx, "parsing dispatch event options: %w", err)
}
if err := f.dispatchEvent(selector, typ, eventInit, popts); err != nil {
k6ext.Panic(f.ctx, "dispatching event %q to %q: %w", typ, selector, err)
}
applySlowMo(f.ctx)
}
// dispatchEvent is like DispatchEvent but takes parsed options and neither throws
// an error, or applies slow motion.
func (f *Frame) dispatchEvent(selector, typ string, eventInit goja.Value, opts *FrameDispatchEventOptions) error {
dispatchEvent := func(apiCtx context.Context, handle *ElementHandle) (any, error) {
return handle.dispatchEvent(apiCtx, typ, eventInit)
}
const (
force = false
noWaitAfter = false
)
act := f.newAction(
selector, DOMElementStateAttached, opts.Strict, dispatchEvent, []string{},
force, noWaitAfter, opts.Timeout,
)
if _, err := call(f.ctx, act, opts.Timeout); err != nil {
return errorFromDOMError(err)
}
return nil
}
// Evaluate will evaluate provided page function within an execution context.
func (f *Frame) Evaluate(pageFunc goja.Value, args ...goja.Value) any {
f.log.Debugf("Frame:Evaluate", "fid:%s furl:%q", f.ID(), f.URL())
f.waitForExecutionContext(mainWorld)
opts := evalOptions{
forceCallable: true,
returnByValue: true,
}
result, err := f.evaluate(f.ctx, mainWorld, opts, pageFunc, args...)
if err != nil {
k6ext.Panic(f.ctx, "evaluating JS: %v", err)
}
applySlowMo(f.ctx)
return result
}
// EvaluateHandle will evaluate provided page function within an execution context.
func (f *Frame) EvaluateHandle(pageFunc goja.Value, args ...goja.Value) (handle api.JSHandle, _ error) {
f.log.Debugf("Frame:EvaluateHandle", "fid:%s furl:%q", f.ID(), f.URL())
f.waitForExecutionContext(mainWorld)
var err error
f.executionContextMu.RLock()
{
ec := f.executionContexts[mainWorld]
if ec == nil {
k6ext.Panic(f.ctx, "evaluating handle for frame: execution context %q not found", mainWorld)
}
handle, err = ec.EvalHandle(f.ctx, pageFunc, args...)
}
f.executionContextMu.RUnlock()
if err != nil {
return nil, fmt.Errorf("evaluating handle for frame: %w", err)
}
applySlowMo(f.ctx)
return handle, nil
}
// Fill fills out the first element found that matches the selector.
func (f *Frame) Fill(selector, value string, opts goja.Value) {
f.log.Debugf("Frame:Fill", "fid:%s furl:%q sel:%q val:%q", f.ID(), f.URL(), selector, value)
popts := NewFrameFillOptions(f.defaultTimeout())
if err := popts.Parse(f.ctx, opts); err != nil {
k6ext.Panic(f.ctx, "parsing fill options: %w", err)
}
if err := f.fill(selector, value, popts); err != nil {
k6ext.Panic(f.ctx, "filling %q with %q: %w", selector, value, err)
}
applySlowMo(f.ctx)
}
func (f *Frame) fill(selector, value string, opts *FrameFillOptions) error {
fill := func(apiCtx context.Context, handle *ElementHandle) (any, error) {
return nil, handle.fill(apiCtx, value)
}
act := f.newAction(
selector, DOMElementStateAttached, opts.Strict,
fill, []string{"visible", "enabled", "editable"},
opts.Force, opts.NoWaitAfter, opts.Timeout,
)
if _, err := call(f.ctx, act, opts.Timeout); err != nil {
return errorFromDOMError(err)
}
return nil
}
// Focus focuses on the first element that matches the selector.
func (f *Frame) Focus(selector string, opts goja.Value) {
f.log.Debugf("Frame:Focus", "fid:%s furl:%q sel:%q", f.ID(), f.URL(), selector)
popts := NewFrameBaseOptions(f.defaultTimeout())
if err := popts.Parse(f.ctx, opts); err != nil {
k6ext.Panic(f.ctx, "parsing focus options: %w", err)
}
if err := f.focus(selector, popts); err != nil {
k6ext.Panic(f.ctx, "focusing %q: %w", selector, err)
}
applySlowMo(f.ctx)
}
func (f *Frame) focus(selector string, opts *FrameBaseOptions) error {
focus := func(apiCtx context.Context, handle *ElementHandle) (any, error) {
return nil, handle.focus(apiCtx, true)
}
act := f.newAction(
selector, DOMElementStateAttached, opts.Strict, focus,
[]string{}, false, true, opts.Timeout,
)
if _, err := call(f.ctx, act, opts.Timeout); err != nil {
return errorFromDOMError(err)
}
return nil
}
// FrameElement returns the element handle for the frame.
func (f *Frame) FrameElement() (api.ElementHandle, error) {
f.log.Debugf("Frame:FrameElement", "fid:%s furl:%q", f.ID(), f.URL())
element, err := f.page.getFrameElement(f)
if err != nil {
return nil, fmt.Errorf("getting frame element: %w", err)
}
return element, nil
}
// GetAttribute of the first element found that matches the selector.
func (f *Frame) GetAttribute(selector, name string, opts goja.Value) goja.Value {
f.log.Debugf("Frame:GetAttribute", "fid:%s furl:%q sel:%q name:%s", f.ID(), f.URL(), selector, name)
popts := NewFrameBaseOptions(f.defaultTimeout())
if err := popts.Parse(f.ctx, opts); err != nil {
k6ext.Panic(f.ctx, "parse: %w", err)
}
v, err := f.getAttribute(selector, name, popts)
if err != nil {
k6ext.Panic(f.ctx, "getting attribute %q of %q: %w", name, selector, err)
}
applySlowMo(f.ctx)
return v
}
func (f *Frame) getAttribute(selector, name string, opts *FrameBaseOptions) (goja.Value, error) {
getAttribute := func(apiCtx context.Context, handle *ElementHandle) (any, error) {
return handle.getAttribute(apiCtx, name)
}
act := f.newAction(
selector, DOMElementStateAttached, opts.Strict, getAttribute,
[]string{}, false, true, opts.Timeout,
)
v, err := call(f.ctx, act, opts.Timeout)
if err != nil {
return nil, errorFromDOMError(err)
}
gv, ok := v.(goja.Value)
if !ok {
return nil, fmt.Errorf("getting %q attribute of %q: unexpected type %T", name, selector, v)
}
return gv, nil
}
// Goto will navigate the frame to the specified URL and return a HTTP response object.
func (f *Frame) Goto(url string, opts goja.Value) (api.Response, error) {
var (
netMgr = f.manager.page.mainFrameSession.getNetworkManager()
defaultReferer = netMgr.extraHTTPHeaders["referer"]
parsedOpts = NewFrameGotoOptions(
defaultReferer,
time.Duration(f.manager.timeoutSettings.navigationTimeout())*time.Second,
)
)
if err := parsedOpts.Parse(f.ctx, opts); err != nil {
return nil, fmt.Errorf("parsing frame navigation options to %q: %w", url, err)
}
resp, err := f.manager.NavigateFrame(f, url, parsedOpts)
if err != nil {
return nil, fmt.Errorf("navigating frame to %q: %w", url, err)
}
applySlowMo(f.ctx)
// Since response will be in an interface, it will never be nil,
// so we need to return nil explicitly.
if resp == nil {
return nil, nil
}
return resp, nil
}
// Hover moves the pointer over the first element that matches the selector.
func (f *Frame) Hover(selector string, opts goja.Value) {
f.log.Debugf("Frame:Hover", "fid:%s furl:%q sel:%q", f.ID(), f.URL(), selector)
popts := NewFrameHoverOptions(f.defaultTimeout())
if err := popts.Parse(f.ctx, opts); err != nil {
k6ext.Panic(f.ctx, "parsing hover options: %w", err)
}
if err := f.hover(selector, popts); err != nil {
k6ext.Panic(f.ctx, "hovering %q: %w", selector, err)
}
applySlowMo(f.ctx)
}
func (f *Frame) hover(selector string, opts *FrameHoverOptions) error {
hover := func(apiCtx context.Context, handle *ElementHandle, p *Position) (any, error) {
return nil, handle.hover(apiCtx, p)
}
act := f.newPointerAction(
selector, DOMElementStateAttached, opts.Strict, hover, &opts.ElementHandleBasePointerOptions,
)
if _, err := call(f.ctx, act, opts.Timeout); err != nil {
return errorFromDOMError(err)
}
return nil
}
// InnerHTML returns the innerHTML attribute of the first element found
// that matches the selector.
func (f *Frame) InnerHTML(selector string, opts goja.Value) string {
f.log.Debugf("Frame:InnerHTML", "fid:%s furl:%q sel:%q", f.ID(), f.URL(), selector)
popts := NewFrameInnerHTMLOptions(f.defaultTimeout())
if err := popts.Parse(f.ctx, opts); err != nil {
k6ext.Panic(f.ctx, "parsing inner HTML options: %w", err)
}
v, err := f.innerHTML(selector, popts)
if err != nil {
k6ext.Panic(f.ctx, "getting inner HTML of %q: %w", selector, err)
}
applySlowMo(f.ctx)
return v
}
func (f *Frame) innerHTML(selector string, opts *FrameInnerHTMLOptions) (string, error) {
innerHTML := func(apiCtx context.Context, handle *ElementHandle) (any, error) {
return handle.innerHTML(apiCtx)
}
act := f.newAction(
selector, DOMElementStateAttached, opts.Strict, innerHTML,
[]string{}, false, true, opts.Timeout,
)
v, err := call(f.ctx, act, opts.Timeout)
if err != nil {
return "", errorFromDOMError(err)
}
if v == nil {
return "", nil
}
gv, ok := v.(goja.Value)
if !ok {
return "", fmt.Errorf("getting inner html of %q: unexpected type %T", selector, v)
}
return gv.String(), nil
}
// InnerText returns the inner text of the first element found
// that matches the selector.
func (f *Frame) InnerText(selector string, opts goja.Value) string {
f.log.Debugf("Frame:InnerText", "fid:%s furl:%q sel:%q", f.ID(), f.URL(), selector)
popts := NewFrameInnerTextOptions(f.defaultTimeout())
if err := popts.Parse(f.ctx, opts); err != nil {
k6ext.Panic(f.ctx, "parsing inner text options: %w", err)
}
v, err := f.innerText(selector, popts)
if err != nil {
k6ext.Panic(f.ctx, "getting inner text of %q: %w", selector, err)
}