-
Notifications
You must be signed in to change notification settings - Fork 1
/
browser.go
87 lines (73 loc) · 2.04 KB
/
browser.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
package util
import (
"os"
"path/filepath"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/launcher"
"github.com/go-rod/rod/lib/proto"
)
// NewBrowser initiates the automated browser to use.
func NewBrowser(headless bool, userDataDir, bin, cacheDir string) (*rod.Browser, error) {
// Launch browser.
launchBrowser := func(controlURL string) (*rod.Browser, error) {
b := rod.New().ControlURL(controlURL).NoDefaultDevice()
if err := b.Connect(); err != nil {
return nil, err
}
return b, nil
}
// Store data in cache (to reduce time).
cacheUserDataDir := filepath.Join(cacheDir, bin)
// Initiate the browser to use.
l := launcher.New().
UserDataDir(cacheUserDataDir).
Headless(headless).
Bin(bin)
controlURL, err := l.Launch()
if err != nil {
return nil, err
}
Browser, err := launchBrowser(controlURL)
if err != nil {
return nil, err
}
// Load temporary browser to extract cookies only if path exists.
if file, err := os.Stat(userDataDir); userDataDir != "" && err == nil && file.IsDir() {
// Initiate browser to extract cookies from.
cookiesl := launcher.NewUserMode().
UserDataDir(userDataDir).
Headless(true).
Bin(bin)
cookiesControlURL, err := cookiesl.Launch()
if err != nil {
return nil, err
}
cookiesBrowser, err := launchBrowser(cookiesControlURL)
if err != nil {
return nil, err
}
defer cookiesBrowser.Close()
// Copy cookies of user.
Browser.MustSetCookies(cookiesBrowser.MustGetCookies()...)
}
return Browser, nil
}
// NewPage loads the given link in a new browser tab.
func NewPage(browser *rod.Browser, link string, block []proto.NetworkResourceType) (*rod.Page, error) {
page, err := browser.Page(proto.TargetCreateTarget{URL: link})
if err != nil {
return nil, err
}
router := page.HijackRequests()
router.MustAdd("*", func(h *rod.Hijack) {
for _, b := range block {
if h.Request.Type() == b {
h.Response.Fail(proto.NetworkErrorReasonBlockedByClient)
return
}
}
h.ContinueRequest(&proto.FetchContinueRequest{})
})
go router.Run()
return page, nil
}