forked from mafredri/cdp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheadless.go
56 lines (46 loc) · 1.42 KB
/
headless.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
package devtool
import (
"context"
"errors"
"regexp"
"github.com/mafredri/cdp"
"github.com/mafredri/cdp/protocol/target"
"github.com/mafredri/cdp/rpcc"
)
var httpRe = regexp.MustCompile("^https?://")
// fallbackHeadlessCreateURL tries to create a new target for Headless Chrome
// that does not support the json new endpoint. A rpcc connection is established
// to the "/devtools/browser" endpoint and "Target.createTarget" is issued.
func fallbackHeadlessCreateURL(ctx context.Context, d *DevTools, openURL string) (*Target, error) {
// Context must be set, rpcc DialContext panics on nil context.
if ctx == nil {
ctx = context.Background()
}
// Headless Chrome requires a non-empty URL for CreateTarget.
if openURL == "" {
openURL = "about:blank"
}
wsURL := "ws://" + httpRe.ReplaceAllString(d.url, "") + "/devtools/browser"
conn, err := rpcc.DialContext(ctx, wsURL)
if err != nil {
return nil, err
}
defer conn.Close()
c := cdp.NewClient(conn)
t, err := c.Target.CreateTarget(ctx, target.NewCreateTargetArgs(openURL))
if err != nil {
return nil, err
}
// List must be called after CreateTarget (headless bug):
// https://bugs.chromium.org/p/chromium/issues/detail?id=704503
list, err := d.List(ctx)
if err != nil {
return nil, err
}
for _, tt := range list {
if tt.ID == string(t.TargetID) {
return tt, nil
}
}
return nil, errors.New("devtool: headlessCreateURL: could not create target")
}