vendor/github.com/go-rod/rod/page_eval.go

380 lines · 9389 bytes

  1// This file serves for the Page.Evaluate.
  2
  3package rod
  4
  5import (
  6	"errors"
  7	"fmt"
  8	"strings"
  9	"time"
 10
 11	"github.com/go-rod/rod/lib/cdp"
 12	"github.com/go-rod/rod/lib/js"
 13	"github.com/go-rod/rod/lib/proto"
 14	"github.com/go-rod/rod/lib/utils"
 15	"github.com/ysmood/gson"
 16)
 17
 18// EvalOptions for Page.Evaluate.
 19type EvalOptions struct {
 20	// If enabled the eval result will be a plain JSON value.
 21	// If disabled the eval result will be a reference of a remote js object.
 22	ByValue bool
 23
 24	AwaitPromise bool
 25
 26	// ThisObj represents the "this" object in the JS
 27	ThisObj *proto.RuntimeRemoteObject
 28
 29	// JS function definition to execute.
 30	JS string
 31
 32	// JSArgs represents the arguments that will be passed to JS.
 33	// If an argument is [*proto.RuntimeRemoteObject] type, the corresponding remote object will be used.
 34	// Or it will be passed as a plain JSON value.
 35	// When an arg in the args is a *js.Function, the arg will be cached on the page's js context.
 36	// When the arg.Name exists in the page's cache, it reuse the cache without sending
 37	// the definition to the browser again.
 38	// Useful when you need to eval a huge js expression many times.
 39	JSArgs []interface{}
 40
 41	// Whether execution should be treated as initiated by user in the UI.
 42	UserGesture bool
 43}
 44
 45// Eval creates a [EvalOptions] with ByValue set to true.
 46func Eval(js string, args ...interface{}) *EvalOptions {
 47	return &EvalOptions{
 48		ByValue:      true,
 49		AwaitPromise: false,
 50		ThisObj:      nil,
 51		JS:           js,
 52		JSArgs:       args,
 53		UserGesture:  false,
 54	}
 55}
 56
 57func evalHelper(fn *js.Function, args ...interface{}) *EvalOptions {
 58	return &EvalOptions{
 59		ByValue: true,
 60		JSArgs:  append([]interface{}{fn}, args...),
 61		JS:      fmt.Sprintf(`function (f /* %s */, ...args) { return f.apply(this, args) }`, fn.Name),
 62	}
 63}
 64
 65// String interface.
 66func (e *EvalOptions) String() string {
 67	fn := e.JS
 68	args := e.JSArgs
 69
 70	paramsStr := ""
 71	thisStr := ""
 72
 73	if e.ThisObj != nil {
 74		thisStr = e.ThisObj.Description
 75	}
 76	if len(args) > 0 {
 77		if f, ok := args[0].(*js.Function); ok {
 78			fn = "rod." + f.Name
 79			args = e.JSArgs[1:]
 80		}
 81
 82		paramsStr = strings.Trim(mustToJSONForDev(args), "[]\r\n")
 83	}
 84
 85	return fmt.Sprintf("%s(%s) %s", fn, paramsStr, thisStr)
 86}
 87
 88// This set the obj as ThisObj.
 89func (e *EvalOptions) This(obj *proto.RuntimeRemoteObject) *EvalOptions {
 90	e.ThisObj = obj
 91	return e
 92}
 93
 94// ByObject disables ByValue.
 95func (e *EvalOptions) ByObject() *EvalOptions {
 96	e.ByValue = false
 97	return e
 98}
 99
