-
Notifications
You must be signed in to change notification settings - Fork 45
/
example_advanced_test.go
270 lines (233 loc) · 6.51 KB
/
example_advanced_test.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
package cdp_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/mafredri/cdp"
"github.com/mafredri/cdp/devtool"
"github.com/mafredri/cdp/protocol/dom"
"github.com/mafredri/cdp/protocol/network"
"github.com/mafredri/cdp/protocol/page"
"github.com/mafredri/cdp/protocol/runtime"
"github.com/mafredri/cdp/rpcc"
"golang.org/x/sync/errgroup"
)
// Cookie represents a browser cookie.
type Cookie struct {
URL string `json:"url"`
Name string `json:"name"`
Value string `json:"value"`
}
// DocumentInfo contains information about the document.
type DocumentInfo struct {
Title string `json:"title"`
}
var (
MyURL = "https://google.com"
Cookies = []Cookie{
{MyURL, "myauth", "myvalue"},
{MyURL, "mysetting1", "myvalue1"},
{MyURL, "mysetting2", "myvalue2"},
{MyURL, "mysetting3", "myvalue3"},
}
)
func Example_advanced() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
devt := devtool.New("http://localhost:9222")
pt, err := devt.Get(ctx, devtool.Page)
if err != nil {
return
}
// Connect to WebSocket URL (page) that speaks the Chrome DevTools Protocol.
conn, err := rpcc.DialContext(ctx, pt.WebSocketDebuggerURL)
if err != nil {
fmt.Println(err)
return
}
defer conn.Close() // Cleanup.
// Create a new CDP Client that uses conn.
c := cdp.NewClient(conn)
// Give enough capacity to avoid blocking any event listeners
abort := make(chan error, 2)
// Watch the abort channel.
go func() {
select {
case <-ctx.Done():
case err := <-abort:
fmt.Printf("aborted: %s\n", err.Error())
cancel()
}
}()
// Setup event handlers early because domain events can be sent as
// soon as Enable is called on the domain.
if err = abortOnErrors(ctx, c, abort); err != nil {
fmt.Println(err)
return
}
if err = runBatch(
// Enable all the domain events that we're interested in.
func() error { return c.DOM.Enable(ctx, nil) },
func() error { return c.Network.Enable(ctx, nil) },
func() error { return c.Page.Enable(ctx) },
func() error { return c.Runtime.Enable(ctx) },
func() error { return setCookies(ctx, c.Network, Cookies...) },
); err != nil {
fmt.Println(err)
return
}
domLoadTimeout := 5 * time.Second
err = navigate(ctx, c.Page, MyURL, domLoadTimeout)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Navigated to: %s\n", MyURL)
// Parse information from the document by evaluating JavaScript.
expression := `
new Promise((resolve, reject) => {
setTimeout(() => {
const title = document.querySelector('title').innerText;
resolve({title});
}, 500);
});
`
evalArgs := runtime.NewEvaluateArgs(expression).SetAwaitPromise(true).SetReturnByValue(true)
eval, err := c.Runtime.Evaluate(ctx, evalArgs)
if err != nil {
fmt.Println(err)
return
}
var info DocumentInfo
if err = json.Unmarshal(eval.Result.Value, &info); err != nil {
fmt.Println(err)
return
}
fmt.Printf("Document title: %q\n", info.Title)
// Fetch the document root node.
doc, err := c.DOM.GetDocument(ctx, nil)
if err != nil {
fmt.Println(err)
return
}
// Fetch all <script> and <noscript> elements so we can delete them.
scriptIDs, err := c.DOM.QuerySelectorAll(ctx, dom.NewQuerySelectorAllArgs(doc.Root.NodeID, "script, noscript"))
if err != nil {
fmt.Println(err)
return
}
if err = removeNodes(ctx, c.DOM, scriptIDs.NodeIDs...); err != nil {
fmt.Println(err)
return
}
}
func abortOnErrors(ctx context.Context, c *cdp.Client, abort chan<- error) error {
exceptionThrown, err := c.Runtime.ExceptionThrown(ctx)
if err != nil {
return err
}
loadingFailed, err := c.Network.LoadingFailed(ctx)
if err != nil {
return err
}
go func() {
defer exceptionThrown.Close() // Cleanup.
defer loadingFailed.Close()
for {
select {
// Check for exceptions so we can abort as soon
// as one is encountered.
case <-exceptionThrown.Ready():
ev, err := exceptionThrown.Recv()
if err != nil {
// This could be any one of: stream closed,
// connection closed, context deadline or
// unmarshal failed.
abort <- err
return
}
// Ruh-roh! Let the caller know something went wrong.
abort <- ev.ExceptionDetails
// Check for non-canceled resources that failed
// to load.
case <-loadingFailed.Ready():
ev, err := loadingFailed.Recv()
if err != nil {
abort <- err
return
}
// For now, most optional fields are pointers
// and must be checked for nil.
canceled := ev.Canceled != nil && *ev.Canceled
if !canceled {
abort <- fmt.Errorf("request %s failed: %s", ev.RequestID, ev.ErrorText)
}
}
}
}()
return nil
}
// setCookies sets all the provided cookies.
func setCookies(ctx context.Context, net cdp.Network, cookies ...Cookie) error {
var cmds []runBatchFunc
for _, c := range cookies {
args := network.NewSetCookieArgs(c.Name, c.Value).SetURL(c.URL)
cmds = append(cmds, func() error {
reply, err := net.SetCookie(ctx, args)
if err != nil {
return err
}
if !reply.Success {
return errors.New("could not set cookie")
}
return nil
})
}
return runBatch(cmds...)
}
// navigate to the URL and wait for DOMContentEventFired. An error is
// returned if timeout happens before DOMContentEventFired.
func navigate(ctx context.Context, pageClient cdp.Page, url string, timeout time.Duration) error {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
// Make sure Page events are enabled.
err := pageClient.Enable(ctx)
if err != nil {
return err
}
// Open client for DOMContentEventFired to block until DOM has fully loaded.
domContentEventFired, err := pageClient.DOMContentEventFired(ctx)
if err != nil {
return err
}
defer domContentEventFired.Close()
_, err = pageClient.Navigate(ctx, page.NewNavigateArgs(url))
if err != nil {
return err
}
_, err = domContentEventFired.Recv()
return err
}
// removeNodes deletes all provided nodeIDs from the DOM.
func removeNodes(ctx context.Context, domClient cdp.DOM, nodes ...dom.NodeID) error {
var rmNodes []runBatchFunc
for _, id := range nodes {
arg := dom.NewRemoveNodeArgs(id)
rmNodes = append(rmNodes, func() error { return domClient.RemoveNode(ctx, arg) })
}
return runBatch(rmNodes...)
}
// runBatchFunc is the function signature for runBatch.
type runBatchFunc func() error
// runBatch runs all functions simultaneously and waits until
// execution has completed or an error is encountered.
func runBatch(fn ...runBatchFunc) error {
eg := errgroup.Group{}
for _, f := range fn {
eg.Go(f)
}
return eg.Wait()
}