forked from metafates/mangal-lua-libs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
browser.go
82 lines (64 loc) · 1.42 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
package headless
import (
"os"
"path/filepath"
"github.com/go-rod/rod"
lua "github.com/yuin/gopher-lua"
)
var browserMethods = map[string]lua.LGFunction{
"page": browserPage,
"close": browserClose,
}
func newBrowser() lua.LGFunction {
return func(L *lua.LState) int {
temp := os.TempDir()
os.RemoveAll(filepath.Join(temp, "rod"))
browser := rod.New()
err := browser.Connect()
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
ud := L.NewUserData()
ud.Value = browser
L.SetMetatable(ud, L.GetTypeMetatable("browser"))
L.Push(ud)
L.Push(lua.LNil)
return 2
}
}
func registerBrowserType(L *lua.LState) {
mt := L.NewTypeMetatable("browser")
L.SetField(mt, "__index", L.SetFuncs(L.NewTable(), browserMethods))
}
func checkBrowser(L *lua.LState) *rod.Browser {
ud := L.CheckUserData(1)
if v, ok := ud.Value.(*rod.Browser); ok {
return v
}
L.ArgError(1, "browser expected")
return nil
}
func browserPage(L *lua.LState) int {
browser := checkBrowser(L)
url := L.ToString(2)
p := browser.MustPage(url)
ud := L.NewUserData()
ud.Value = p
L.SetMetatable(ud, L.GetTypeMetatable("browserPage"))
L.Push(ud)
return 1
}
func browserClose(L *lua.LState) int {
browser := checkBrowser(L)
err := browser.Close()
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
// L.Push(lua.LNil)
L.Push(lua.LString("browser closed"))
return 1
}