This repository was archived by the owner on Jan 30, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathpage.go
1610 lines (1302 loc) · 48.3 KB
/
page.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 (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/chromedp/cdproto"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/dom"
"github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/page"
cdppage "github.com/chromedp/cdproto/page"
"github.com/chromedp/cdproto/runtime"
cdpruntime "github.com/chromedp/cdproto/runtime"
"github.com/chromedp/cdproto/target"
"github.com/grafana/sobek"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"github.com/grafana/xk6-browser/k6ext"
"github.com/grafana/xk6-browser/log"
k6modules "go.k6.io/k6/js/modules"
)
// BlankPage represents a blank page.
const BlankPage = "about:blank"
// PageOnEventName represents the name of the page.on event.
type PageOnEventName string
const webVitalBinding = "k6browserSendWebVitalMetric"
const (
// EventPageConsoleAPICalled represents the page.on('console') event.
EventPageConsoleAPICalled PageOnEventName = "console"
// EventPageMetricCalled represents the page.on('metric') event.
EventPageMetricCalled PageOnEventName = "metric"
)
// MediaType represents the type of media to emulate.
type MediaType string
const (
// MediaTypeScreen represents the screen media type.
MediaTypeScreen MediaType = "screen"
// MediaTypePrint represents the print media type.
MediaTypePrint MediaType = "print"
)
// ReducedMotion represents a browser reduce-motion setting.
type ReducedMotion string
// Valid reduce-motion options.
const (
ReducedMotionReduce ReducedMotion = "reduce"
ReducedMotionNoPreference ReducedMotion = "no-preference"
)
func (r ReducedMotion) String() string {
return reducedMotionToString[r]
}
var reducedMotionToString = map[ReducedMotion]string{ //nolint:gochecknoglobals
ReducedMotionReduce: "reduce",
ReducedMotionNoPreference: "no-preference",
}
var reducedMotionToID = map[string]ReducedMotion{ //nolint:gochecknoglobals
"reduce": ReducedMotionReduce,
"no-preference": ReducedMotionNoPreference,
}
// MarshalJSON marshals the enum as a quoted JSON string.
func (r ReducedMotion) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString(`"`)
buffer.WriteString(reducedMotionToString[r])
buffer.WriteString(`"`)
return buffer.Bytes(), nil
}
// UnmarshalJSON unmarshals a quoted JSON string to the enum value.
func (r *ReducedMotion) UnmarshalJSON(b []byte) error {
var j string
err := json.Unmarshal(b, &j)
if err != nil {
return fmt.Errorf("unmarshaling %q to ReducedMotion: %w", b, err)
}
// Note that if the string cannot be found then it will be set to the zero value.
*r = reducedMotionToID[j]
return nil
}
// Screen represents a device screen.
type Screen struct {
Width int64 `js:"width"`
Height int64 `js:"height"`
}
// ColorScheme represents a browser color scheme.
type ColorScheme string
// Valid color schemes.
const (
ColorSchemeLight ColorScheme = "light"
ColorSchemeDark ColorScheme = "dark"
ColorSchemeNoPreference ColorScheme = "no-preference"
)
func (c ColorScheme) String() string {
return colorSchemeToString[c]
}
var colorSchemeToString = map[ColorScheme]string{ //nolint:gochecknoglobals
ColorSchemeLight: "light",
ColorSchemeDark: "dark",
ColorSchemeNoPreference: "no-preference",
}
var colorSchemeToID = map[string]ColorScheme{ //nolint:gochecknoglobals
"light": ColorSchemeLight,
"dark": ColorSchemeDark,
"no-preference": ColorSchemeNoPreference,
}
// MarshalJSON marshals the enum as a quoted JSON string.
func (c ColorScheme) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString(`"`)
buffer.WriteString(colorSchemeToString[c])
buffer.WriteString(`"`)
return buffer.Bytes(), nil
}
// UnmarshalJSON unmarshals a quoted JSON string to the enum value.
func (c *ColorScheme) UnmarshalJSON(b []byte) error {
var j string
err := json.Unmarshal(b, &j)
if err != nil {
return fmt.Errorf("unmarshaling %q to ColorScheme: %w", b, err)
}
// Note that if the string cannot be found then it will be set to the zero value.
*c = colorSchemeToID[j]
return nil
}
// EmulatedSize represents the emulated viewport and screen sizes.
type EmulatedSize struct {
Viewport Viewport
Screen Screen
}
// NewEmulatedSize creates and returns a new EmulatedSize.
func NewEmulatedSize(viewport Viewport, screen Screen) *EmulatedSize {
return &EmulatedSize{
Viewport: viewport,
Screen: screen,
}
}
// ConsoleMessage represents a page console message.
type ConsoleMessage struct {
// Args represent the list of arguments passed to a console function call.
Args []JSHandleAPI
// Page is the page that produced the console message, if any.
Page *Page
// Text represents the text of the console message.
Text string
// Type is the type of the console message.
// It can be one of 'log', 'debug', 'info', 'error', 'warning', 'dir', 'dirxml',
// 'table', 'trace', 'clear', 'startGroup', 'startGroupCollapsed', 'endGroup',
// 'assert', 'profile', 'profileEnd', 'count', 'timeEnd'.
Type string
}
type PageOnHandler func(PageOnEvent) error
// Page stores Page/tab related context.
type Page struct {
BaseEventEmitter
Keyboard *Keyboard
Mouse *Mouse
Touchscreen *Touchscreen
ctx context.Context
// what it really needs is an executor with
// SessionID and TargetID
session session
browserCtx *BrowserContext
targetID target.ID
opener *Page
frameManager *FrameManager
timeoutSettings *TimeoutSettings
jsEnabled bool
// protects from race between:
// - Browser.initEvents.onDetachedFromTarget->Page.didClose
// - FrameSession.initEvents.onFrameDetached->FrameManager.frameDetached.removeFramesRecursively->Page.IsClosed
closedMu sync.RWMutex
closed bool
// TODO: setter change these fields (mutex?)
emulatedSize *EmulatedSize
mediaType MediaType
colorScheme ColorScheme
reducedMotion ReducedMotion
extraHTTPHeaders map[string]string
backgroundPage bool
eventCh chan Event
eventHandlers map[PageOnEventName][]PageOnHandler
eventHandlersMu sync.RWMutex
mainFrameSession *FrameSession
frameSessions map[cdp.FrameID]*FrameSession
frameSessionsMu sync.RWMutex
workers map[target.SessionID]*Worker
routes []any // TODO: Implement
vu k6modules.VU
logger *log.Logger
}
// NewPage creates a new browser page context.
func NewPage(
ctx context.Context,
s session,
bctx *BrowserContext,
tid target.ID,
opener *Page,
bp bool,
logger *log.Logger,
) (*Page, error) {
p := Page{
BaseEventEmitter: NewBaseEventEmitter(ctx),
ctx: ctx,
session: s,
browserCtx: bctx,
targetID: tid,
opener: opener,
backgroundPage: bp,
mediaType: MediaTypeScreen,
colorScheme: bctx.opts.ColorScheme,
reducedMotion: bctx.opts.ReducedMotion,
extraHTTPHeaders: bctx.opts.ExtraHTTPHeaders,
timeoutSettings: NewTimeoutSettings(bctx.timeoutSettings),
Keyboard: NewKeyboard(ctx, s),
jsEnabled: true,
eventCh: make(chan Event),
eventHandlers: make(map[PageOnEventName][]PageOnHandler),
frameSessions: make(map[cdp.FrameID]*FrameSession),
workers: make(map[target.SessionID]*Worker),
vu: k6ext.GetVU(ctx),
logger: logger,
}
p.logger.Debugf("Page:NewPage", "sid:%v tid:%v backgroundPage:%t",
p.sessionID(), tid, bp)
// We need to init viewport and screen size before initializing the main frame session,
// as that's where the emulation is activated.
if !bctx.opts.Viewport.IsEmpty() {
p.emulatedSize = NewEmulatedSize(bctx.opts.Viewport, bctx.opts.Screen)
}
var err error
p.frameManager = NewFrameManager(ctx, s, &p, p.timeoutSettings, p.logger)
p.mainFrameSession, err = NewFrameSession(ctx, s, &p, nil, tid, p.logger, true)
if err != nil {
p.logger.Debugf("Page:NewPage:NewFrameSession:return", "sid:%v tid:%v err:%v",
p.sessionID(), tid, err)
return nil, err
}
p.frameSessionsMu.Lock()
p.frameSessions[cdp.FrameID(tid)] = p.mainFrameSession
p.frameSessionsMu.Unlock()
p.Mouse = NewMouse(ctx, s, p.frameManager.MainFrame(), bctx.timeoutSettings, p.Keyboard)
p.Touchscreen = NewTouchscreen(ctx, s, p.Keyboard)
p.initEvents()
action := target.SetAutoAttach(true, true).WithFlatten(true)
if err := action.Do(cdp.WithExecutor(p.ctx, p.session)); err != nil {
return nil, fmt.Errorf("internal error while auto attaching to browser pages: %w", err)
}
add := runtime.AddBinding(webVitalBinding)
if err := add.Do(cdp.WithExecutor(p.ctx, p.session)); err != nil {
return nil, fmt.Errorf("internal error while adding binding to page: %w", err)
}
if err := bctx.applyAllInitScripts(&p); err != nil {
return nil, fmt.Errorf("internal error while applying init scripts to page: %w", err)
}
return &p, nil
}
func (p *Page) initEvents() {
p.logger.Debugf("Page:initEvents",
"sid:%v tid:%v", p.session.ID(), p.targetID)
events := []string{
cdproto.EventRuntimeConsoleAPICalled,
}
p.session.on(p.ctx, events, p.eventCh)
go func() {
p.logger.Debugf("Page:initEvents:go",
"sid:%v tid:%v", p.session.ID(), p.targetID)
defer func() {
p.logger.Debugf("Page:initEvents:go:return",
"sid:%v tid:%v", p.session.ID(), p.targetID)
}()
for {
select {
case <-p.session.Done():
p.logger.Debugf("Page:initEvents:go:session.done",
"sid:%v tid:%v", p.session.ID(), p.targetID)
return
case <-p.ctx.Done():
p.logger.Debugf("Page:initEvents:go:ctx.Done",
"sid:%v tid:%v", p.session.ID(), p.targetID)
return
case event := <-p.eventCh:
if ev, ok := event.data.(*cdpruntime.EventConsoleAPICalled); ok {
p.onConsoleAPICalled(ev)
}
}
}
}()
}
// hasPageOnHandler returns true if there is a handler registered
// for the given page on event.
func hasPageOnHandler(p *Page, event PageOnEventName) bool {
p.eventHandlersMu.RLock()
defer p.eventHandlersMu.RUnlock()
_, ok := p.eventHandlers[event]
return ok
}
// MetricEvent is the type that is exported to JS. It is currently only used to
// match on the urlTag and return a name when a match is found.
type MetricEvent struct {
// The URL value from the metric's url tag. It will be used to match
// against the URL grouping regexs.
url string
// The method of the request made to the URL.
method string
// When a match is found this userProvidedURLTagName field should be updated.
userProvidedURLTagName string
// When a match is found this is set to true.
isUserURLTagNameExist bool
}
// TagMatches contains the name tag and matches used to match against existing
// metric tags that are about to be emitted.
type TagMatches struct {
// The name to send back to the caller of the handler.
TagName string `js:"name"`
// The patterns to match against.
Matches []Match `js:"matches"`
}
// Match contains the fields that will be used to match against metric tags
// that are about to be emitted.
type Match struct {
// This is a regex that will be compared against the existing url tag.
URLRegEx string `js:"url"`
// This is the request method to match on.
Method string `js:"method"`
}
// K6BrowserCheckRegEx is a function that will be used to check the URL tag
// against the user defined regexes in the Sobek runtime.
type K6BrowserCheckRegEx func(pattern, url string) (bool, error)
// Tag will find the first match given the URLTagPatterns and the URL from
// the metric tag and update the name field.
func (e *MetricEvent) Tag(matchesRegex K6BrowserCheckRegEx, matches TagMatches) error {
name := strings.TrimSpace(matches.TagName)
if name == "" {
return fmt.Errorf("name %q is invalid", matches.TagName)
}
for _, m := range matches.Matches {
// Validate the request method type if it has been assigned in a Match.
method := strings.TrimSpace(m.Method)
if method != "" {
method = strings.ToUpper(method)
switch method {
case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch,
http.MethodHead, http.MethodOptions, http.MethodConnect, http.MethodTrace:
default:
return fmt.Errorf("method %q is invalid", m.Method)
}
if method != e.method {
continue
}
}
// matchesRegex is a function that will perform the regex test in the Sobek
// runtime.
matched, err := matchesRegex(m.URLRegEx, e.url)
if err != nil {
return err
}
if matched {
e.isUserURLTagNameExist = true
e.userProvidedURLTagName = name
return nil
}
}
return nil
}
// urlTagName is used to match the given url with the matches defined by the
// user. Currently matches only contains url. When a match is found a user
// defined name, which is to be used in the urls place in the url metric tag,
// is returned.
//
// The check is done by calling the handlers that were registered with
// `page.on('metric')`. The user will need to use `Tag` to supply the
// url regexes and the matching is done from within there. If a match is found,
// the supplied name is returned back upstream to the caller of urlTagName.
func (p *Page) urlTagName(url string, method string) (string, bool) {
if !hasPageOnHandler(p, EventPageMetricCalled) {
return "", false
}
var newTagName string
var urlMatched bool
em := &MetricEvent{
url: url,
method: method,
}
p.eventHandlersMu.RLock()
defer p.eventHandlersMu.RUnlock()
for _, h := range p.eventHandlers[EventPageMetricCalled] {
err := func() error {
// Handlers can register other handlers, so we need to
// unlock the mutex before calling the next handler.
p.eventHandlersMu.RUnlock()
defer p.eventHandlersMu.RLock()
// Call and wait for the handler to complete.
return h(PageOnEvent{
Metric: em,
})
}()
if err != nil {
p.logger.Debugf("urlTagName", "handler returned an error: %v", err)
return "", false
}
}
// If a match was found then the name field in em will have been updated.
if em.isUserURLTagNameExist {
newTagName = em.userProvidedURLTagName
urlMatched = true
}
p.logger.Debugf("urlTagName", "name: %q nameChanged: %v", newTagName, urlMatched)
return newTagName, urlMatched
}
func (p *Page) onConsoleAPICalled(event *cdpruntime.EventConsoleAPICalled) {
if !hasPageOnHandler(p, EventPageConsoleAPICalled) {
return
}
m, err := p.consoleMsgFromConsoleEvent(event)
if err != nil {
p.logger.Errorf("Page:onConsoleAPICalled", "building console message: %v", err)
return
}
p.eventHandlersMu.RLock()
defer p.eventHandlersMu.RUnlock()
for _, h := range p.eventHandlers[EventPageConsoleAPICalled] {
err := h(PageOnEvent{
ConsoleMessage: m,
})
if err != nil {
p.logger.Debugf("onConsoleAPICalled", "handler returned an error: %v", err)
return
}
}
}
func (p *Page) consoleMsgFromConsoleEvent(e *cdpruntime.EventConsoleAPICalled) (*ConsoleMessage, error) {
execCtx, err := p.executionContextForID(e.ExecutionContextID)
if err != nil {
return nil, err
}
var (
objects = make([]string, 0, len(e.Args))
objectHandles = make([]JSHandleAPI, 0, len(e.Args))
)
for _, robj := range e.Args {
s, err := parseConsoleRemoteObject(p.logger, robj)
if err != nil {
p.logger.Errorf("consoleMsgFromConsoleEvent", "failed to parse console message %v", err)
}
objects = append(objects, s)
objectHandles = append(objectHandles, NewJSHandle(
p.ctx, p.session, execCtx, execCtx.Frame(), robj, p.logger,
))
}
return &ConsoleMessage{
Args: objectHandles,
Page: p,
Text: textForConsoleEvent(e, objects),
Type: e.Type.String(),
}, nil
}
func (p *Page) closeWorker(sessionID target.SessionID) {
p.logger.Debugf("Page:closeWorker", "sid:%v", sessionID)
if worker, ok := p.workers[sessionID]; ok {
worker.didClose()
delete(p.workers, sessionID)
}
}
func (p *Page) defaultTimeout() time.Duration {
return p.timeoutSettings.timeout()
}
func (p *Page) didClose() {
p.logger.Debugf("Page:didClose", "sid:%v", p.sessionID())
p.closedMu.Lock()
{
p.closed = true
}
p.closedMu.Unlock()
p.emit(EventPageClose, p)
}
func (p *Page) didCrash() {
p.logger.Debugf("Page:didCrash", "sid:%v", p.sessionID())
p.emit(EventPageCrash, p)
}
func (p *Page) evaluateOnNewDocument(source string) error {
p.logger.Debugf("Page:evaluateOnNewDocument", "sid:%v", p.sessionID())
action := page.AddScriptToEvaluateOnNewDocument(source)
_, err := action.Do(cdp.WithExecutor(p.ctx, p.session))
if err != nil {
return fmt.Errorf("evaluating script on document: %w", err)
}
return nil
}
func (p *Page) getFrameElement(f *Frame) (handle *ElementHandle, _ error) {
if f == nil {
p.logger.Debugf("Page:getFrameElement", "sid:%v frame:nil", p.sessionID())
} else {
p.logger.Debugf("Page:getFrameElement", "sid:%v fid:%s furl:%s",
p.sessionID(), f.ID(), f.URL())
}
parent := f.parentFrame
if parent == nil {
return nil, errors.New("frame has been detached 1")
}
rootFrame := f
for ; rootFrame.parentFrame != nil; rootFrame = rootFrame.parentFrame {
}
parentSession := p.getFrameSession(cdp.FrameID(rootFrame.ID()))
action := dom.GetFrameOwner(cdp.FrameID(f.ID()))
backendNodeId, _, err := action.Do(cdp.WithExecutor(p.ctx, parentSession.session))
if err != nil {
if strings.Contains(err.Error(), "frame with the given id was not found") {
return nil, errors.New("frame has been detached")
}
return nil, fmt.Errorf("getting frame owner: %w", err)
}
parent = f.parentFrame
if parent == nil {
return nil, errors.New("frame has been detached 2")
}
return parent.adoptBackendNodeID(mainWorld, backendNodeId)
}
func (p *Page) getOwnerFrame(apiCtx context.Context, h *ElementHandle) (cdp.FrameID, error) {
p.logger.Debugf("Page:getOwnerFrame", "sid:%v", p.sessionID())
// document.documentElement has frameId of the owner frame
pageFn := `
node => {
const doc = node;
if (doc.documentElement && doc.documentElement.ownerDocument === doc)
return doc.documentElement;
return node.ownerDocument ? node.ownerDocument.documentElement : null;
}
`
opts := evalOptions{
forceCallable: true,
returnByValue: false,
}
result, err := h.execCtx.eval(apiCtx, opts, pageFn, h)
if err != nil {
p.logger.Debugf("Page:getOwnerFrame:return", "sid:%v err:%v", p.sessionID(), err)
return "", nil
}
switch result.(type) {
case nil:
p.logger.Debugf("Page:getOwnerFrame:return", "sid:%v result:nil", p.sessionID())
return "", nil
}
documentElement := result.(*ElementHandle)
if documentElement == nil {
p.logger.Debugf("Page:getOwnerFrame:return", "sid:%v docel:nil", p.sessionID())
return "", nil
}
if documentElement.remoteObject.ObjectID == "" {
p.logger.Debugf("Page:getOwnerFrame:return", "sid:%v robjid:%q", p.sessionID(), "")
return "", nil
}
action := dom.DescribeNode().WithObjectID(documentElement.remoteObject.ObjectID)
node, err := action.Do(cdp.WithExecutor(p.ctx, p.session))
if err != nil {
p.logger.Debugf("Page:getOwnerFrame:DescribeNode:return", "sid:%v err:%v", p.sessionID(), err)
return "", nil
}
if node == nil {
p.logger.Debugf("Page:getOwnerFrame:node:nil:return", "sid:%v err:%v", p.sessionID(), err)
return "", nil
}
frameID := node.FrameID
if err := documentElement.Dispose(); err != nil {
return "", fmt.Errorf("disposing document element while getting owner frame: %w", err)
}
return frameID, nil
}
func (p *Page) attachFrameSession(fid cdp.FrameID, fs *FrameSession) {
p.logger.Debugf("Page:attachFrameSession", "sid:%v fid=%v", p.session.ID(), fid)
p.frameSessionsMu.Lock()
defer p.frameSessionsMu.Unlock()
fs.page.frameSessions[fid] = fs
}
func (p *Page) getFrameSession(frameID cdp.FrameID) *FrameSession {
p.logger.Debugf("Page:getFrameSession", "sid:%v fid:%v", p.sessionID(), frameID)
p.frameSessionsMu.RLock()
defer p.frameSessionsMu.RUnlock()
return p.frameSessions[frameID]
}
func (p *Page) hasRoutes() bool {
return len(p.routes) > 0
}
func (p *Page) resetViewport() error {
p.logger.Debugf("Page:resetViewport", "sid:%v", p.sessionID())
action := emulation.SetDeviceMetricsOverride(0, 0, 0, false)
return action.Do(cdp.WithExecutor(p.ctx, p.session))
}
func (p *Page) setEmulatedSize(emulatedSize *EmulatedSize) error {
p.logger.Debugf("Page:setEmulatedSize", "sid:%v", p.sessionID())
p.emulatedSize = emulatedSize
return p.mainFrameSession.updateViewport()
}
func (p *Page) setViewportSize(viewportSize *Size) error {
p.logger.Debugf("Page:setViewportSize", "sid:%v vps:%v",
p.sessionID(), viewportSize)
viewport := Viewport{
Width: int64(viewportSize.Width),
Height: int64(viewportSize.Height),
}
screen := Screen{
Width: int64(viewportSize.Width),
Height: int64(viewportSize.Height),
}
return p.setEmulatedSize(NewEmulatedSize(viewport, screen))
}
func (p *Page) updateExtraHTTPHeaders() error {
p.logger.Debugf("Page:updateExtraHTTPHeaders", "sid:%v", p.sessionID())
p.frameSessionsMu.RLock()
defer p.frameSessionsMu.RUnlock()
for _, fs := range p.frameSessions {
if err := fs.updateExtraHTTPHeaders(false); err != nil {
return fmt.Errorf("updating extra HTTP headers: %w", err)
}
}
return nil
}
func (p *Page) updateGeolocation() error {
p.logger.Debugf("Page:updateGeolocation", "sid:%v", p.sessionID())
p.frameSessionsMu.RLock()
defer p.frameSessionsMu.RUnlock()
for _, fs := range p.frameSessions {
p.logger.Debugf("Page:updateGeolocation:frameSession",
"sid:%v tid:%v wid:%v",
p.sessionID(), fs.targetID, fs.windowID)
if err := fs.updateGeolocation(false); err != nil {
p.logger.Debugf("Page:updateGeolocation:frameSession:return",
"sid:%v tid:%v wid:%v err:%v",
p.sessionID(), fs.targetID, fs.windowID, err)
return err
}
}
return nil
}
func (p *Page) updateOffline() error {
p.logger.Debugf("Page:updateOffline", "sid:%v", p.sessionID())
p.frameSessionsMu.RLock()
defer p.frameSessionsMu.RUnlock()
for _, fs := range p.frameSessions {
if err := fs.updateOffline(false); err != nil {
return fmt.Errorf("updating page frame sessions to offline: %w", err)
}
}
return nil
}
func (p *Page) updateHTTPCredentials() error {
p.logger.Debugf("Page:updateHttpCredentials", "sid:%v", p.sessionID())
p.frameSessionsMu.RLock()
defer p.frameSessionsMu.RUnlock()
for _, fs := range p.frameSessions {
if err := fs.updateHTTPCredentials(false); err != nil {
return err
}
}
return nil
}
func (p *Page) viewportSize() Size {
return Size{
Width: float64(p.emulatedSize.Viewport.Width),
Height: float64(p.emulatedSize.Viewport.Height),
}
}
// BringToFront activates the browser tab for this page.
func (p *Page) BringToFront() error {
p.logger.Debugf("Page:BringToFront", "sid:%v", p.sessionID())
action := cdppage.BringToFront()
if err := action.Do(cdp.WithExecutor(p.ctx, p.session)); err != nil {
return fmt.Errorf("bringing page to front: %w", err)
}
return nil
}
// SetChecked sets the checked state of the element matching the provided selector.
func (p *Page) SetChecked(selector string, checked bool, opts sobek.Value) error {
p.logger.Debugf("Page:SetChecked", "sid:%v selector:%s checked:%t", p.sessionID(), selector, checked)
return p.MainFrame().SetChecked(selector, checked, opts)
}
// Check checks an element matching the provided selector.
func (p *Page) Check(selector string, opts sobek.Value) error {
p.logger.Debugf("Page:Check", "sid:%v selector:%s", p.sessionID(), selector)
return p.MainFrame().Check(selector, opts)
}
// Uncheck unchecks an element matching the provided selector.
func (p *Page) Uncheck(selector string, opts sobek.Value) error {
p.logger.Debugf("Page:Uncheck", "sid:%v selector:%s", p.sessionID(), selector)
return p.MainFrame().Uncheck(selector, opts)
}
// IsChecked returns true if the first element that matches the selector
// is checked. Otherwise, returns false.
func (p *Page) IsChecked(selector string, opts sobek.Value) (bool, error) {
p.logger.Debugf("Page:IsChecked", "sid:%v selector:%s", p.sessionID(), selector)
return p.MainFrame().IsChecked(selector, opts)
}
// Click clicks an element matching provided selector.
func (p *Page) Click(selector string, opts *FrameClickOptions) error {
p.logger.Debugf("Page:Click", "sid:%v selector:%s", p.sessionID(), selector)
return p.MainFrame().Click(selector, opts)
}
// Close closes the page.
func (p *Page) Close(_ sobek.Value) error {
p.logger.Debugf("Page:Close", "sid:%v", p.sessionID())
_, span := TraceAPICall(p.ctx, p.targetID.String(), "page.close")
defer span.End()
// forcing the pagehide event to trigger web vitals metrics.
v := `() => window.dispatchEvent(new Event('pagehide'))`
ctx, cancel := context.WithTimeout(p.ctx, p.defaultTimeout())
defer cancel()
_, err := p.MainFrame().EvaluateWithContext(ctx, v)
if err != nil {
p.logger.Warnf("Page:Close", "failed to hide page: %v", err)
}
add := runtime.RemoveBinding(webVitalBinding)
if err := add.Do(cdp.WithExecutor(p.ctx, p.session)); err != nil {
err := fmt.Errorf("internal error while removing binding from page: %w", err)
spanRecordError(span, err)
return err
}
action := target.CloseTarget(p.targetID)
err = action.Do(cdp.WithExecutor(p.ctx, p.session))
if err != nil {
// When a close target command is sent to the browser via CDP,
// the browser will start to cleanup and the first thing it
// will do is return a target.EventDetachedFromTarget, which in
// our implementation will close the session connection (this
// does not close the CDP websocket, just removes the session
// so no other CDP calls can be made with the session ID).
// This can result in the session's context being closed while
// we're waiting for the response to come back from the browser
// for this current command (it's racey).
if errors.Is(err, context.Canceled) {
return nil
}
err := fmt.Errorf("closing a page: %w", err)
spanRecordError(span, err)
return err
}
return nil
}
// Content returns the HTML content of the page.
func (p *Page) Content() (string, error) {
p.logger.Debugf("Page:Content", "sid:%v", p.sessionID())
return p.MainFrame().Content()
}
// Context closes the page.
func (p *Page) Context() *BrowserContext {
return p.browserCtx
}
// Dblclick double clicks an element matching provided selector.
func (p *Page) Dblclick(selector string, opts sobek.Value) error {
p.logger.Debugf("Page:Dblclick", "sid:%v selector:%s", p.sessionID(), selector)
return p.MainFrame().Dblclick(selector, opts)
}
// DispatchEvent dispatches an event on the page to the element that matches the provided selector.
func (p *Page) DispatchEvent(selector string, typ string, eventInit any, opts *FrameDispatchEventOptions) error {
p.logger.Debugf("Page:DispatchEvent", "sid:%v selector:%s", p.sessionID(), selector)
return p.MainFrame().DispatchEvent(selector, typ, eventInit, opts)
}
// EmulateMedia emulates the given media type.
func (p *Page) EmulateMedia(opts sobek.Value) error {
p.logger.Debugf("Page:EmulateMedia", "sid:%v", p.sessionID())
parsedOpts := NewPageEmulateMediaOptions(p.mediaType, p.colorScheme, p.reducedMotion)
if err := parsedOpts.Parse(p.ctx, opts); err != nil {
return fmt.Errorf("parsing emulateMedia options: %w", err)
}
p.mediaType = parsedOpts.Media
p.colorScheme = parsedOpts.ColorScheme
p.reducedMotion = parsedOpts.ReducedMotion
p.frameSessionsMu.RLock()
for _, fs := range p.frameSessions {
if err := fs.updateEmulateMedia(false); err != nil {
p.frameSessionsMu.RUnlock()
return fmt.Errorf("emulating media: %w", err)
}
}
p.frameSessionsMu.RUnlock()
applySlowMo(p.ctx)
return nil
}
// EmulateVisionDeficiency activates/deactivates emulation of a vision deficiency.
func (p *Page) EmulateVisionDeficiency(typ string) error {
p.logger.Debugf("Page:EmulateVisionDeficiency", "sid:%v typ:%s", p.sessionID(), typ)
validTypes := map[string]emulation.SetEmulatedVisionDeficiencyType{
"achromatopsia": emulation.SetEmulatedVisionDeficiencyTypeAchromatopsia,
"blurredVision": emulation.SetEmulatedVisionDeficiencyTypeBlurredVision,
"deuteranopia": emulation.SetEmulatedVisionDeficiencyTypeDeuteranopia,
"none": emulation.SetEmulatedVisionDeficiencyTypeNone,
"protanopia": emulation.SetEmulatedVisionDeficiencyTypeProtanopia,
"tritanopia": emulation.SetEmulatedVisionDeficiencyTypeTritanopia,
}
t, ok := validTypes[typ]
if !ok {
return fmt.Errorf("unsupported vision deficiency: %s", typ)
}
action := emulation.SetEmulatedVisionDeficiency(t)
if err := action.Do(cdp.WithExecutor(p.ctx, p.session)); err != nil {
return fmt.Errorf("setting emulated vision deficiency %q: %w", typ, err)
}
applySlowMo(p.ctx)
return nil
}
// Evaluate runs JS code within the execution context of the main frame of the page.
func (p *Page) Evaluate(pageFunc string, args ...any) (any, error) {
p.logger.Debugf("Page:Evaluate", "sid:%v", p.sessionID())
return p.MainFrame().Evaluate(pageFunc, args...)
}
// EvaluateHandle runs JS code within the execution context of the main frame of the page.
func (p *Page) EvaluateHandle(pageFunc string, args ...any) (JSHandleAPI, error) {
p.logger.Debugf("Page:EvaluateHandle", "sid:%v", p.sessionID())
h, err := p.MainFrame().EvaluateHandle(pageFunc, args...)
if err != nil {
return nil, fmt.Errorf("evaluating handle for page: %w", err)
}
return h, nil
}
// Fill fills an input element with the provided value.
func (p *Page) Fill(selector string, value string, opts sobek.Value) error {
p.logger.Debugf("Page:Fill", "sid:%v selector:%s", p.sessionID(), selector)