forked from raff/godet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
godet.go
1708 lines (1423 loc) · 47.1 KB
/
godet.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 godet implements a client to interact with an instance of Chrome via the Remote Debugging Protocol.
//
// See https://developer.chrome.com/devtools/docs/debugger-protocol
package godet
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"path/filepath"
"time"
"github.com/gobs/httpclient"
"github.com/gorilla/websocket"
)
const (
// EventClosed represents the "RemoteDebugger.closed" event.
// It is emitted when RemoteDebugger.Close() is called.
EventClosed = "RemoteDebugger.closed"
// EventClosed represents the "RemoteDebugger.disconnected" event.
// It is emitted when we lose connection with the debugger and we stop reading events
EventDisconnect = "RemoteDebugger.disconnected"
// NavigationProceed allows the navigation
NavigationProceed = NavigationResponse("Proceed")
// NavigationCancel cancels the navigation
NavigationCancel = NavigationResponse("Cancel")
// NavigationCancelAndIgnore cancels the navigation and makes the requester of the navigation acts like the request was never made.
NavigationCancelAndIgnore = NavigationResponse("CancelAndIgnore")
ErrorReasonFailed = ErrorReason("Failed")
ErrorReasonAborted = ErrorReason("Aborted")
ErrorReasonTimedOut = ErrorReason("TimedOut")
ErrorReasonAccessDenied = ErrorReason("AccessDenied")
ErrorReasonConnectionClosed = ErrorReason("ConnectionClosed")
ErrorReasonConnectionReset = ErrorReason("ConnectionReset")
ErrorReasonConnectionRefused = ErrorReason("ConnectionRefused")
ErrorReasonConnectionAborted = ErrorReason("ConnectionAborted")
ErrorReasonConnectionFailed = ErrorReason("ConnectionFailed")
ErrorReasonNameNotResolved = ErrorReason("NameNotResolved")
ErrorReasonInternetDisconnected = ErrorReason("InternetDisconnected")
ErrorReasonAddressUnreachable = ErrorReason("AddressUnreachable")
ErrorReasonBlockedByClient = ErrorReason("BlockedByClient")
ErrorReasonBlockedByResponse = ErrorReason("BlockedByResponse")
// VirtualTimePolicyAdvance specifies that if the scheduler runs out of immediate work, the virtual time base may fast forward to allow the next delayed task (if any) to run
VirtualTimePolicyAdvance = VirtualTimePolicy("advance")
// VirtualTimePolicyPause specifies that the virtual time base may not advance
VirtualTimePolicyPause = VirtualTimePolicy("pause")
// VirtualTimePolicyPauseIfNetworkFetchesPending specifies that the virtual time base may not advance if there are any pending resource fetches.
VirtualTimePolicyPauseIfNetworkFetchesPending = VirtualTimePolicy("pauseIfNetworkFetchesPending")
AllowDownload = DownloadBehavior("allow")
NameDownload = DownloadBehavior("allowAndName")
DenyDownload = DownloadBehavior("deny")
DefaultDownload = DownloadBehavior("default")
)
type IdType int
const (
NodeId IdType = iota
BackendNodeId
ObjectId
)
var (
// ErrorNoActiveTab is returned if there are no active tabs (of type "page")
ErrorNoActiveTab = errors.New("no active tab")
// ErrorNoWsURL is returned if the active tab has no websocket URL
ErrorNoWsURL = errors.New("no websocket URL")
// ErrorNoResponse is returned if a method was expecting a response but got nil instead
ErrorNoResponse = errors.New("no response")
// ErrorClose is returned if a method is called after the connection has been close
ErrorClose = errors.New("closed")
MaxReadBufferSize = 0 // default gorilla/websocket buffer size
MaxWriteBufferSize = 100 * 1024 // this should be large enough to send large scripts
)
// NavigationResponse defines the type for ProcessNavigation `response`
type NavigationResponse string
// ErrorReason defines what error should be generated to abort a request in ContinueInterceptedRequest
type ErrorReason string
// VirtualTimePolicy defines the type for Emulation.SetVirtualTimePolicy
type VirtualTimePolicy string
// DownloadBehaviour defines the type for Page.SetDownloadBehavior
type DownloadBehavior string
func decode(resp *httpclient.HttpResponse, v interface{}) error {
err := json.NewDecoder(resp.Body).Decode(v)
resp.Close()
return err
}
func unmarshal(payload []byte) (map[string]interface{}, error) {
var response map[string]interface{}
err := json.Unmarshal(payload, &response)
if err != nil {
log.Println("unmarshal", string(payload), len(payload), err)
}
return response, err
}
func responseError(resp *httpclient.HttpResponse, err error) (*httpclient.HttpResponse, error) {
if err == nil {
return resp, resp.ResponseError()
}
return resp, err
}
// Version holds the DevTools version information.
type Version struct {
Browser string `json:"Browser"`
ProtocolVersion string `json:"Protocol-Version"`
UserAgent string `json:"User-Agent"`
V8Version string `json:"V8-Version"`
WebKitVersion string `json:"WebKit-Version"`
}
// Domain holds a domain name and version.
type Domain struct {
Name string `json:"name"`
Version string `json:"version"`
}
// Tab represents an opened tab/page.
type Tab struct {
ID string `json:"id"`
Type string `json:"type"`
Description string `json:"description"`
Title string `json:"title"`
URL string `json:"url"`
WsURL string `json:"webSocketDebuggerUrl"`
DevURL string `json:"devtoolsFrontendUrl"`
}
// NavigationEntry represent a navigation history entry.
type NavigationEntry struct {
ID int64 `json:"id"`
URL string `json:"url"`
Title string `json:"title"`
}
// Profile represents a profile data structure.
type Profile struct {
Nodes []ProfileNode `json:"nodes"`
StartTime int64 `json:"startTime"`
EndTime int64 `json:"endTime"`
Samples []int64 `json:"samples"`
TimeDeltas []int64 `json:"timeDeltas"`
}
// ProfileNode represents a profile node data structure.
// The experimental fields are kept as json.RawMessage, so you may decode them with your own code, see: https://chromedevtools.github.io/debugger-protocol-viewer/tot/Profiler/
type ProfileNode struct {
ID int64 `json:"id"`
CallFrame json.RawMessage `json:"callFrame"`
HitCount int64 `json:"hitCount"`
Children []int64 `json:"children"`
DeoptReason string `json:"deoptReason"`
PositionTicks json.RawMessage `json:"positionTicks"`
}
// EvaluateError is returned by Evaluate in case of expression errors.
type EvaluateError struct {
ErrorDetails map[string]interface{}
ExceptionDetails map[string]interface{}
}
func (err EvaluateError) Error() string {
desc := err.ErrorDetails["description"].(string)
if excp := err.ExceptionDetails; excp != nil {
if excp["exception"] != nil {
desc += fmt.Sprintf(" at line %v col %v",
excp["lineNumber"].(float64), excp["columnNumber"].(float64))
}
}
return desc
}
type NavigationError string
func (err NavigationError) Error() string {
return "NavigationError:" + string(err)
}
type ConnectOption func(c *httpclient.HttpClient)
// Host set the host header
func Host(host string) ConnectOption {
return func(c *httpclient.HttpClient) {
c.Host = host
}
}
// Headers set specified HTTP headers
func Headers(headers map[string]string) ConnectOption {
return func(c *httpclient.HttpClient) {
c.Headers = headers
}
}
func (remote *RemoteDebugger) socket() (ws *websocket.Conn) {
ws = remote.wsConn
return
}
func (remote *RemoteDebugger) Verbose(v bool) {
remote.verbose = v
}
type wsMessage struct {
ID int `json:"id"`
Result json.RawMessage `json:"result"`
Method string `json:"Method"`
Params json.RawMessage `json:"Params"`
}
// SendRequest sends a request and returns the reply as a a map.
func (remote *RemoteDebugger) SendRequest(method string, params Params) (map[string]interface{}, error) {
rawReply, err := remote.sendRawReplyRequest(method, params)
if err != nil || rawReply == nil {
return nil, err
}
return unmarshal(rawReply)
}
// sendRawReplyRequest sends a request and returns the reply bytes.
func (remote *RemoteDebugger) sendRawReplyRequest(method string, params Params) ([]byte, error) {
// 加锁,避免在关闭channel之后发送命令,主要是channel操作。
remote.Lock()
defer remote.Unlock()
if remote.wsConn == nil {
return nil, ErrorClose
}
responseChan := make(chan json.RawMessage, 1)
reqID := remote.reqID
remote.responses[reqID] = responseChan
remote.reqID++
command := Params{
"id": reqID,
"method": method,
"params": params,
}
remote.requests <- command
reply := <-responseChan
delete(remote.responses, reqID)
return reply, nil
}
func (remote *RemoteDebugger) sendMessages() {
for message := range remote.requests {
ws := remote.socket()
if ws == nil { // the socket is now closed
break
}
if remote.verbose {
log.Printf("SEND %#v\n", message)
}
err := ws.WriteJSON(message)
if err != nil {
log.Println("write message:", err)
}
}
remote.wg.Done()
}
func permanentError(err error) bool {
if websocket.IsUnexpectedCloseError(err) {
log.Println("unexpected close error")
return true
}
if neterr, ok := err.(net.Error); ok && !neterr.Temporary() {
log.Println("permanent network error")
return true
}
return false
}
func (remote *RemoteDebugger) readMessages(ws *websocket.Conn) {
remoteClosed := false
loop:
for {
select {
case <-remote.closed:
remoteClosed = !remoteClosed
break loop
default:
if remote.socket() != ws { // this socket is now closed
break loop
}
var message wsMessage
err := ws.ReadJSON(&message)
if err != nil {
if remote.socket() != ws { // this socket is now closed
continue // one more check for remote.closed
}
log.Println("read message:", err)
if permanentError(err) {
break loop
}
} else if message.Method != "" {
if remote.verbose {
log.Println("EVENT", message.Method, string(message.Params), len(eventChan))
}
_, ok := callbacks.Load(message.Method)
//_, ok := callbacks[message.Method]
if !ok {
continue // don't queue unrequested events
}
select {
case eventChan <- message:
case <-remote.closed:
remoteClosed = true
break loop
}
} else {
//
// should be a method reply
//
if remote.verbose {
log.Println("REPLY", message.ID, string(message.Result))
}
ch := remote.responses[message.ID]
if ch != nil {
ch <- message.Result
}
}
}
}
// log.Println("exit readMessages", remoteClosed)
// Close Event is not needed
//if remoteClosed {
// eventChan <- wsMessage{Method: EventClosed, Params: []byte("{}")}
//
//} else if remote.socket() == ws { // we should still be connected but something is wrong
// eventChan <- wsMessage{Method: EventDisconnect, Params: []byte("{}")}
//}
remote.wg.Done()
}
// Version returns version information (protocol, browser, etc.).
func (remote *RemoteDebugger) Version() (*Version, error) {
resp, err := responseError(remote.http.Get("/json/version", nil, nil))
if err != nil {
return nil, err
}
var version Version
if err = decode(resp, &version); err != nil {
return nil, err
}
return &version, nil
}
// Protocol returns the DevTools protocol specification
func (remote *RemoteDebugger) Protocol() (map[string]interface{}, error) {
resp, err := responseError(remote.http.Get("/json/protocol", nil, nil))
if err != nil {
return nil, err
}
var proto map[string]interface{}
if err = decode(resp, &proto); err != nil {
return nil, err
}
return proto, nil
}
// TabList returns a list of opened tabs/pages.
// If filter is not empty, only tabs of the specified type are returned (i.e. "page").
//
// Note that tabs are ordered by activitiy time (most recently used first) so the
// current tab is the first one of type "page".
func (remote *RemoteDebugger) TabList(filter string) ([]*Tab, error) {
resp, err := responseError(remote.http.Get("/json/list", nil, nil))
if err != nil {
return nil, err
}
var tabs []*Tab
if err = decode(resp, &tabs); err != nil {
return nil, err
}
if filter == "" {
return tabs, nil
}
var filtered []*Tab
for _, t := range tabs {
if t.Type == filter {
filtered = append(filtered, t)
}
}
return filtered, nil
}
// ActivateTab activates the specified tab.
func (remote *RemoteDebugger) ActivateTab(tab *Tab) error {
resp, err := responseError(remote.http.Get("/json/activate/"+tab.ID, nil, nil))
resp.Close()
if err == nil {
err = remote.connectWs(tab)
}
return err
}
// CloseTab closes the specified tab.
func (remote *RemoteDebugger) CloseTab(tab *Tab) error {
resp, err := responseError(remote.http.Get("/json/close/"+tab.ID, nil, nil))
resp.Close()
return err
}
// NewTab creates a new tab.
func (remote *RemoteDebugger) NewTab(url string) (*Tab, error) {
path := "/json/new"
if url != "" {
path += "?" + url
}
resp, err := responseError(remote.http.Do(remote.http.Request("GET", path, nil, nil)))
if err != nil {
return nil, err
}
var tab Tab
if err = decode(resp, &tab); err != nil {
return nil, err
}
if err = remote.connectWs(&tab); err != nil {
return nil, err
}
return &tab, nil
}
// GetDomains lists the available DevTools domains.
//
// Deprecated: The Schema domain is now deprecated.
func (remote *RemoteDebugger) GetDomains() ([]Domain, error) {
res, err := remote.sendRawReplyRequest("Schema.getDomains", nil)
if err != nil {
return nil, err
}
var domains struct {
Domains []Domain
}
err = json.Unmarshal(res, &domains)
if err != nil {
return nil, err
}
return domains.Domains, nil
}
// Navigate navigates to the specified URL.
func (remote *RemoteDebugger) Navigate(url string) (string, error) {
res, err := remote.SendRequest("Page.navigate", Params{
"url": url,
})
if err != nil {
return "", err
}
if errorText, ok := res["errorText"]; ok {
return "", NavigationError(errorText.(string))
}
frameID, ok := res["frameId"]
if !ok {
return "", nil
}
return frameID.(string), nil
}
// Reload reloads the current page.
func (remote *RemoteDebugger) Reload() error {
_, err := remote.SendRequest("Page.reload", Params{
"ignoreCache": true,
})
return err
}
// GetNavigationHistory returns navigation history for the current page.
func (remote *RemoteDebugger) GetNavigationHistory() (int, []NavigationEntry, error) {
rawReply, err := remote.sendRawReplyRequest("Page.getNavigationHistory", nil)
if err != nil {
return 0, nil, err
}
var history struct {
Current int64 `json:"currentIndex"`
Entries []NavigationEntry `json:"entries"`
}
if err := json.Unmarshal(rawReply, &history); err != nil {
return 0, nil, err
}
return int(history.Current), history.Entries, nil
}
// SetControlNavigations toggles navigation throttling which allows programatic control over navigation and redirect response.
func (remote *RemoteDebugger) SetControlNavigations(enabled bool) error {
_, err := remote.SendRequest("Page.setControlNavigations", Params{
"enabled": enabled,
})
return err
}
// ProcessNavigation should be sent in response to a navigationRequested or a redirectRequested event, telling the browser how to handle the navigation.
func (remote *RemoteDebugger) ProcessNavigation(navigationID int, navigation NavigationResponse) error {
_, err := remote.SendRequest("Page.processNavigation", Params{
"response": navigation,
"navigationId": navigationID,
})
return err
}
// CaptureScreenshot takes a screenshot, uses "png" as default format.
func (remote *RemoteDebugger) CaptureScreenshot(format string, quality int, fromSurface bool) ([]byte, error) {
if format == "" {
format = "png"
}
res, err := remote.SendRequest("Page.captureScreenshot", Params{
"format": format,
"quality": quality,
"fromSurface": fromSurface,
})
if err != nil {
return nil, err
}
if res == nil {
return nil, ErrorNoResponse
}
return base64.StdEncoding.DecodeString(res["data"].(string))
}
// SaveScreenshot takes a screenshot and saves it to a file.
func (remote *RemoteDebugger) SaveScreenshot(filename string, perm os.FileMode, quality int, fromSurface bool) error {
var format string
ext := filepath.Ext(filename)
switch ext {
case ".jpg":
format = "jpeg"
case ".png":
format = "png"
default:
return errors.New("Image format not supported")
}
rawScreenshot, err := remote.CaptureScreenshot(format, quality, fromSurface)
if err != nil {
return err
}
return ioutil.WriteFile(filename, rawScreenshot, perm)
}
// PrintToPDFOption defines the functional option for PrintToPDF
type PrintToPDFOption func(map[string]interface{})
// LandscapeMode instructs PrintToPDF to print pages in landscape mode
func LandscapeMode() PrintToPDFOption {
return func(o map[string]interface{}) {
o["landscape"] = true
}
}
// PortraitMode instructs PrintToPDF to print pages in portrait mode
func PortraitMode() PrintToPDFOption {
return func(o map[string]interface{}) {
o["landscape"] = false
}
}
// DisplayHeaderFooter instructs PrintToPDF to print headers/footers or not
func DisplayHeaderFooter() PrintToPDFOption {
return func(o map[string]interface{}) {
o["displayHeaderFooter"] = true
}
}
// printBackground instructs PrintToPDF to print background graphics
func PrintBackground() PrintToPDFOption {
return func(o map[string]interface{}) {
o["printBackground"] = true
}
}
// Scale instructs PrintToPDF to scale the pages (1.0 is current scale)
func Scale(n float64) PrintToPDFOption {
return func(o map[string]interface{}) {
o["scale"] = n
}
}
// Dimensions sets the current page dimensions for PrintToPDF
func Dimensions(width, height float64) PrintToPDFOption {
return func(o map[string]interface{}) {
o["paperWidth"] = width
o["paperHeight"] = height
}
}
// Margins sets the margin sizes for PrintToPDF
func Margins(top, bottom, left, right float64) PrintToPDFOption {
return func(o map[string]interface{}) {
o["marginTop"] = top
o["marginBottom"] = bottom
o["marginLeft"] = left
o["marginRight"] = right
}
}
// PageRanges instructs PrintToPDF to print only the specified range of pages
func PageRanges(ranges string) PrintToPDFOption {
return func(o map[string]interface{}) {
o["pageRanges"] = ranges
}
}
// PrintToPDF print the current page as PDF.
func (remote *RemoteDebugger) PrintToPDF(options ...PrintToPDFOption) ([]byte, error) {
mOptions := map[string]interface{}{}
for _, o := range options {
o(mOptions)
}
res, err := remote.SendRequest("Page.printToPDF", mOptions)
if err != nil {
return nil, err
}
if res == nil {
return nil, ErrorNoResponse
}
return base64.StdEncoding.DecodeString(res["data"].(string))
}
// SavePDF print current page as PDF and save to file
func (remote *RemoteDebugger) SavePDF(filename string, perm os.FileMode, options ...PrintToPDFOption) error {
rawPDF, err := remote.PrintToPDF(options...)
if err != nil {
return err
}
return ioutil.WriteFile(filename, rawPDF, perm)
}
// HandleJavaScriptDialog accepts or dismisses a Javascript initiated dialog.
func (remote *RemoteDebugger) HandleJavaScriptDialog(accept bool, promptText string) error {
_, err := remote.SendRequest("Page.handleJavaScriptDialog", Params{
"accept": accept,
"promptText": promptText,
})
return err
}
// SetDownloadBehaviour enable/disable downloads.
func (remote *RemoteDebugger) SetDownloadBehavior(behavior DownloadBehavior, downloadPath string) error {
params := Params{"behavior": behavior}
if len(downloadPath) > 0 {
params["downloadPath"] = downloadPath
}
_, err := remote.SendRequest("Page.setDownloadBehavior", params)
return err
}
// GetResponseBody returns the response body of a given requestId (from the Network.responseReceived payload).
func (remote *RemoteDebugger) GetResponseBody(req string) ([]byte, error) {
res, err := remote.SendRequest("Network.getResponseBody", Params{
"requestId": req,
})
if err != nil {
return nil, err
}
body := res["body"]
if body == nil {
return nil, nil
}
if b, ok := res["base64Encoded"]; ok && b.(bool) {
return base64.StdEncoding.DecodeString(body.(string))
} else {
return []byte(body.(string)), nil
}
}
func (remote *RemoteDebugger) GetResponseBodyForInterception(iid string) ([]byte, error) {
res, err := remote.SendRequest("Network.getResponseBodyForInterception", Params{
"interceptionId": iid,
})
if err != nil {
return nil, err
} else if b, ok := res["base64Encoded"]; ok && b.(bool) {
return base64.StdEncoding.DecodeString(res["body"].(string))
} else {
return []byte(res["body"].(string)), nil
}
}
type Cookie struct {
Name string `json:"name"`
Value string `json:"value"`
Domain string `json:"domain"`
Path string `json:"path"`
Size int `json:"size"`
Expires float64 `json:"expires"`
HttpOnly bool `json:"httpOnly"`
Secure bool `json:"secure"`
Session bool `json:"session"`
SameSite string `json:"sameSite"`
}
// GetCookies returns all browser cookies for the current URL.
// Depending on the backend support, will return detailed cookie information in the `cookies` field.
func (remote *RemoteDebugger) GetCookies(urls []string) ([]Cookie, error) {
params := Params{}
if urls != nil {
params["urls"] = urls
}
rawReply, err := remote.sendRawReplyRequest("Network.getCookies", params)
if err != nil {
return nil, err
}
var cookies struct {
Cookies []Cookie `json:"cookies"`
}
err = json.Unmarshal(rawReply, &cookies)
if err != nil {
log.Println("unmarshal:", err)
log.Println(string(rawReply))
return nil, err
}
return cookies.Cookies, nil
}
// GetAllCookies returns all browser cookies. Depending on the backend support,
// will return detailed cookie information in the `cookies` field.
func (remote *RemoteDebugger) GetAllCookies() ([]Cookie, error) {
rawReply, err := remote.sendRawReplyRequest("Network.getCookies", nil)
if err != nil {
return nil, err
}
var cookies struct {
Cookies []Cookie `json:"cookies"`
}
err = json.Unmarshal(rawReply, &cookies)
if err != nil {
log.Println("unmarshal:", err)
log.Println(string(rawReply))
return nil, err
}
return cookies.Cookies, nil
}
// Set browser cookies.
func (remote *RemoteDebugger) SetCookies(cookies []Cookie) error {
params := Params{}
params["cookies"] = cookies
_, err := remote.SendRequest("Network.setCookies", params)
return err
}
// Deletes browser cookies with matching name and url or domain/path pair.
//
// Parameters:
//
// name string: Name of the cookies to remove.
// url string: If specified, deletes all the cookies with the given name where domain and path match provided URL.
// domain string: If specified, deletes only cookies with the exact domain.
// path string: If specified, deletes only cookies with the exact path.
func (remote *RemoteDebugger) DeleteCookies(name, url, domain, path string) error {
params := Params{}
params["name"] = name
if url != "" {
params["url"] = url
}
if domain != "" {
params["domain"] = domain
}
if path != "" {
params["path"] = path
}
_, err := remote.SendRequest("Network.deleteCookies", params)
return err
}
//Set browser cookie
func (remote *RemoteDebugger) SetCookie(cookie Cookie) bool {
params := Params{}
params["name"] = cookie.Name
params["value"] = cookie.Value
if cookie.Domain != "" {
params["domain"] = cookie.Domain
}
if cookie.Path != "" {
params["path"] = cookie.Path
}
if cookie.Secure {
params["secure"] = cookie.Secure
}
if cookie.HttpOnly {
params["httpOnly"] = cookie.HttpOnly
}
if cookie.SameSite != "" {
params["sameSite"] = cookie.SameSite
}
if cookie.Expires > 0 {
params["expires"] = cookie.Expires
}
_, err := remote.SendRequest("Network.setCookies", params)
if err != nil {
return false
}
return true
}
type ResourceType string
const (
ResourceTypeDocument = ResourceType("Document")
ResourceTypeStylesheet = ResourceType("Stylesheet")
ResourceTypeImage = ResourceType("Image")
ResourceTypeMedia = ResourceType("Media")
ResourceTypeFont = ResourceType("Font")
ResourceTypeScript = ResourceType("Script")
ResourceTypeTextTrack = ResourceType("TextTrack")
ResourceTypeXHR = ResourceType("XHR")
ResourceTypeFetch = ResourceType("Fetch")
ResourceTypeEventSource = ResourceType("EventSource")
ResourceTypeWebSocket = ResourceType("WebSocket")
ResourceTypeManifest = ResourceType("Manifest")
ResourceTypeSignedExchange = ResourceType("SignedExchange")
ResourceTypePing = ResourceType("Ping")
ResourceTypeCSPViolationReport = ResourceType("CSPViolationReport")
ResourceTypeOther = ResourceType("Other")
)
type InterceptionStage string
type RequestStage string
const (
StageRequest = InterceptionStage("Request")
StageHeadersReceived = InterceptionStage("HeadersReceived")
RequestStageRequest = RequestStage("Request")
RequestStageResponse = RequestStage("Response")
)
type RequestPattern struct {
UrlPattern string `json:"urlPattern,omitempty"`
ResourceType ResourceType `json:"resourceType,omitempty"`
InterceptionStage InterceptionStage `json:"interceptionStage,omitempty"`
}
type FetchRequestPattern struct {
UrlPattern string `json:"urlPattern,omitempty"`
ResourceType ResourceType `json:"resourceType,omitempty"`
RequestStage RequestStage `json:"requestStage,omitempty"`
}
// SetRequestInterception sets the requests to intercept that match the provided patterns
// and optionally resource types.
//
// Deprecated: use EnableRequestPaused instead.
func (remote *RemoteDebugger) SetRequestInterception(patterns ...RequestPattern) error {
_, err := remote.SendRequest("Network.setRequestInterception", Params{
"patterns": patterns,
})
return err
}
// EnableRequestInterception enables interception, modification or cancellation of network requests
func (remote *RemoteDebugger) EnableRequestInterception(enabled bool) error {
if enabled {
return remote.SetRequestInterception(RequestPattern{UrlPattern: "*"})
} else {
return remote.SetRequestInterception()
}
}
// ContinueInterceptedRequest is the response to Network.requestIntercepted
// which either modifies the request to continue with any modifications, or blocks it,
// or completes it with the provided response bytes.
//
// If a network fetch occurs as a result which encounters a redirect an additional Network.requestIntercepted
// event will be sent with the same InterceptionId.
//
// Parameters:
// errorReason ErrorReason - if set this causes the request to fail with the given reason.
// rawResponse string - if set the requests completes using with the provided base64 encoded raw response, including HTTP status line and headers etc...
// url string - if set the request url will be modified in a way that's not observable by page.
// method string - if set this allows the request method to be overridden.
// postData string - if set this allows postData to be set.
// headers Headers - if set this allows the request headers to be changed.
//
// Deprecated: use ContinueRequest, FulfillRequest and FailRequest instead.
func (remote *RemoteDebugger) ContinueInterceptedRequest(interceptionID string,
errorReason ErrorReason,
rawResponse string,
url string,
method string,
postData string,
headers map[string]string) error {
params := Params{
"interceptionId": interceptionID,
}
if errorReason != "" {
params["errorReason"] = string(errorReason)
}
if rawResponse != "" {
params["rawResponse"] = rawResponse
}
if url != "" {
params["url"] = url
}
if method != "" {
params["method"] = method
}
if postData != "" {
params["postData"] = postData
}
if headers != nil {