-
Notifications
You must be signed in to change notification settings - Fork 45
/
example_dial_test.go
72 lines (63 loc) · 1.8 KB
/
example_dial_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
package cdp_test
import (
"context"
"fmt"
"io"
"log"
"github.com/coder/websocket"
"github.com/mafredri/cdp"
"github.com/mafredri/cdp/devtool"
"github.com/mafredri/cdp/protocol/runtime"
"github.com/mafredri/cdp/rpcc"
)
func Example_dial_using_alternative_websocket_implementation() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
devt := devtool.New("http://localhost:9222")
page, err := devt.CreateURL(ctx, "about:blank")
if err != nil {
log.Println(err)
}
// Dial using an alternative websocket implementation.
//
// Note that this disables functionality like:
//
// - Safety measure against writing fragmented websocket messages
// - Setting compression level after dial
dialer := rpcc.WithDialer(func(dialCtx context.Context, addr string) (io.ReadWriteCloser, error) {
log.Println(addr)
conn, _, err := websocket.Dial(dialCtx, addr, &websocket.DialOptions{
CompressionMode: websocket.CompressionContextTakeover,
})
if err != nil {
return nil, err
}
// Note that we cannot use dialCtx here since websocket.NetConn
// binds to the lifetime of ctx.
return websocket.NetConn(ctx, conn, websocket.MessageText), nil
})
conn, err := rpcc.Dial(page.WebSocketDebuggerURL, dialer)
if err != nil {
log.Println(err)
}
defer conn.Close()
// Use the connection that uses nhooyr.io/websocket underneath.
c := cdp.NewClient(conn)
if err = c.Runtime.Enable(ctx); err != nil {
log.Println(err)
}
eval, err := c.Runtime.Evaluate(ctx, runtime.NewEvaluateArgs(`document.location.href`).SetReturnByValue(true))
if err == nil && eval.ExceptionDetails != nil {
err = eval.ExceptionDetails
}
if err != nil {
log.Println(err)
}
fmt.Println(eval.Result.String())
err = devt.Close(ctx, page)
if err != nil {
log.Println(err)
}
// Output:
// "about:blank"
}