forked from go-rod/rod
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpage.go
More file actions
648 lines (543 loc) · 15 KB
/
page.go
File metadata and controls
648 lines (543 loc) · 15 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
package rod
import (
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"net/http"
"strings"
"sync"
"time"
"github.com/ysmood/goob"
"github.com/ysmood/kit"
"github.com/ysmood/rod/lib/assets"
"github.com/ysmood/rod/lib/cdp"
"github.com/ysmood/rod/lib/proto"
)
// Page implements the proto.Caller interface
var _ proto.Caller = &Page{}
// Page represents the webpage
type Page struct {
// these are the handler for ctx
ctx context.Context
ctxCancel func()
timeoutCancel func()
browser *Browser
TargetID proto.TargetTargetID
SessionID proto.TargetSessionID
FrameID proto.PageFrameID
// devices
Mouse *Mouse
Keyboard *Keyboard
element *Element // iframe only
windowObjectID proto.RuntimeRemoteObjectID // used as the thisObject when eval js
getDownloadFileLock *sync.Mutex
viewport *proto.EmulationSetDeviceMetricsOverride
event *goob.Observable
}
// IsIframe tells if it's iframe
func (p *Page) IsIframe() bool {
return p.element != nil
}
// Event returns the observable for page events
func (p *Page) Event() *goob.Observable {
return p.event
}
// Root page of the iframe, if it's not a iframe returns itself
func (p *Page) Root() *Page {
f := p
for f.IsIframe() {
f = f.element.page
}
return f
}
// CookiesE returns the page cookies. By default it will return the cookies for current page.
// The urls is the list of URLs for which applicable cookies will be fetched.
func (p *Page) CookiesE(urls []string) ([]*proto.NetworkCookie, error) {
if len(urls) == 0 {
info, err := proto.TargetGetTargetInfo{TargetID: p.TargetID}.Call(p)
if err != nil {
return nil, err
}
urls = []string{info.TargetInfo.URL}
}
res, err := proto.NetworkGetCookies{Urls: urls}.Call(p)
if err != nil {
return nil, err
}
return res.Cookies, nil
}
// SetCookiesE of the page.
// Cookie format: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookie
func (p *Page) SetCookiesE(cookies []*proto.NetworkCookieParam) error {
err := proto.NetworkSetCookies{Cookies: cookies}.Call(p)
return err
}
// SetExtraHeadersE whether to always send extra HTTP headers with the requests from this page.
func (p *Page) SetExtraHeadersE(dict []string) error {
headers := proto.NetworkHeaders{}
for i := 0; i < len(dict); i += 2 {
headers[dict[i]] = proto.NewJSON(dict[i+1])
}
return proto.NetworkSetExtraHTTPHeaders{Headers: headers}.Call(p)
}
// SetUserAgentE Allows overriding user agent with the given string.
func (p *Page) SetUserAgentE(req *proto.NetworkSetUserAgentOverride) error {
if req == nil {
req = &proto.NetworkSetUserAgentOverride{
UserAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
AcceptLanguage: "en",
Platform: "MacIntel",
}
}
return req.Call(p)
}
// NavigateE doc is similar to the method Navigate
func (p *Page) NavigateE(url string) error {
err := p.StopLoadingE()
if err != nil {
return err
}
res, err := proto.PageNavigate{URL: url}.Call(p)
if err != nil {
return err
}
if res.ErrorText != "" {
return &Error{Code: ErrNavigation, Details: res.ErrorText}
}
return nil
}
func (p *Page) getWindowID() (proto.BrowserWindowID, error) {
res, err := proto.BrowserGetWindowForTarget{TargetID: p.TargetID}.Call(p)
if err != nil {
return 0, err
}
return res.WindowID, err
}
// GetWindowE doc is similar to the method GetWindow
func (p *Page) GetWindowE() (*proto.BrowserBounds, error) {
id, err := p.getWindowID()
if err != nil {
return nil, err
}
res, err := proto.BrowserGetWindowBounds{WindowID: id}.Call(p)
if err != nil {
return nil, err
}
return res.Bounds, nil
}
// WindowE https://chromedevtools.github.io/devtools-protocol/tot/Browser#type-Bounds
func (p *Page) WindowE(bounds *proto.BrowserBounds) error {
id, err := p.getWindowID()
if err != nil {
return err
}
err = proto.BrowserSetWindowBounds{WindowID: id, Bounds: bounds}.Call(p)
return err
}
// ViewportE doc is similar to the method Viewport
func (p *Page) ViewportE(params *proto.EmulationSetDeviceMetricsOverride) error {
p.viewport = params
err := params.Call(p)
return err
}
// StopLoadingE forces the page stop all navigations and pending resource fetches.
func (p *Page) StopLoadingE() error {
return proto.PageStopLoading{}.Call(p)
}
// CloseE page
func (p *Page) CloseE() error {
err := p.StopLoadingE()
if err != nil {
return err
}
err = proto.PageClose{}.Call(p)
if err != nil {
return err
}
p.ctxCancel()
return nil
}
// HandleDialogE doc is similar to the method HandleDialog
func (p *Page) HandleDialogE(accept bool, promptText string) func() error {
wait := p.WaitEvent()
return func() error {
wait(&proto.PageJavascriptDialogOpening{})
return proto.PageHandleJavaScriptDialog{
Accept: accept,
PromptText: promptText,
}.Call(p)
}
}
// GetDownloadFileE how it works is to proxy the request, the dir is the dir to save the file.
func (p *Page) GetDownloadFileE(dir, pattern string) (func() (http.Header, []byte, error), error) {
var fetchEnable *proto.FetchEnable
if pattern != "" {
fetchEnable = &proto.FetchEnable{
Patterns: []*proto.FetchRequestPattern{
{URLPattern: pattern},
},
}
}
// both Page.setDownloadBehavior and Fetch.enable will pollute the global status,
// we have to prevent race condition here
p.getDownloadFileLock.Lock()
err := proto.PageSetDownloadBehavior{
Behavior: proto.PageSetDownloadBehaviorBehaviorAllow,
DownloadPath: dir,
}.Call(p)
if err != nil {
return nil, err
}
err = fetchEnable.Call(p)
if err != nil {
return nil, err
}
wait := p.WaitEvent()
return func() (http.Header, []byte, error) {
defer p.getDownloadFileLock.Unlock()
var err error
defer func() {
e := proto.FetchDisable{}.Call(p)
if err == nil {
err = e
}
}()
msgReq := &proto.FetchRequestPaused{}
wait(msgReq)
req := kit.Req(msgReq.Request.URL).Context(p.ctx)
for k, v := range msgReq.Request.Headers {
req.Header(k, v.String())
}
res, err := req.Response()
if err != nil {
return nil, nil, err
}
body, err := req.Bytes()
if err != nil {
return nil, nil, err
}
headers := []*proto.FetchHeaderEntry{}
for k, vs := range res.Header {
for _, v := range vs {
headers = append(headers, &proto.FetchHeaderEntry{Name: k, Value: v})
}
}
err = proto.FetchFulfillRequest{
RequestID: msgReq.RequestID,
ResponseCode: int64(res.StatusCode),
ResponseHeaders: headers,
Body: body,
}.Call(p)
if err != nil {
return nil, nil, err
}
return res.Header, body, nil
}, err
}
// ScreenshotE options: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-captureScreenshot
func (p *Page) ScreenshotE(fullpage bool, req *proto.PageCaptureScreenshot) ([]byte, error) {
if fullpage {
metrics, err := proto.PageGetLayoutMetrics{}.Call(p)
if err != nil {
return nil, err
}
oldView := p.viewport
view := *oldView
view.Width = int64(metrics.ContentSize.Width)
view.Height = int64(metrics.ContentSize.Height)
err = p.ViewportE(&view)
if err != nil {
return nil, err
}
defer func() {
e := p.ViewportE(oldView)
if err == nil {
err = e
}
}()
}
shot, err := req.Call(p)
if err != nil {
return nil, err
}
return shot.Data, nil
}
// PDFE prints page as PDF
func (p *Page) PDFE(req *proto.PagePrintToPDF) ([]byte, error) {
res, err := req.Call(p)
if err != nil {
return nil, err
}
return res.Data, nil
}
// WaitOpenE doc is similar to the method WaitPage
func (p *Page) WaitOpenE() func() (*Page, error) {
b := p.browser.Context(p.ctx)
wait := b.EachEvent()
return func() (*Page, error) {
var targetID proto.TargetTargetID
wait(func(e *proto.TargetTargetCreated) bool {
if e.TargetInfo.OpenerID == p.TargetID {
targetID = e.TargetInfo.TargetID
return true
}
return false
})
return b.PageFromTargetIDE(targetID)
}
}
// PauseE doc is similar to the method Pause
func (p *Page) PauseE() error {
_, err := proto.DebuggerEnable{}.Call(p)
if err != nil {
return err
}
wait := p.WaitEvent()
err = proto.DebuggerPause{}.Call(p)
if err != nil {
return err
}
wait(&proto.DebuggerResumed{})
return nil
}
// WaitRequestIdleE returns a wait function that waits until no request for d duration.
// Use the includes and excludes regexp list to filter the requests by their url.
// Such as set n to 1 if there's a polling request.
func (p *Page) WaitRequestIdleE(d time.Duration, includes, excludes []string) func() error {
ctx, cancel := context.WithCancel(p.ctx)
s := p.event.Subscribe(ctx)
done := make(chan error)
go func() {
defer cancel()
reqList := map[proto.NetworkRequestID]kit.Nil{}
timeout := time.NewTimer(d)
reset := func(id proto.NetworkRequestID) {
delete(reqList, id)
if len(reqList) == 0 {
timeout.Reset(d)
}
}
for {
select {
case <-p.ctx.Done():
done <- p.ctx.Err()
return
case <-timeout.C:
done <- nil
return
case msg, ok := <-s:
if !ok {
done <- nil
return
}
e := msg.(*cdp.Event)
sent := &proto.NetworkRequestWillBeSent{}
finished := &proto.NetworkLoadingFinished{} // it will be after the Network.responseReceived
failed := &proto.NetworkLoadingFailed{}
if Event(e, sent) {
timeout.Stop()
kit.E(json.Unmarshal(e.Params, sent))
url := sent.Request.URL
id := sent.RequestID
if matchWithFilter(url, includes, excludes) {
reqList[id] = kit.Nil{}
}
} else if Event(e, finished) {
kit.E(json.Unmarshal(e.Params, finished))
reset(finished.RequestID)
} else if Event(e, failed) {
kit.E(json.Unmarshal(e.Params, failed))
reset(failed.RequestID)
}
}
}
}()
return func() (err error) {
defer func() { done = nil }()
if done == nil {
panic("can't use wait function twice")
}
if p.browser.trace {
defer p.Overlay(0, 0, 300, 0, "waiting for request idle "+strings.Join(includes, " "))()
}
return <-done
}
}
// WaitIdleE doc is similar to the method WaitIdle
func (p *Page) WaitIdleE(timeout time.Duration) (err error) {
_, err = p.EvalE(true, "", p.jsFn("waitIdle"), Array{timeout.Seconds()})
return err
}
// WaitLoadE doc is similar to the method WaitLoad
func (p *Page) WaitLoadE() error {
_, err := p.EvalE(true, "", p.jsFn("waitLoad"), nil)
return err
}
// WaitEvent waits for the next event for one time. It will also load the data into the event object.
func (p *Page) WaitEvent() (wait func(proto.Event)) {
ctx, cancel := context.WithCancel(p.ctx)
s := p.event.Subscribe(ctx)
return func(e proto.Event) {
defer cancel()
for msg := range s {
if Event(msg.(*cdp.Event), e) {
return
}
}
}
}
// AddScriptTagE to page. If url is empty, content will be used.
func (p *Page) AddScriptTagE(url, content string) error {
hash := md5.Sum([]byte(url + content))
id := hex.EncodeToString(hash[:])
_, err := p.EvalE(true, "", p.jsFn("addScriptTag"), Array{id, url, content})
return err
}
// AddStyleTagE to page. If url is empty, content will be used.
func (p *Page) AddStyleTagE(url, content string) error {
hash := md5.Sum([]byte(url + content))
id := hex.EncodeToString(hash[:])
_, err := p.EvalE(true, "", p.jsFn("addStyleTag"), Array{id, url, content})
return err
}
// EvalE thisID is the remote objectID that will be the this of the js function, if it's empty "window" will be used.
// Set the byValue to true to reduce memory occupation.
func (p *Page) EvalE(byValue bool, thisID proto.RuntimeRemoteObjectID, js string, jsArgs Array) (*proto.RuntimeRemoteObject, error) {
backoff := kit.BackoffSleeper(30*time.Millisecond, 3*time.Second, nil)
objectID := thisID
var err error
var res *proto.RuntimeCallFunctionOnResult
// js context will be invalid if a frame is reloaded
err = kit.Retry(p.ctx, backoff, func() (bool, error) {
if thisID == "" {
if p.windowObjectID == "" {
err := p.initJS()
if err != nil {
if isNilContextErr(err) {
return false, nil
}
return true, err
}
}
objectID = p.windowObjectID
}
args := []*proto.RuntimeCallArgument{}
for _, p := range jsArgs {
args = append(args, &proto.RuntimeCallArgument{Value: proto.NewJSON(p)})
}
res, err = proto.RuntimeCallFunctionOn{
ObjectID: objectID,
AwaitPromise: true,
ReturnByValue: byValue,
FunctionDeclaration: SprintFnThis(js),
Arguments: args,
}.Call(p)
if thisID == "" {
if isNilContextErr(err) {
_ = p.initJS()
return false, nil
}
}
return true, err
})
if err != nil {
return nil, err
}
if res.ExceptionDetails != nil {
return nil, &Error{nil, ErrEval, res.ExceptionDetails.Exception.Description}
}
return res.Result, nil
}
// Sleeper returns the default sleeper for retry, it uses backoff and requestIdleCallback to wait
func (p *Page) Sleeper() kit.Sleeper {
return kit.BackoffSleeper(100*time.Millisecond, time.Second, nil)
}
// ElementFromObjectID creates an Element from the remote object id.
func (p *Page) ElementFromObjectID(id proto.RuntimeRemoteObjectID) *Element {
return (&Element{
page: p,
ObjectID: id,
}).Context(p.ctx)
}
// ReleaseE doc is similar to the method Release
func (p *Page) ReleaseE(objectID proto.RuntimeRemoteObjectID) error {
err := proto.RuntimeReleaseObject{ObjectID: objectID}.Call(p)
return err
}
// CallContext parameters for proto
func (p *Page) CallContext() (context.Context, proto.Client, string) {
return p.ctx, p.browser.client, string(p.SessionID)
}
func (p *Page) initSession() error {
obj, err := proto.TargetAttachToTarget{
TargetID: p.TargetID,
Flatten: true, // if it's not set no response will return
}.Call(p)
if err != nil {
return err
}
p.SessionID = obj.SessionID
err = p.initEvents()
if err != nil {
return err
}
res, err := proto.DOMGetDocument{}.Call(p)
if err != nil {
return err
}
for _, child := range res.Root.Children {
frameID := child.FrameID
if frameID != "" {
p.FrameID = frameID
}
}
return nil
}
func (p *Page) initEvents() error {
p.event = p.browser.event.Filter(p.ctx, func(e *cdp.Event) bool {
return e.SessionID == string(p.SessionID)
})
err := proto.PageEnable{}.Call(p)
if err != nil {
return err
}
err = proto.NetworkEnable{}.Call(p)
if err != nil {
return err
}
return nil
}
func (p *Page) initJS() error {
scriptURL := "\n//# sourceURL=__rod_helper__"
params := &proto.RuntimeEvaluate{
Expression: sprintFnApply(assets.Helper, Array{p.FrameID}) + scriptURL,
}
if p.IsIframe() {
res, err := proto.PageCreateIsolatedWorld{
FrameID: p.FrameID,
}.Call(p)
if err != nil {
return err
}
params.ContextID = res.ExecutionContextID
}
res, err := params.Call(p)
if err != nil {
return err
}
p.windowObjectID = res.Result.ObjectID
if p.browser.trace {
_, err := p.EvalE(true, "", p.jsFn("initMouseTracer"), Array{p.Mouse.id, assets.MousePointer})
if err != nil {
return err
}
}
return nil
}
func (p *Page) jsFnPrefix() string {
return "rod" + string(p.FrameID) + "."
}
func (p *Page) jsFn(fnName string) string {
return p.jsFnPrefix() + fnName
}