100// ByUser enables UserGesture.
101func (e *EvalOptions) ByUser() *EvalOptions {
102	e.UserGesture = true
103	return e
104}
105
106// ByPromise enables AwaitPromise.
107func (e *EvalOptions) ByPromise() *EvalOptions {
108	e.AwaitPromise = true
109	return e
110}
111
112func (e *EvalOptions) formatToJSFunc() string {
113	js := strings.Trim(e.JS, "\t\n\v\f\r ;")
114	return fmt.Sprintf(`function() { return (%s).apply(this, arguments) }`, js)
115}
116
117// Eval is a shortcut for [Page.Evaluate] with AwaitPromise, ByValue set to true.
118func (p *Page) Eval(js string, args ...interface{}) (*proto.RuntimeRemoteObject, error) {
119	return p.Evaluate(Eval(js, args...).ByPromise())
120}
121
122// Evaluate js on the page.
123func (p *Page) Evaluate(opts *EvalOptions) (res *proto.RuntimeRemoteObject, err error) {
124	var backoff utils.Sleeper
125
126	// js context will be invalid if a frame is reloaded or not ready, then the isNilContextErr
127	// will be true, then we retry the eval again.
128	for {
129		res, err = p.evaluate(opts)
130		if err != nil && errors.Is(err, cdp.ErrCtxNotFound) {
131			if opts.ThisObj != nil {
132				return nil, &ObjectNotFoundError{opts.ThisObj}
133			}
134
135			if backoff == nil {
136				backoff = utils.BackoffSleeper(30*time.Millisecond, 3*time.Second, nil)
137			} else {
138				_ = backoff(p.ctx)
139			}
140
141			p.unsetJSCtxID()
142
143			continue
144		}
145		return
146	}
147}
148
149func (p *Page) evaluate(opts *EvalOptions) (*proto.RuntimeRemoteObject, error) {
150	args, err := p.formatArgs(opts)
151	if err != nil {
152		return nil, err
153	}
154
155	req := proto.RuntimeCallFunctionOn{
156		AwaitPromise:        opts.AwaitPromise,
157		ReturnByValue:       opts.ByValue,
158		UserGesture:         opts.UserGesture,
159		FunctionDeclaration: opts.formatToJSFunc(),
160		Arguments:           args,
161	}
162
163	if opts.ThisObj == nil {
164		req.ObjectID, err = p.getJSCtxID()
165		if err != nil {
166			return nil, err
167		}
168	} else {
169		req.ObjectID = opts.ThisObj.ObjectID
170	}
171
172	res, err := req.Call(p)
173	if err != nil {
174		return nil, err
175	}
176
177	if res.ExceptionDetails != nil {
178		return nil, &EvalError{res.ExceptionDetails}
179	}
180
181	return res.Result, nil
182}
183
184// Expose fn to the page's window object with the name. The exposure survives reloads.
185// Call stop to unbind the fn.
186func (p *Page) Expose(name string, fn func(gson.JSON) (interface{}, error)) (stop func() error, err error) {
187	bind := "_" + utils.RandString(8)
188
189	err = proto.RuntimeAddBinding{Name: bind}.Call(p)
190	if err != nil {
191		return
192	}
193
194	_, err = p.Evaluate(Eval(js.ExposeFunc.Definition, name, bind))
195	if err != nil {
196		return
197	}
198
199	code := fmt.Sprintf(`(%s)("%s", "%s")`, js.ExposeFunc.Definition, name, bind)
200	remove, err := p.EvalOnNewDocument(code)
201	if err != nil {
202		return
203	}
204
205	p, cancel := p.WithCancel()
206
207	stop = func() error {
208		defer cancel()
209		err := remove()
210		if err != nil {
211			return err
212		}
213		return proto.RuntimeRemoveBinding{Name: bind}.Call(p)
214	}
215
216	go p.EachEvent(func(e *proto.RuntimeBindingCalled) {
217		if e.Name == bind {
218			payload := gson.NewFrom(e.Payload)
219			res, err := fn(payload.Get("req"))
220			code := fmt.Sprintf("(res, err) => %s(res, err)", payload.Get("cb").Str())
221			_, _ = p.Evaluate(Eval(code, res, err))
222		}
223	})()
224
225	return
226}
227
228func (p *Page) formatArgs(opts *EvalOptions) ([]*proto.RuntimeCallArgument, error) {
229	formatted := []*proto.RuntimeCallArgument{}
230	for _, arg := range opts.JSArgs {
231		if obj, ok := arg.(*proto.RuntimeRemoteObject); ok { // remote object
232			formatted = append(formatted, &proto.RuntimeCallArgument{ObjectID: obj.ObjectID})
233		} else if obj, ok := arg.(*js.Function); ok { // js helper
234			id, err := p.ensureJSHelper(obj)
235			if err != nil {
236				return nil, err
237			}
238			formatted = append(formatted, &proto.RuntimeCallArgument{ObjectID: id})
239		} else { // plain json data
240			formatted = append(formatted, &proto.RuntimeCallArgument{Value: gson.New(arg)})
241		}
242	}
243
244	return formatted, nil
245}
246
247// Check the doc of EvalHelper.
248func (p *Page) ensureJSHelper(fn *js.Function) (proto.RuntimeRemoteObjectID, error) {
249	jsCtxID, err := p.getJSCtxID()
250	if err != nil {
251		return "", err
252	}
253
254	fnID, has := p.getHelper(jsCtxID, js.Functions.Name)
255	if !has {
256		res, err := proto.RuntimeCallFunctionOn{
257			ObjectID:            jsCtxID,
258			FunctionDeclaration: js.Functions.Definition,
259		}.Call(p)
260		if err != nil {
261			return "", err
262		}
263		fnID = res.Result.ObjectID
264		p.setHelper(jsCtxID, js.Functions.Name, fnID)
265	}
266
267	id, has := p.getHelper(jsCtxID, fn.Name)
268	if !has {
269		for _, dep := range fn.Dependencies {
270			_, err := p.ensureJSHelper(dep)
271			if err != nil {
272				return "", err
273			}
274		}
275
276		res, err := proto.RuntimeCallFunctionOn{
277			ObjectID:  jsCtxID,
278			Arguments: []*proto.RuntimeCallArgument{{ObjectID: fnID}},
279
280			FunctionDeclaration: fmt.Sprintf(
281				// we only need the object id, but the cdp will return the whole function string.
282				// So we override the toString to reduce the overhead.
283				"functions => { const f = functions.%s = %s; f.toString = () => 'fn'; return f }",
284				fn.Name, fn.Definition,
285			),
286		}.Call(p)
287		if err != nil {
288			return "", err
289		}
290
291		id = res.Result.ObjectID
292		p.setHelper(jsCtxID, fn.Name, id)
293	}
294
295	return id, nil
296}
297
298func (p *Page) getHelper(jsCtxID proto.RuntimeRemoteObjectID, name string) (proto.RuntimeRemoteObjectID, bool) {
299	p.helpersLock.Lock()
300	defer p.helpersLock.Unlock()
301
302	if p.helpers == nil {
303		p.helpers = map[proto.RuntimeRemoteObjectID]map[string]proto.RuntimeRemoteObjectID{}
304	}
305
306	list, ok := p.helpers[jsCtxID]
307	if !ok {
308		list = map[string]proto.RuntimeRemoteObjectID{}
309		p.helpers[jsCtxID] = list
310	}
311
312	id, ok := list[name]
313	return id, ok
314}
315
316func (p *Page) setHelper(jsCtxID proto.RuntimeRemoteObjectID, name string, fnID proto.RuntimeRemoteObjectID) {
317	p.helpersLock.Lock()
318	defer p.helpersLock.Unlock()
319
320	p.helpers[jsCtxID][name] = fnID
321}
322
323// Returns the page's window object, the page can be an iframe.
324func (p *Page) getJSCtxID() (proto.RuntimeRemoteObjectID, error) {
325	p.jsCtxLock.Lock()
326	defer p.jsCtxLock.Unlock()
327
328	if *p.jsCtxID != "" {
329		return *p.jsCtxID, nil
330	}
331
332	if !p.IsIframe() {
333		obj, err := proto.RuntimeEvaluate{Expression: "window"}.Call(p)
334		if err != nil {
335			return "", err
336		}
337
338		*p.jsCtxID = obj.Result.ObjectID
339		p.helpersLock.Lock()
340		p.helpers = nil
341		p.helpersLock.Unlock()
342		return *p.jsCtxID, nil
343	}
344
345	node, err := p.element.Describe(1, true)
346	if err != nil {
347		return "", err
348	}
349
350	obj, err := proto.DOMResolveNode{BackendNodeID: node.ContentDocument.BackendNodeID}.Call(p)
351	if err != nil {
352		return "", err
353	}
354
355	p.helpersLock.Lock()
356	delete(p.helpers, *p.jsCtxID)
357	p.helpersLock.Unlock()
358	id, err := p.jsCtxIDByObjectID(obj.Object.ObjectID)
359	*p.jsCtxID = id
360	return *p.jsCtxID, err
361}
362
363func (p *Page) unsetJSCtxID() {
364	p.jsCtxLock.Lock()
365	defer p.jsCtxLock.Unlock()
366
367	*p.jsCtxID = ""
368}
369
370func (p *Page) jsCtxIDByObjectID(id proto.RuntimeRemoteObjectID) (proto.RuntimeRemoteObjectID, error) {
371	res, err := proto.RuntimeCallFunctionOn{
372		ObjectID:            id,
373		FunctionDeclaration: `() => window`,
374	}.Call(p)
375	if err != nil {
376		return "", err
377	}
378
379	return res.Result.ObjectID, nil
380}