-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
page.go
840 lines (717 loc) · 24.2 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
package rod
import (
"context"
"crypto/md5"
"encoding/base64"
"encoding/hex"
"fmt"
"sync"
"time"
"github.com/go-rod/rod/lib/devices"
"github.com/go-rod/rod/lib/js"
"github.com/go-rod/rod/lib/proto"
"github.com/go-rod/rod/lib/utils"
"github.com/ysmood/goob"
"github.com/ysmood/gson"
)
// Page implements these interfaces
// Page 实现的接口
var _ proto.Client = &Page{}
var _ proto.Contextable = &Page{}
var _ proto.Sessionable = &Page{}
// Page represents the webpage.
// Page 代表网页页面
// We try to hold as less states as possible.
// 我们会尽可能减少页面所拥有的状态
// When a page is closed by Rod or not all the ongoing operations an events on it will abort.
// 当一个页面被Rod关闭或不是所有正在进行的操作时,它上的事件将中止。
type Page struct {
// TargetID is a unique ID for a remote page.
// TargetID 每个页面独有的ID
// It's usually used in events sent from the browser to tell which page an event belongs to.
// 它通常用于从浏览器发送的事件中,以说明事件属于哪个页面。
TargetID proto.TargetTargetID
// FrameID is a unique ID for a browsing context.
// FrameID 是浏览器 ctx 的独有ID
// Usually, different FrameID means different javascript execution context.
// 通常,不同的FrameID 意味着不同的JS执行ctx
// Such as an iframe and the page it belongs to will have the same TargetID but different FrameIDs.
// 如一个iframe和它所属的页面有相同的TargetID,但不同的FrameID。
FrameID proto.PageFrameID
// SessionID is a unique ID for a page attachment to a controller.
// SessionID 是指向控制器的页面附件的唯一ID。
// It's usually used in transport layer to tell which page to send the control signal.
// 它通常用于传输层,告诉哪个页面要发送控制信号。
// A page can attached to multiple controllers, the browser uses it distinguish controllers.
// 一个页面可以附加到多个控制器,浏览器使用它来区分控制器。
SessionID proto.TargetSessionID
e eFunc
ctx context.Context
// Used to abort all ongoing actions when a page closes.
// 用于在页面关闭时中止所有正在进行的操作。
sessionCancel func()
root *Page
sleeper func() utils.Sleeper
browser *Browser
event *goob.Observable
// devices // 页面中的设备
Mouse *Mouse
Keyboard *Keyboard
Touch *Touch
element *Element // iframe only
jsCtxLock *sync.Mutex
jsCtxID *proto.RuntimeRemoteObjectID // use pointer so that page clones can share the change // 使用指针,以便于页面克隆时可以共享更改
helpersLock *sync.Mutex
helpers map[proto.RuntimeRemoteObjectID]map[string]proto.RuntimeRemoteObjectID
}
// String interface
func (p *Page) String() string {
id := p.TargetID
if len(id) > 8 {
id = id[:8]
}
return fmt.Sprintf("<page:%s>", id)
}
// IsIframe tells if it's iframe
// IsIframe 用于判断页面是否是一个iframe
func (p *Page) IsIframe() bool {
return p.element != nil
}
// GetSessionID interface
// 获取 SessionID 的接口
func (p *Page) GetSessionID() proto.TargetSessionID {
return p.SessionID
}
// Browser of the page
// 页面所属的浏览器对象
func (p *Page) Browser() *Browser {
return p.browser
}
// Info of the page, such as the URL or title of the page
// 打印页面的信息,例页面的URL,标题等。
func (p *Page) Info() (*proto.TargetTargetInfo, error) {
return p.browser.pageInfo(p.TargetID)
}
// HTML of the page
// 获取页面的HTML代码
func (p *Page) HTML() (string, error) {
el, err := p.Element("html")
if err != nil {
return "", err
}
return el.HTML()
}
// Cookies returns the page cookies. By default it will return the cookies for current page.
// 用于返回当前页面的Cookies。默认返回当前页面的Cookies。
// The urls is the list of URLs for which applicable cookies will be fetched.
// urls 是获取Cookies的URL列表
func (p *Page) Cookies(urls []string) ([]*proto.NetworkCookie, error) {
if len(urls) == 0 {
info, err := p.Info()
if err != nil {
return nil, err
}
urls = []string{info.URL}
}
res, err := proto.NetworkGetCookies{Urls: urls}.Call(p)
if err != nil {
return nil, err
}
return res.Cookies, nil
}
// SetCookies is similar to Browser.SetCookies .
// SetCookies 类似于 Browser.SetCookies .
func (p *Page) SetCookies(cookies []*proto.NetworkCookieParam) error {
if cookies == nil {
return proto.NetworkClearBrowserCookies{}.Call(p)
}
return proto.NetworkSetCookies{Cookies: cookies}.Call(p)
}
// SetExtraHeaders whether to always send extra HTTP headers with the requests from this page.
// SetExtraHeaders 是否总是从这个页面的请求中发送额外的HTTP头信息。用于向页面中的请求添加额外的请求头。
func (p *Page) SetExtraHeaders(dict []string) (func(), error) {
headers := proto.NetworkHeaders{}
for i := 0; i < len(dict); i += 2 {
headers[dict[i]] = gson.New(dict[i+1])
}
return p.EnableDomain(&proto.NetworkEnable{}), proto.NetworkSetExtraHTTPHeaders{Headers: headers}.Call(p)
}
// SetUserAgent (browser brand, accept-language, etc) of the page.
// 用于设置页面中的UserAgent
// If req is nil, a default user agent will be used, a typical mac chrome.
// 如果 req 的值是 nil 将会使用默认的 UserAgent,典型的例如 mac chrome
func (p *Page) SetUserAgent(req *proto.NetworkSetUserAgentOverride) error {
if req == nil {
req = devices.LaptopWithMDPIScreen.UserAgentEmulation()
}
return req.Call(p)
}
// Navigate to the url. If the url is empty, "about:blank" will be used.
// 导航至 url 地址,如果 url 是空的,则默认使用 "about:blank"
// It will return immediately after the server responds the http header.
// 在接收到服务器HTTP响应头后,立即返回。
func (p *Page) Navigate(url string) error {
if url == "" {
url = "about:blank"
}
// try to stop loading
// 尝试停止加载页面
_ = p.StopLoading()
res, err := proto.PageNavigate{URL: url}.Call(p)
if err != nil {
return err
}
if res.ErrorText != "" {
return &ErrNavigation{res.ErrorText}
}
p.root.unsetJSCtxID()
return nil
}
// NavigateBack history.
// 返回到历史页面
func (p *Page) NavigateBack() error {
// Not using cdp API because it doesn't work for iframe
// 注意:因为不适用于 iframe 所以才使用了 cdp API
_, err := p.Evaluate(Eval(`() => history.back()`).ByUser())
return err
}
// NavigateForward history.
// 前进到历史页面
func (p *Page) NavigateForward() error {
// Not using cdp API because it doesn't work for iframe
// 注意:因为不适用于 iframe 所以才使用了 cdp API
_, err := p.Evaluate(Eval(`() => history.forward()`).ByUser())
return err
}
// Reload page.
// 刷新页面
func (p *Page) Reload() error {
p, cancel := p.WithCancel()
defer cancel()
wait := p.EachEvent(func(e *proto.PageFrameNavigated) bool {
return e.Frame.ID == p.FrameID
})
// Not using cdp API because it doesn't work for iframe
// 注意:因为不适用于 iframe 所以才使用了 cdp API
_, err := p.Evaluate(Eval(`() => location.reload()`).ByUser())
if err != nil {
return err
}
wait()
p.unsetJSCtxID()
return nil
}
// Activate (focuses) the page
// 激活页面
func (p *Page) Activate() (*Page, error) {
err := proto.TargetActivateTarget{TargetID: p.TargetID}.Call(p.browser)
return p, err
}
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
}
// GetWindow position and size info
// 获取页面窗口大小信息
func (p *Page) GetWindow() (*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
}
// SetWindow location and size
// 设置窗口位置和大小
func (p *Page) SetWindow(bounds *proto.BrowserBounds) error {
id, err := p.getWindowID()
if err != nil {
return err
}
err = proto.BrowserSetWindowBounds{WindowID: id, Bounds: bounds}.Call(p)
return err
}
// SetViewport overrides the values of device screen dimensions
// SetViewport覆盖设备屏幕尺寸的值
func (p *Page) SetViewport(params *proto.EmulationSetDeviceMetricsOverride) error {
if params == nil {
return proto.EmulationClearDeviceMetricsOverride{}.Call(p)
}
return params.Call(p)
}
// SetDocumentContent sets the page document html content
// 在页面中添加 HTML 内容
func (p *Page) SetDocumentContent(html string) error {
return proto.PageSetDocumentContent{
FrameID: p.FrameID,
HTML: html,
}.Call(p)
}
// Emulate the device, such as iPhone9. If device is devices.Clear, it will clear the override.
// 模拟设备,例如 IPhone9,。如果 devices是devcs.Clear,将会清除覆盖
func (p *Page) Emulate(device devices.Device) error {
err := p.SetViewport(device.MetricsEmulation())
if err != nil {
return err
}
err = device.TouchEmulation().Call(p)
if err != nil {
return err
}
return p.SetUserAgent(device.UserAgentEmulation())
}
// StopLoading forces the page stop navigation and pending resource fetches.
// 强制停止页面的加载以及资源的请求
func (p *Page) StopLoading() error {
return proto.PageStopLoading{}.Call(p)
}
// Close tries to close page, running its beforeunload hooks, if has any.
// 尝试关闭页面,如果有的话,它会运行 beforeunload 钩子函数。
func (p *Page) Close() error {
p.browser.targetsLock.Lock()
defer p.browser.targetsLock.Unlock()
success := true
ctx, cancel := context.WithCancel(p.ctx)
defer cancel()
messages := p.browser.Context(ctx).Event()
err := proto.PageClose{}.Call(p)
if err != nil {
return err
}
for msg := range messages {
stop := false
destroyed := proto.TargetTargetDestroyed{}
closed := proto.PageJavascriptDialogClosed{}
if msg.Load(&destroyed) {
stop = destroyed.TargetID == p.TargetID
} else if msg.SessionID == p.SessionID && msg.Load(&closed) {
success = closed.Result
stop = !success
}
if stop {
break
}
}
if success {
p.cleanupStates()
} else {
return &ErrPageCloseCanceled{}
}
return nil
}
// HandleDialog accepts or dismisses next JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload).
// HandleDialog 接受或驳回下一个JavaScript发起的对话框(警报、确认、提示或onbeforeunload)。
// Because modal dialog will block js, usually you have to trigger the dialog in another goroutine.
// 由于模态对话框将阻塞js,通常您必须在另一个goroutine中触发对话框。
// For example:
//
// wait, handle := page.MustHandleDialog()
// go page.MustElement("button").MustClick()
// wait()
// handle(true, "")
//
func (p *Page) HandleDialog() (
wait func() *proto.PageJavascriptDialogOpening,
handle func(*proto.PageHandleJavaScriptDialog) error,
) {
restore := p.EnableDomain(&proto.PageEnable{})
var e proto.PageJavascriptDialogOpening
w := p.WaitEvent(&e)
return func() *proto.PageJavascriptDialogOpening {
w()
return &e
}, func(h *proto.PageHandleJavaScriptDialog) error {
defer restore()
return h.Call(p)
}
}
// Screenshot captures the screenshot of current page.
// 捕获当前页面的截图
func (p *Page) Screenshot(fullpage bool, req *proto.PageCaptureScreenshot) ([]byte, error) {
if req == nil {
req = &proto.PageCaptureScreenshot{}
}
if fullpage {
metrics, err := proto.PageGetLayoutMetrics{}.Call(p)
if err != nil {
return nil, err
}
oldView := proto.EmulationSetDeviceMetricsOverride{}
set := p.LoadState(&oldView)
view := oldView
view.Width = int(metrics.CSSContentSize.Width)
view.Height = int(metrics.CSSContentSize.Height)
err = p.SetViewport(&view)
if err != nil {
return nil, err
}
defer func() { // try to recover the viewport
if !set {
_ = proto.EmulationClearDeviceMetricsOverride{}.Call(p)
return
}
_ = p.SetViewport(&oldView)
}()
}
shot, err := req.Call(p)
if err != nil {
return nil, err
}
return shot.Data, nil
}
// PDF prints page as PDF
// 将页面保存为 PDF
func (p *Page) PDF(req *proto.PagePrintToPDF) (*StreamReader, error) {
req.TransferMode = proto.PagePrintToPDFTransferModeReturnAsStream
res, err := req.Call(p)
if err != nil {
return nil, err
}
return NewStreamReader(p, res.Stream), nil
}
// GetResource content by the url. Such as image, css, html, etc.
// 通过URL获取页面中的资源,例如 image,css,html等
// Use the proto.PageGetResourceTree to list all the resources.
// 使用 proto.PageGetResourceTree 会返回所有的资源
func (p *Page) GetResource(url string) ([]byte, error) {
res, err := proto.PageGetResourceContent{
FrameID: p.FrameID,
URL: url,
}.Call(p)
if err != nil {
return nil, err
}
data := res.Content
var bin []byte
if res.Base64Encoded {
bin, err = base64.StdEncoding.DecodeString(data)
utils.E(err)
} else {
bin = []byte(data)
}
return bin, nil
}
// WaitOpen waits for the next new page opened by the current one
// 等待打开从当前页面打开的新页面
func (p *Page) WaitOpen() func() (*Page, error) {
var targetID proto.TargetTargetID
b := p.browser.Context(p.ctx)
wait := b.EachEvent(func(e *proto.TargetTargetCreated) bool {
targetID = e.TargetInfo.TargetID
return e.TargetInfo.OpenerID == p.TargetID
})
return func() (*Page, error) {
defer p.tryTrace(TraceTypeWait, "wait open")()
wait()
return b.PageFromTarget(targetID)
}
}
// EachEvent of the specified event types, if any callback returns true the wait function will resolve,
// 指定事件类型的事件,如果任何回调返回 true 等待函数将会解决,
// The type of each callback is (? means optional):
// 每一个回调类型
//
// func(proto.Event, proto.TargetSessionID?) bool?
//
// You can listen to multiple event types at the same time like:
// 你可以监听很多事件类型同时:
//
// browser.EachEvent(func(a *proto.A) {}, func(b *proto.B) {})
//
// Such as subscribe the events to know when the navigation is complete or when the page is rendered.
// 例如订阅事件,以便于了解navigation何时完成或者页面何时渲染完成。
// Here's an example to dismiss all dialogs/alerts on the page:
// 这里是一个关闭所有对话框的例子:
//
// go page.EachEvent(func(e *proto.PageJavascriptDialogOpening) {
// _ = proto.PageHandleJavaScriptDialog{ Accept: false, PromptText: ""}.Call(page)
// })()
//
func (p *Page) EachEvent(callbacks ...interface{}) (wait func()) {
return p.browser.Context(p.ctx).eachEvent(p.SessionID, callbacks...)
}
// WaitEvent waits for the next event for one time. It will also load the data into the event object.
// 等待下一个发生的事件一次。它还会将数据加载到事件对象中。
func (p *Page) WaitEvent(e proto.Event) (wait func()) {
defer p.tryTrace(TraceTypeWait, "event", e.ProtoEvent())()
return p.browser.Context(p.ctx).waitEvent(p.SessionID, e)
}
// WaitNavigation wait for a page lifecycle event when navigating.
// WaitNavigation 在导航时等待一个页面生命周期事件。
// Usually you will wait for proto.PageLifecycleEventNameNetworkAlmostIdle
// 通常等待的是:proto.PageLifecycleEventNameNetworkAlmostIdle
func (p *Page) WaitNavigation(name proto.PageLifecycleEventName) func() {
_ = proto.PageSetLifecycleEventsEnabled{Enabled: true}.Call(p)
wait := p.EachEvent(func(e *proto.PageLifecycleEvent) bool {
return e.Name == name
})
return func() {
defer p.tryTrace(TraceTypeWait, "navigation", name)()
wait()
_ = proto.PageSetLifecycleEventsEnabled{Enabled: false}.Call(p)
}
}
// WaitRequestIdle returns a wait function that waits until no request for d duration.
// WaitRequestIdle 返回一个等待函数,等待持续d时间内没有请求为止。
// Be careful, d is not the max wait timeout, it's the least idle time.
// 注意:d不是最大超时时间,而是最小空闲时间
// If you want to set a timeout you can use the "Page.Timeout" function.
// 如果你想为页面设置超时,请使用:`Page.timeout` 函数
// Use the includes and excludes regexp list to filter the requests by their url.
// 使用includes和excludes regexp列表按请求的url筛选请求
func (p *Page) WaitRequestIdle(d time.Duration, includes, excludes []string) func() {
if len(includes) == 0 {
includes = []string{""}
}
p, cancel := p.WithCancel()
match := genRegMatcher(includes, excludes)
waitlist := map[proto.NetworkRequestID]string{}
idleCounter := utils.NewIdleCounter(d)
update := p.tryTraceReq(includes, excludes)
update(nil)
checkDone := func(id proto.NetworkRequestID) {
if _, has := waitlist[id]; has {
delete(waitlist, id)
update(waitlist)
idleCounter.Done()
}
}
wait := p.EachEvent(func(sent *proto.NetworkRequestWillBeSent) {
if match(sent.Request.URL) {
// Redirect will send multiple NetworkRequestWillBeSent events with the same RequestID,
// we should filter them out.
// 过滤掉重定向发送的多个相同 RequestsID 的 NetworkRequestWillBeSent 事件。
if _, has := waitlist[sent.RequestID]; !has {
waitlist[sent.RequestID] = sent.Request.URL
update(waitlist)
idleCounter.Add()
}
}
}, func(e *proto.NetworkLoadingFinished) {
checkDone(e.RequestID)
}, func(e *proto.NetworkLoadingFailed) {
checkDone(e.RequestID)
})
return func() {
go func() {
idleCounter.Wait(p.ctx)
cancel()
}()
wait()
}
}
// WaitIdle waits until the next window.requestIdleCallback is called.
// WaitIdle 等待直到 window.requestIdleCallback 被调用
func (p *Page) WaitIdle(timeout time.Duration) (err error) {
_, err = p.Evaluate(evalHelper(js.WaitIdle, timeout.Seconds()).ByPromise())
return err
}
// WaitRepaint waits until the next repaint.
// WaitRepaint会等待下一次重绘。
// Doc: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
func (p *Page) WaitRepaint() error {
// we use root here because iframe doesn't trigger requestAnimationFrame
_, err := p.root.Eval(`() => new Promise(r => requestAnimationFrame(r))`)
return err
}
// WaitLoad waits for the `window.onload` event, it returns immediately if the event is already fired.
// 等待 `window.load` 事件触发,如果已经被触发,则会立即返回
func (p *Page) WaitLoad() error {
defer p.tryTrace(TraceTypeWait, "load")()
_, err := p.Evaluate(evalHelper(js.WaitLoad).ByPromise())
return err
}
// AddScriptTag to page. If url is empty, content will be used.
// 向页面添加 Script 标签。如果url是空的,content参数将会被使用
func (p *Page) AddScriptTag(url, content string) error {
hash := md5.Sum([]byte(url + content))
id := hex.EncodeToString(hash[:])
_, err := p.Evaluate(evalHelper(js.AddScriptTag, id, url, content).ByPromise())
return err
}
// AddStyleTag to page. If url is empty, content will be used.
// 向页面添加 CSS 标签。如果url是空的,content参数将会被使用
func (p *Page) AddStyleTag(url, content string) error {
hash := md5.Sum([]byte(url + content))
id := hex.EncodeToString(hash[:])
_, err := p.Evaluate(evalHelper(js.AddStyleTag, id, url, content).ByPromise())
return err
}
// EvalOnNewDocument Evaluates given script in every frame upon creation (before loading frame's scripts).
// 会在每一个新的 frame 创建时,执行给定的JS脚本
func (p *Page) EvalOnNewDocument(js string) (remove func() error, err error) {
res, err := proto.PageAddScriptToEvaluateOnNewDocument{Source: js}.Call(p)
if err != nil {
return
}
remove = func() error {
return proto.PageRemoveScriptToEvaluateOnNewDocument{
Identifier: res.Identifier,
}.Call(p)
}
return
}
// Wait until the js returns true
// 等待 JS 脚本执行返回 true (JS执行成功)
func (p *Page) Wait(opts *EvalOptions) error {
return utils.Retry(p.ctx, p.sleeper(), func() (bool, error) {
res, err := p.Evaluate(opts)
if err != nil {
return true, err
}
return res.Value.Bool(), nil
})
}
// WaitElementsMoreThan Wait until there are more than <num> <selector> elements.
// 判断某个元素在页面上是否出现以及出现的次数
func (p *Page) WaitElementsMoreThan(selector string, num int) error {
return p.Wait(Eval(`(s, n) => document.querySelectorAll(s).length > n`, selector, num))
}
// ObjectToJSON by object id
// 通过对象ID将对象转换为JSON
func (p *Page) ObjectToJSON(obj *proto.RuntimeRemoteObject) (gson.JSON, error) {
if obj.ObjectID == "" {
return obj.Value, nil
}
res, err := proto.RuntimeCallFunctionOn{
ObjectID: obj.ObjectID,
FunctionDeclaration: `function() { return this }`,
ReturnByValue: true,
}.Call(p)
if err != nil {
return gson.New(nil), err
}
return res.Result.Value, nil
}
// ElementFromObject creates an Element from the remote object id.
// ElementFromObject从远程对象id创建一个元素。
func (p *Page) ElementFromObject(obj *proto.RuntimeRemoteObject) (*Element, error) {
// If the element is in an iframe, we need the jsCtxID to inject helper.js to the correct context.
// 如果该元素是在一个iframe中,我们需要jsCtxID来注入helper.js到正确的上下文。
id, err := p.jsCtxIDByObjectID(obj.ObjectID)
if err != nil {
return nil, err
}
pid, err := p.getJSCtxID()
if err != nil {
return nil, err
}
if id != pid {
clone := *p
clone.jsCtxID = &id
p = &clone
}
return &Element{
e: p.e,
ctx: p.ctx,
sleeper: p.sleeper,
page: p,
Object: obj,
}, nil
}
// ElementFromNode creates an Element from the node, NodeID or BackendNodeID must be specified.
// ElementFromNode从节点创建一个元素,必须指定NodeID或BackendNodeID。
func (p *Page) ElementFromNode(node *proto.DOMNode) (*Element, error) {
res, err := proto.DOMResolveNode{
NodeID: node.NodeID,
BackendNodeID: node.BackendNodeID,
}.Call(p)
if err != nil {
return nil, err
}
el, err := p.ElementFromObject(res.Object)
if err != nil {
return nil, err
}
// make sure always return an element node
// 确保总是返回一个element节点
desc, err := el.Describe(0, false)
if err != nil {
return nil, err
}
if desc.NodeName == "#text" {
el, err = el.Parent()
if err != nil {
return nil, err
}
}
return el, nil
}
// ElementFromPoint creates an Element from the absolute point on the page.
// ElementFromPoint从页面上的绝对点创建一个元素。
// The point should include the window scroll offset.
// 该点应包括窗口滚动偏移量。
func (p *Page) ElementFromPoint(x, y int) (*Element, error) {
node, err := proto.DOMGetNodeForLocation{X: x, Y: y}.Call(p)
if err != nil {
return nil, err
}
return p.ElementFromNode(&proto.DOMNode{
BackendNodeID: node.BackendNodeID,
})
}
// Release the remote object. Usually, you don't need to call it.
// 释放远程对象。通常情况下,你不需要调用它。
// When a page is closed or reloaded, all remote objects will be released automatically.
// 当一个页面被关闭或重新加载时,所有的远程对象将被自动释放。
// It's useful if the page never closes or reloads.
// 这对于页面从来没有被关闭或者重新加载过是非常有用的。
func (p *Page) Release(obj *proto.RuntimeRemoteObject) error {
err := proto.RuntimeReleaseObject{ObjectID: obj.ObjectID}.Call(p)
return err
}
// Call implements the proto.Client
// 实现了 `proto.Client`
func (p *Page) Call(ctx context.Context, sessionID, methodName string, params interface{}) (res []byte, err error) {
return p.browser.Call(ctx, sessionID, methodName, params)
}
// Event of the page
// 页面上的事件
func (p *Page) Event() <-chan *Message {
dst := make(chan *Message)
s := p.event.Subscribe(p.ctx)
go func() {
defer close(dst)
for {
select {
case <-p.ctx.Done():
return
case msg, ok := <-s:
if !ok {
return
}
select {
case <-p.ctx.Done():
return
case dst <- msg.(*Message):
}
}
}
}()
return dst
}
func (p *Page) initEvents() {
p.event = goob.New(p.ctx)
event := p.browser.Context(p.ctx).Event()
go func() {
for msg := range event {
detached := proto.TargetDetachedFromTarget{}
destroyed := proto.TargetTargetDestroyed{}
if (msg.Load(&detached) && detached.SessionID == p.SessionID) ||
(msg.Load(destroyed) && destroyed.TargetID == p.TargetID) {
p.sessionCancel()
return
}
if msg.SessionID != p.SessionID {
continue
}
p.event.Publish(msg)
}
}()
}