-
-
Notifications
You must be signed in to change notification settings - Fork 328
/
page_eval.go
305 lines (251 loc) · 7.41 KB
/
page_eval.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
// This file serves for the Page.Evaluate.
package rod
import (
"errors"
"fmt"
"time"
"github.com/go-rod/rod/lib/cdp"
"github.com/go-rod/rod/lib/js"
"github.com/go-rod/rod/lib/proto"
"github.com/go-rod/rod/lib/utils"
"github.com/ysmood/gson"
)
// EvalOptions for Page.Evaluate
type EvalOptions struct {
// If enabled the eval result will be a plain JSON value.
// If disabled the eval result will be a reference of a remote js object.
ByValue bool
AwaitPromise bool
// ThisObj represents the "this" object in the JS
ThisObj *proto.RuntimeRemoteObject
// JS code to eval
JS string
// JSArgs represents the arguments in the JS if the JS is a function definition.
// If an argument is *proto.RuntimeRemoteObject type, the corresponding remote object will be used.
// Or it will be passed as a plain JSON value.
JSArgs []interface{}
// Whether execution should be treated as initiated by user in the UI.
UserGesture bool
jsHelper *js.Function
}
// Eval creates a EvalOptions with ByValue set to true.
func Eval(js string, args ...interface{}) *EvalOptions {
return &EvalOptions{true, false, nil, js, args, false, nil}
}
// Convert name and jsArgs to Page.Eval, the name is method name in the "lib/js/helper.js".
func jsHelper(fn *js.Function, args ...interface{}) *EvalOptions {
return &EvalOptions{
ByValue: true,
JSArgs: args,
JS: `({fn}, ...args) => fn.apply(this, args)`,
jsHelper: fn,
}
}
// This set the obj as ThisObj
func (e *EvalOptions) This(obj *proto.RuntimeRemoteObject) *EvalOptions {
e.ThisObj = obj
return e
}
// ByObject disables ByValue.
func (e *EvalOptions) ByObject() *EvalOptions {
e.ByValue = false
return e
}
// ByUser enables UserGesture.
func (e *EvalOptions) ByUser() *EvalOptions {
e.UserGesture = true
return e
}
// ByPromise enables AwaitPromise.
func (e *EvalOptions) ByPromise() *EvalOptions {
e.AwaitPromise = true
return e
}
// Strings appends each string to JSArgs
func (e *EvalOptions) Strings(list ...string) *EvalOptions {
for _, s := range list {
e.JSArgs = append(e.JSArgs, s)
}
return e
}
func (e *EvalOptions) formatToJSFunc() string {
if detectJSFunction(e.JS) {
return fmt.Sprintf(`function() { return (%s).apply(this, arguments) }`, e.JS)
}
return fmt.Sprintf(`function() { return %s }`, e.JS)
}
// Eval is just a shortcut for Page.Evaluate
func (p *Page) Eval(js string, jsArgs ...interface{}) (*proto.RuntimeRemoteObject, error) {
return p.Evaluate(Eval(js, jsArgs...).ByPromise())
}
// Evaluate js on the page.
func (p *Page) Evaluate(opts *EvalOptions) (res *proto.RuntimeRemoteObject, err error) {
var backoff utils.Sleeper
// js context will be invalid if a frame is reloaded or not ready, then the isNilContextErr
// will be true, then we retry the eval again.
for {
res, err = p.evaluate(opts)
if err != nil && errors.Is(err, cdp.ErrCtxNotFound) {
if opts.ThisObj != nil {
return nil, &ErrObjectNotFound{opts.ThisObj}
}
if backoff == nil {
backoff = utils.BackoffSleeper(30*time.Millisecond, 3*time.Second, nil)
} else {
_ = backoff(p.ctx)
}
err := p.updateJSCtxID()
if err != nil {
return nil, err
}
continue
}
return
}
}
func (p *Page) evaluate(opts *EvalOptions) (*proto.RuntimeRemoteObject, error) {
args, err := p.formatArgs(opts)
if err != nil {
return nil, err
}
req := proto.RuntimeCallFunctionOn{
AwaitPromise: opts.AwaitPromise,
ReturnByValue: opts.ByValue,
UserGesture: opts.UserGesture,
FunctionDeclaration: opts.formatToJSFunc(),
Arguments: args,
}
if opts.ThisObj == nil {
req.ExecutionContextID = p.getJSCtxID()
} else {
req.ObjectID = opts.ThisObj.ObjectID
}
res, err := req.Call(p)
if err != nil {
return nil, err
}
if res.ExceptionDetails != nil {
return nil, &ErrEval{res.ExceptionDetails}
}
return res.Result, nil
}
func (p *Page) initSession() error {
session, err := proto.TargetAttachToTarget{
TargetID: p.TargetID,
Flatten: true, // if it's not set no response will return
}.Call(p)
if err != nil {
return err
}
p.SessionID = session.SessionID
// If we don't enable it, it will cause a lot of unexpected browser behavior.
// Such as proto.PageAddScriptToEvaluateOnNewDocument won't work.
p.EnableDomain(&proto.PageEnable{})
// If we don't enable it, it will remove remote node id whenever we disable the domain
// even after we re-enable it again we can't query the ids any more.
p.EnableDomain(&proto.DOMEnable{})
p.FrameID = proto.PageFrameID(p.TargetID)
return p.updateJSCtxID()
}
func (p *Page) formatArgs(opts *EvalOptions) ([]*proto.RuntimeCallArgument, error) {
formated := []*proto.RuntimeCallArgument{}
for _, arg := range opts.JSArgs {
if obj, ok := arg.(*proto.RuntimeRemoteObject); ok { // remote object
formated = append(formated, &proto.RuntimeCallArgument{ObjectID: obj.ObjectID})
} else { // plain json data
formated = append(formated, &proto.RuntimeCallArgument{Value: gson.New(arg)})
}
}
if opts.jsHelper != nil {
p.jsCtxLock.Lock()
id, err := p.ensureJSHelper(opts.jsHelper)
p.jsCtxLock.Unlock()
if err != nil {
return nil, err
}
formated = append([]*proto.RuntimeCallArgument{{ObjectID: id}}, formated...)
}
return formated, nil
}
func (p *Page) ensureJSHelper(fn *js.Function) (proto.RuntimeRemoteObjectID, error) {
if p.helpers == nil {
p.helpers = map[proto.RuntimeExecutionContextID]map[string]proto.RuntimeRemoteObjectID{}
}
list, ok := p.helpers[*p.jsCtxID]
if !ok {
list = map[string]proto.RuntimeRemoteObjectID{}
p.helpers[*p.jsCtxID] = list
}
fns, has := list[js.Functions.Name]
if !has {
res, err := proto.RuntimeCallFunctionOn{
ExecutionContextID: *p.jsCtxID,
FunctionDeclaration: js.Functions.Definition,
}.Call(p)
if err != nil {
return "", err
}
fns = res.Result.ObjectID
list[js.Functions.Name] = fns
}
id, has := list[fn.Name]
if !has {
for _, dep := range fn.Dependencies {
_, err := p.ensureJSHelper(dep)
if err != nil {
return "", err
}
}
res, err := proto.RuntimeCallFunctionOn{
ExecutionContextID: *p.jsCtxID,
Arguments: []*proto.RuntimeCallArgument{{ObjectID: fns}},
FunctionDeclaration: fmt.Sprintf(
// We wrap an extra {fn: fn} here to reduce the response body size,
// we only need the object id, but the cdp will return the whole function string.
"functions => { functions.%s = %s; return { fn: functions.%s } }",
fn.Name, fn.Definition, fn.Name,
),
}.Call(p)
if err != nil {
return "", err
}
id = res.Result.ObjectID
list[fn.Name] = id
}
return id, nil
}
func (p *Page) getJSCtxID() proto.RuntimeExecutionContextID {
p.jsCtxLock.Lock()
defer p.jsCtxLock.Unlock()
return *p.jsCtxID
}
func (p *Page) updateJSCtxID() error {
if !p.IsIframe() {
obj, err := proto.RuntimeEvaluate{Expression: "window"}.Call(p)
if err != nil {
return err
}
p.jsCtxLock.Lock()
*p.jsCtxID = obj.Result.ObjectID.ExecutionID()
p.helpers = nil
p.jsCtxLock.Unlock()
return nil
}
owner, err := proto.DOMGetFrameOwner{FrameID: p.FrameID}.Call(p)
if err != nil {
return err
}
node, err := proto.DOMDescribeNode{BackendNodeID: owner.BackendNodeID, Pierce: true}.Call(p)
if err != nil {
return err
}
obj, err := proto.DOMResolveNode{BackendNodeID: node.Node.ContentDocument.BackendNodeID}.Call(p)
if err != nil {
return err
}
p.jsCtxLock.Lock()
delete(p.helpers, *p.jsCtxID)
*p.jsCtxID = obj.Object.ObjectID.ExecutionID()
p.jsCtxLock.Unlock()
return nil
}