Skip to content

Commit

Permalink
encapsulate runtime.CallFunctionOn
Browse files Browse the repository at this point in the history
The advantages of runtime.CallFunctionOn are:

1. it's safe to pass arguments into js;
2. the js function can be bound to a remote object (accessed by "this").

So that we can use runtime.CallFunctionOn to run js function without
constructing js dynamically.
  • Loading branch information
ZekeLu committed Jul 12, 2021
1 parent 17a358f commit 398348c
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions call.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package chromedp

import (
"context"

"github.com/chromedp/cdproto/runtime"
)

// CallAction are actions that calls a Javascript function using
// runtime.CallFunctionOn.
type CallAction Action

// CallFunctionOn is an action to call a Javascript function, unmarshaling
// the result of the function to res.
//
// The handling of res is the same as that of Evaluate.
//
// Do not call the following methods on runtime.CallFunctionOnParams:
// - WithReturnByValue: it will be set depending on the type of res;
// - WithArguments: pass the arguments with args instead.
//
// Note: any exception encountered will be returned as an error.
func CallFunctionOn(functionDeclaration string, res interface{}, opt CallOption, args ...interface{}) CallAction {
return ActionFunc(func(ctx context.Context) error {
// set up parameters
p := runtime.CallFunctionOn(functionDeclaration).
WithSilent(true)

switch res.(type) {
case nil, **runtime.RemoteObject:
default:
p = p.WithReturnByValue(true)
}

// apply opt
if opt != nil {
p = opt(p)
}

// arguments
if len(args) > 0 {
ea := &errAppender{args: make([]*runtime.CallArgument, 0, len(args))}
for _, arg := range args {
ea.append(arg)
}
if ea.err != nil {
return ea.err
}
p = p.WithArguments(ea.args)
}

// call
v, exp, err := p.Do(ctx)
if err != nil {
return err
}
if exp != nil {
return exp
}

return parseRemoteObject(v, res)
})
}

// CallOption is a function to modify the runtime.CallFunctionOnParams
// to provide more information.
type CallOption = func(params *runtime.CallFunctionOnParams) *runtime.CallFunctionOnParams

0 comments on commit 398348c

Please sign in to comment.