I have a slice containing a list of terms, and I want to search for each term in a certain search engine page, so I am doing this:
func risk(slice []string) chromedp.Tasks {
return chromedp.Tasks{
chromedp.Navigate("https://testpage"),
chromedp.WaitVisible("#query_box", chromedp.ByID),
chromedp.ActionFunc(func(context.Context, cdp.Executor) error {
for _, element := range slice[2:] {
fmt.Println(element)
chromedp.SendKeys("#query_box", element, chromedp.ByID)
chromedp.Click("#searchButton", chromedp.ByID),
}
return nil
}),
}
}
When calling this inside main
as
err = c.Run(ctxt, risk(items))
if err != nil {
log.Fatal(err)
}
Everything works until the ActionFunc
. Whatever action I can add before the function (take screenshot, etc...) work without issues.
However, the actions inside ActionFunc
don't get performed.
Is the reason the return nil
? I wanted to return the set of tasks like I am doing outside the loop, but I couldn't find about how to do that inside a loop in the ActionFunc
, since the return would always be the latest item rather than the full set... Returning nil
was the only way to get the function to at least get started.
What is the correct way to perform this sort of loop operations inside a set of chromedp.Tasks
?
chromedp.ActionFunc
is used to build a custom action. The function you give it will be executed during the Run
phase.
This means that your function needs to actually run the actions you are using inside. This is done by calling the .Do
method on the action and passing it a context.Context
and cdp.Executor
.
As for errors, the function should return any error encountered while running. When calling .Do
on your embedded actions, check the error and return it if non-nil.
Your code should look like:
func risk(slice []string) chromedp.Tasks {
return chromedp.Tasks{
// ... other actions ...
chromedp.ActionFunc(func(c context.Context, e cdp.Executor) error {
for _, element := range slice[2:] {
fmt.Println(element)
err := chromedp.SendKeys("#query_box", element, chromedp.ByID).Do(c, e)
if err != nil {
return err
}
err = chromedp.Click("#searchButton", chromedp.ByID).Do(c, e)
if err != nil {
return err
}
}
return nil
}),
}
}
disclaimer: I haven't tested this code, so there may be issues, but this should give you the general idea of defining vs executing an action, and properly returning errors.