Repository navigation
Expand file tree
/
Copy pathbrowser.go
More file actions
863 lines (759 loc) · 23.4 KB
/
Copy pathbrowser.go
File metadata and controls
863 lines (759 loc) · 23.4 KB
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
//go:generate go run ./lib/utils/setup
//go:generate go run ./lib/proto/generate
//go:generate go run ./lib/js/generate
//go:generate go run ./lib/assets/generate
//go:generate go run ./lib/utils/lint
// Package rod is a high-level driver directly based on DevTools Protocol.
package rod
import (
"context"
"errors"
"io"
"reflect"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/projectdiscovery/rod/lib/cdp"
"github.com/projectdiscovery/rod/lib/defaults"
"github.com/projectdiscovery/rod/lib/devices"
"github.com/projectdiscovery/rod/lib/launcher"
"github.com/projectdiscovery/rod/lib/proto"
"github.com/projectdiscovery/rod/lib/utils"
)
// aboutBlank is the URL of an empty tab.
const aboutBlank = "about:blank"
// Browser implements these interfaces.
var (
_ proto.Client = &Browser{}
_ proto.Contextable = &Browser{}
)
// Browser represents the browser.
// It doesn't depends on file system, it should work with remote browser seamlessly.
// To check the env var you can use to quickly enable options from CLI, check here:
// https://pkg.go.dev/github.com/projectdiscovery/rod/lib/defaults
type Browser struct {
// BrowserContextID is the id for incognito window
BrowserContextID proto.BrowserBrowserContextID
e eFunc
ctx context.Context
sleeper func() utils.Sleeper
logger utils.Logger
slowMotion time.Duration // see defaults.slow
trace bool // see defaults.Trace
monitor string
defaultDevice devices.Device
// compliant skips the default device and aligns the user agent with the
// browser. The launcher must also be started with [launcher.Launcher.Compliant].
compliant bool
profile *compliantProfile
controlURL string
client CDPClient
launcher *launcher.Launcher // set when Connect started the browser itself
router *router // all the browser events from cdp client
eventQueue int
targetsLock *sync.Mutex
domainMu *sync.Mutex
domains map[stateKey]int
autoAttach *atomic.Bool
// opening joins concurrent PageFromTarget calls for one target so the
// attach and emulation run once, and never while targetsLock is held.
opening map[proto.TargetTargetID]*pageOpen
// stores all the previous cdp call of same type. Browser doesn't have enough API
// for us to retrieve all its internal states. This is an workaround to map them to local.
// For example you can't use cdp API to get the current position of mouse.
states *sync.Map
}
// New creates a controller.
// Compliant is on by default: pages report the browser's own user agent and
// client hints, and the default device is not applied, so no stale Chrome
// version is reported. Use [Browser.Compliant](false) to opt out, which
// brings back [devices.LaptopWithMDPIScreen] as the default device.
func New() *Browser {
return (&Browser{
ctx: context.Background(),
sleeper: DefaultSleeper,
controlURL: defaults.URL,
slowMotion: defaults.Slow,
trace: defaults.Trace,
monitor: defaults.Monitor,
logger: DefaultLogger,
defaultDevice: devices.LaptopWithMDPIScreen.Landscape(),
targetsLock: &sync.Mutex{},
domainMu: &sync.Mutex{},
domains: map[stateKey]int{},
autoAttach: &atomic.Bool{},
states: &sync.Map{},
opening: map[proto.TargetTargetID]*pageOpen{},
profile: newCompliantProfile(),
compliant: true,
}).WithPanic(utils.Panic)
}
// Incognito creates a new incognito browser.
func (b *Browser) Incognito() (*Browser, error) {
return b.IncognitoContext(b.ctx, BrowserContextOptions{})
}
// BrowserContextOptions configures an incognito browser context.
type BrowserContextOptions struct {
ProxyServer string
ProxyBypassList string
DisposeOnDetach bool
}
// IncognitoContext creates an incognito browser context. The call honours ctx.
func (b *Browser) IncognitoContext(ctx context.Context, opts BrowserContextOptions) (*Browser, error) {
res, err := proto.TargetCreateBrowserContext{
ProxyServer: opts.ProxyServer,
ProxyBypassList: opts.ProxyBypassList,
DisposeOnDetach: opts.DisposeOnDetach,
}.Call(b.Context(ctx))
if err != nil {
return nil, err
}
incognito := *b
incognito.BrowserContextID = res.BrowserContextID
return &incognito, nil
}
// Alive reports whether the browser still answers CDP.
func (b *Browser) Alive() error {
_, err := proto.BrowserGetVersion{}.Call(b)
return err
}
// AutoAttach turns on flattened auto-attach so cross-origin iframes and
// workers get their own sessions. New targets are paused until
// Runtime.runIfWaitingForDebugger, which initEvents sends for attached targets
// when this was enabled.
func (b *Browser) AutoAttach() error {
b.autoAttach.Store(true)
return proto.TargetSetAutoAttach{
AutoAttach: true,
WaitForDebuggerOnStart: true,
Flatten: true,
}.Call(b)
}
// ControlURL set the url to remote control browser.
func (b *Browser) ControlURL(url string) *Browser {
b.controlURL = url
return b
}
// SlowMotion set the delay for each control action, such as the simulation of the human inputs.
func (b *Browser) SlowMotion(delay time.Duration) *Browser {
b.slowMotion = delay
return b
}
// Trace enables/disables the visual tracing of the input actions on the page.
func (b *Browser) Trace(enable bool) *Browser {
b.trace = enable
return b
}
// Monitor address to listen if not empty. Shortcut for [Browser.ServeMonitor].
func (b *Browser) Monitor(url string) *Browser {
b.monitor = url
return b
}
// Logger overrides the default log functions for tracing.
func (b *Browser) Logger(l utils.Logger) *Browser {
b.logger = l
return b
}
// Client set the cdp client.
func (b *Browser) Client(c CDPClient) *Browser {
b.client = c
return b
}
// DefaultDevice sets the default device for new page to emulate in the future.
// Default is [devices.LaptopWithMDPIScreen].
// Set it to [devices.Clear] to disable it.
func (b *Browser) DefaultDevice(d devices.Device) *Browser {
b.defaultDevice = d
return b
}
// NoDefaultDevice is the same as [Browser.DefaultDevice](devices.Clear).
func (b *Browser) NoDefaultDevice() *Browser {
return b.DefaultDevice(devices.Clear)
}
// Compliant makes pages report this browser's own user agent and client hints,
// with the HeadlessChrome token removed. It also skips the default device,
// which would force a Chrome 114 user agent. The browser has to be launched
// with [launcher.Launcher.Compliant], which turns navigator.webdriver off.
// Without that launch, the user agent is aligned and webdriver stays true.
func (b *Browser) Compliant(enable bool) *Browser {
b.compliant = enable
return b
}
// Connect to the browser and start to control it.
// If fails to connect, try to launch a local browser, if local browser not found try to download one.
//
// A local launch talks CDP over --remote-debugging-pipe, so no debugging port
// is opened and other local processes cannot reach the browser. Where pipes
// are not available (Windows), the browser is launched on a port instead.
func (b *Browser) Connect() error {
err := b.startClient()
if err != nil {
return err
}
b.initEvents()
if b.monitor != "" {
launcher.Open(b.ServeMonitor(b.monitor))
}
err = (proto.TargetSetDiscoverTargets{Discover: true}).Call(b)
if err != nil {
if b.launcher != nil {
b.abandonLaunch()
}
return err
}
return nil
}
// Close the browser and, when this instance owns the connection, the CDP transport.
// A browser that Connect launched itself is also waited for and its profile
// directory removed.
func (b *Browser) Close() error {
var err error
if b.BrowserContextID == "" {
err = proto.BrowserClose{}.Call(b)
if c, ok := b.client.(io.Closer); ok && c != nil {
_ = c.Close()
}
if b.launcher != nil {
reapBrowser(b.launcher, BrowserExitTimeout)
}
return err
}
return proto.TargetDisposeBrowserContext{BrowserContextID: b.BrowserContextID}.Call(b)
}
// BrowserExitTimeout is how long Close waits for a browser that Connect
// launched to exit on its own before killing it.
var BrowserExitTimeout = 10 * time.Second
func reapBrowser(l *launcher.Launcher, timeout time.Duration) {
done := make(chan struct{})
go func() {
l.Cleanup()
close(done)
}()
t := time.NewTimer(timeout)
defer t.Stop()
select {
case <-done:
case <-t.C:
l.Kill()
<-done
}
}
// Page creates a new browser tab. If opts.URL is empty, the default target will be "about:blank".
//
//nolint:gocognit // the close loop retries half-open targets until the timeout
func (b *Browser) Page(opts proto.TargetCreateTarget) (p *Page, err error) {
req := opts
req.BrowserContextID = b.BrowserContextID
req.URL = aboutBlank
target, err := req.Call(b)
if err != nil {
return nil, err
}
defer func() {
// If Navigate or PageFromTarget fails we should close the target to prevent leak.
// Use a fresh timeout so a cancelled caller context still closes the target.
if err != nil {
closeCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
closer := b.Context(closeCtx)
// A target stuck in navigation can ignore the first close, and
// Chrome may have opened a child of that target. A failed
// GetTargets is not proof the target is gone.
for closeCtx.Err() == nil {
_, _ = proto.TargetCloseTarget{TargetID: target.TargetID}.Call(closer)
list, listErr := proto.TargetGetTargets{}.Call(closer)
if listErr != nil {
time.Sleep(50 * time.Millisecond)
continue
}
left := false
for _, info := range list.TargetInfos {
owned := info.TargetID == target.TargetID ||
info.OpenerID == target.TargetID ||
info.ParentID == target.TargetID
if !owned {
continue
}
left = true
if info.TargetID != target.TargetID {
_, _ = proto.TargetCloseTarget{TargetID: info.TargetID}.Call(closer)
}
}
if !left {
return
}
time.Sleep(50 * time.Millisecond)
}
}
}()
p, err = b.PageFromTarget(target.TargetID)
if err != nil {
return
}
if opts.URL == "" {
return
}
err = p.Navigate(opts.URL)
return
}
// Pages retrieves all visible pages.
func (b *Browser) Pages() (Pages, error) {
list, err := proto.TargetGetTargets{}.Call(b)
if err != nil {
return nil, err
}
pageList := Pages{}
for _, target := range list.TargetInfos {
if target.Type != proto.TargetTargetInfoTypePage {
continue
}
page, err := b.PageFromTarget(target.TargetID)
if err != nil {
return nil, err
}
pageList = append(pageList, page)
}
return pageList, nil
}
// Call implements the [proto.Client] to call raw cdp interface directly.
func (b *Browser) Call(ctx context.Context, sessionID, methodName string, params any) (res []byte, err error) {
res, err = b.client.Call(ctx, sessionID, methodName, params)
if err != nil {
return nil, err
}
b.set(proto.TargetSessionID(sessionID), methodName, params)
return
}
// PageFromSession is used for low-level debugging.
func (b *Browser) PageFromSession(sessionID proto.TargetSessionID) *Page {
sessionCtx, cancel, cancelCause := b.sessionContext()
page := &Page{
e: b.e,
ctx: sessionCtx,
session: sessionCtx,
sessionCancel: cancel,
cancelCause: cancelCause,
sleeper: b.sleeper,
browser: b,
SessionID: sessionID,
jsCtxLock: &sync.Mutex{},
jsCtxID: new(proto.RuntimeRemoteObjectID),
helpersLock: &sync.Mutex{},
}
page.root = page
page.newKeyboard().newMouse().newTouch()
return page
}
// PageSetupTimeout bounds attach and the first emulation when the caller set
// no deadline. A Chrome command that never returns must not pin the browser:
// every later page used to wait behind that one.
var PageSetupTimeout = 30 * time.Second
// pageOpen is one in-flight attach of a target.
type pageOpen struct {
done chan struct{}
page *Page
err error
}
// PageFromTarget gets or creates a Page instance.
func (b *Browser) PageFromTarget(targetID proto.TargetTargetID) (*Page, error) {
if b.compliant {
err := b.ensureCompliant()
if err != nil {
return nil, err
}
}
return b.pageFromTarget(targetID, true)
}
// EachEvent is similar to [Page.EachEvent], but catches events of the entire browser.
func (b *Browser) EachEvent(callbacks ...any) (wait func()) {
return b.eachEvent("", callbacks...)
}
// WaitEvent waits for the next event for one time. It will also load the data into the event object.
func (b *Browser) WaitEvent(e proto.Event) (wait func()) {
return b.waitEvent("", e)
}
// Event of the browser.
func (b *Browser) Event() <-chan *Message {
return b.listen(b.ctx, "", nil)
}
// IgnoreCertErrors switch. If enabled, all certificate errors will be ignored.
func (b *Browser) IgnoreCertErrors(enable bool) error {
return proto.SecuritySetIgnoreCertificateErrors{Ignore: enable}.Call(b)
}
// GetCookies from the browser.
func (b *Browser) GetCookies() ([]*proto.NetworkCookie, error) {
res, err := proto.StorageGetCookies{BrowserContextID: b.BrowserContextID}.Call(b)
if err != nil {
return nil, err
}
return res.Cookies, nil
}
// SetCookies to the browser. If the cookies is nil it will clear all the cookies.
func (b *Browser) SetCookies(cookies []*proto.NetworkCookieParam) error {
if cookies == nil {
return proto.StorageClearCookies{BrowserContextID: b.BrowserContextID}.Call(b)
}
return proto.StorageSetCookies{
Cookies: cookies,
BrowserContextID: b.BrowserContextID,
}.Call(b)
}
// WaitDownload returns a helper to get the next download file.
// The file path will be:
//
// filepath.Join(dir, info.GUID)
func (b *Browser) WaitDownload(dir string) func() (info *proto.PageDownloadWillBegin) {
var oldDownloadBehavior proto.BrowserSetDownloadBehavior
has := b.LoadState("", &oldDownloadBehavior)
_ = proto.BrowserSetDownloadBehavior{
Behavior: proto.BrowserSetDownloadBehaviorBehaviorAllowAndName,
BrowserContextID: b.BrowserContextID,
DownloadPath: dir,
}.Call(b)
var start *proto.PageDownloadWillBegin
waitProgress := b.EachEvent(func(e *proto.PageDownloadWillBegin) {
start = e
}, func(e *proto.PageDownloadProgress) bool {
return start != nil && start.GUID == e.GUID && e.State == proto.PageDownloadProgressStateCompleted
})
return func() *proto.PageDownloadWillBegin {
defer func() {
if has {
_ = oldDownloadBehavior.Call(b)
} else {
_ = proto.BrowserSetDownloadBehavior{
Behavior: proto.BrowserSetDownloadBehaviorBehaviorDefault,
BrowserContextID: b.BrowserContextID,
}.Call(b)
}
}()
waitProgress()
return start
}
}
// Version info of the browser.
func (b *Browser) Version() (*proto.BrowserGetVersionResult, error) {
return proto.BrowserGetVersion{}.Call(b)
}
// attach connects over a pipe when the platform supports it and over a
// websocket otherwise. l is nil when the browser is remote and u is its URL.
func (b *Browser) attach(l *launcher.Launcher, u string) (CDPClient, error) {
if l != nil && launcher.PipeSupported() {
pc, err := l.LaunchPipe()
if err != nil {
return nil, err
}
return pc, nil
}
if l != nil {
var err error
u, err = l.Launch()
if err != nil {
return nil, err
}
}
cc, err := cdp.StartWithURL(b.ctx, u, nil)
if err != nil {
if l != nil {
l.Kill()
l.Cleanup()
}
return nil, err
}
return cc, nil
}
// startClient launches or attaches the CDP client unless one is already set.
func (b *Browser) startClient() error {
if b.client != nil {
if b.controlURL != "" {
return errors.New("Browser.Client and Browser.ControlURL can't be set at the same time")
}
return nil
}
// Pipe launches do not wait on the context, so check it here.
err := b.ctx.Err()
if err != nil {
return err
}
u := b.controlURL
var l *launcher.Launcher
if u == "" {
l = launcher.New().Context(b.ctx)
if b.compliant {
l.Compliant(true)
}
}
c, err := b.attach(l, u)
if err != nil {
return err
}
b.launcher = l
b.client = c
return nil
}
func (b *Browser) isHeadless() (enabled bool) {
res, err := proto.BrowserGetBrowserCommandLine{}.Call(b)
if err == nil {
for _, v := range res.Arguments {
if strings.Contains(v, "headless") {
return true
}
}
return false
}
// Chrome only reports its arguments when --enable-automation is set, and
// compliant mode removes it. SystemInfo still reports the full command line.
info, err := proto.SystemInfoGetInfo{}.Call(b)
if err != nil {
return false
}
for _, arg := range strings.Fields(info.CommandLine) {
if strings.HasPrefix(arg, "--") && strings.Contains(arg, "headless") {
return true
}
}
return false
}
func (b *Browser) pageInfo(id proto.TargetTargetID) (*proto.TargetTargetInfo, error) {
res, err := proto.TargetGetTargetInfo{TargetID: id}.Call(b)
if err != nil {
return nil, err
}
return res.TargetInfo, nil
}
func (b *Browser) initEvents() {
queue := b.eventQueue
if queue == 0 {
queue = DefaultEventQueue
}
b.router = newRouter(queue)
if b.domains == nil {
b.domains = map[stateKey]int{}
}
if b.domainMu == nil {
b.domainMu = &sync.Mutex{}
}
if b.autoAttach == nil {
b.autoAttach = &atomic.Bool{}
}
event := b.client.Event()
go func() {
for e := range event {
msg := &Message{
SessionID: proto.TargetSessionID(e.SessionID),
Method: e.Method,
lock: &sync.Mutex{},
data: e.Params,
}
switch e.Method {
case "Target.attachedToTarget":
if b.autoAttach.Load() {
go b.resumeAttached(e.Params)
}
case "Target.detachedFromTarget", "Target.targetDestroyed":
b.targetGone(e.Method, e.Params)
}
b.router.publish(msg)
}
cause := b.Err()
if cause == nil {
cause = cdp.ErrConnClosed
}
b.cancelPages(cause)
}()
}
// listen returns a channel of events. An empty sessionID means every session.
// When methods is non-nil only those methods are delivered. The channel is
// closed when ctx ends.
func (b *Browser) listen(
ctx context.Context, sessionID proto.TargetSessionID, methods map[string]struct{},
) <-chan *Message {
if b.router == nil {
ch := make(chan *Message)
close(ch)
return ch
}
return b.router.subscribe(ctx, sessionID, methods)
}
// eachEventStop is eachEvent whose wait reports whether a callback stopped it.
func (b *Browser) eachEventStop(sessionID proto.TargetSessionID, callbacks ...any) (wait func() bool) {
cbMap := map[string]reflect.Value{}
restores := []func(){}
for _, cb := range callbacks {
cbVal := reflect.ValueOf(cb)
eType := cbVal.Type().In(0)
name := reflect.New(eType.Elem()).Interface().(proto.Event).ProtoEvent() //nolint: forcetypeassert
cbMap[name] = cbVal
// Only enabled domains will emit events to cdp client.
// We enable the domains for the event types if it's not enabled.
// We restore the domains to their previous states after the wait ends.
domain, _ := proto.ParseMethodName(name)
if req := proto.GetType(domain + ".enable"); req != nil {
enable := reflect.New(req).Interface().(proto.Request) //nolint: forcetypeassert
restores = append(restores, b.EnableDomain(sessionID, enable))
}
}
methods := make(map[string]struct{}, len(cbMap))
for name := range cbMap {
methods[name] = struct{}{}
}
b, cancel := b.WithCancel()
messages := b.listen(b.ctx, sessionID, methods)
return func() bool {
if messages == nil {
return false
}
defer func() {
cancel()
messages = nil
for _, restore := range restores {
restore()
}
}()
for msg := range messages {
if cbVal, has := cbMap[msg.Method]; has {
e := reflect.New(proto.GetType(msg.Method))
msg.Load(e.Interface().(proto.Event)) //nolint: forcetypeassert
args := []reflect.Value{e}
if cbVal.Type().NumIn() == 2 {
args = append(args, reflect.ValueOf(msg.SessionID))
}
res := cbVal.Call(args)
if len(res) > 0 {
if res[0].Bool() {
return true
}
}
}
}
return false
}
}
// If the any callback returns true the event loop will stop.
// It will enable the related domains if not enabled, and restore them after wait ends.
func (b *Browser) eachEvent(sessionID proto.TargetSessionID, callbacks ...any) (wait func()) {
w := b.eachEventStop(sessionID, callbacks...)
return func() { w() }
}
// waits for the next event for one time. It will also load the data into the event object.
func (b *Browser) waitEvent(sessionID proto.TargetSessionID, e proto.Event) (wait func()) {
return b.eachEvent(sessionID, eventLoader(e))
}
func (b *Browser) openTarget(targetID proto.TargetTargetID, prepare bool) (page *Page, err error) {
ctx, cancel := b.pageSetupContext()
defer cancel()
caller := b.Context(ctx)
session, err := proto.TargetAttachToTarget{
TargetID: targetID,
Flatten: true, // if it's not set no response will return
}.Call(caller)
if err != nil {
return nil, err
}
sessionCtx, cancelSession, cancelCause := b.sessionContext()
page = &Page{
e: b.e,
ctx: sessionCtx,
session: sessionCtx,
sessionCancel: cancelSession,
cancelCause: cancelCause,
sleeper: b.sleeper,
browser: b,
TargetID: targetID,
SessionID: session.SessionID,
FrameID: proto.PageFrameID(targetID),
jsCtxLock: &sync.Mutex{},
jsCtxID: new(proto.RuntimeRemoteObjectID),
helpersLock: &sync.Mutex{},
}
page.root = page
page.newKeyboard().newMouse().newTouch()
// return nil, err clears the named page result before this runs.
opened := page
defer func() {
if err != nil && opened.sessionCancel != nil {
opened.sessionCancel()
}
}()
if prepare {
if b.compliant {
err = page.Context(ctx).applyCompliant()
} else if !b.defaultDevice.IsClear() {
err = page.Context(ctx).Emulate(b.defaultDevice)
}
if err != nil {
return nil, err
}
}
// If we don't enable it, it will cause a lot of unexpected browser behavior.
// Such as proto.PageAddScriptToEvaluateOnNewDocument won't work.
// A stuck Page.enable used to sit on the browser lock until the caller gave up.
restore := page.Context(ctx).EnableDomain(&proto.PageEnable{})
err = ctx.Err()
if err != nil {
restore()
return nil, err
}
return page, nil
}
func (b *Browser) pageSetupContext() (context.Context, context.CancelFunc) {
if _, ok := b.ctx.Deadline(); ok {
return b.ctx, func() {}
}
timeout := PageSetupTimeout
if timeout <= 0 {
timeout = 30 * time.Second
}
return context.WithTimeout(b.ctx, timeout)
}
// pageFromTarget attaches to targetID. When prepare is set, the default
// device or the compliant user agent is applied. The browser lock is not
// held across those calls.
func (b *Browser) pageFromTarget(targetID proto.TargetTargetID, prepare bool) (*Page, error) {
if page := b.loadCachedPage(targetID); page != nil {
return page, nil
}
b.targetsLock.Lock()
if page := b.loadCachedPage(targetID); page != nil {
b.targetsLock.Unlock()
return page, nil
}
if b.opening == nil {
b.opening = map[proto.TargetTargetID]*pageOpen{}
}
if op, ok := b.opening[targetID]; ok {
b.targetsLock.Unlock()
<-op.done
return op.page, op.err
}
op := &pageOpen{done: make(chan struct{})}
b.opening[targetID] = op
b.targetsLock.Unlock()
page, err := b.openTarget(targetID, prepare)
b.targetsLock.Lock()
if err == nil {
if existing := b.loadCachedPage(targetID); existing != nil {
page.sessionCancel()
page = existing
} else {
b.cachePage(page)
}
}
op.page, op.err = page, err
delete(b.opening, targetID)
close(op.done)
b.targetsLock.Unlock()
return page, err
}
// abandonLaunch tears down a browser that Connect started but could not
// finish connecting to. Closing the client also ends the event loop.
func (b *Browser) abandonLaunch() {
if c, ok := b.client.(io.Closer); ok && c != nil {
_ = c.Close()
}
b.launcher.Kill()
b.launcher.Cleanup()
b.client = nil
b.launcher = nil
}