gochromedp

Tasks inside chromedp.ActionFunc not working as expected


This is my code:

package main

import (
        "context"
        "log"
        "fmt"
        "github.com/chromedp/chromedp"
)

func main() {
        queries := [3]string{"Object.keys(window);", "window.CSS", "window.Array"}

        // create context
        ctx, cancel := chromedp.NewContext(context.Background())
        defer cancel()

        // run task list
        var res []byte
        err := chromedp.Run(ctx,
                chromedp.Navigate(`https://www.google.com/`),
                chromedp.ActionFunc(func(ctx context.Context) error {
                for _, query := range queries {

                        err2 := chromedp.Evaluate(query, &res)
                        if err2 != nil {
                                fmt.Printf("error in ActionFunc: %s\n", err2)
                        }

                        fmt.Printf("Query %s outputs: %v\n", query, res)
                }
        return nil
        }),
        )
        if err != nil {
                log.Fatal(err)
        }

}

What i am trying to do is to navigate to url to Evaluate and get values for a big list of queries (I reduced the array to 3 queries for the example).

and then it should just outputs the values from those queries.

But what i get is these errors for every iteration:

error in ActionFunc: %!s(chromedp.ActionFunc=0x7f25a0)
Query Object.keys(window); outputs: []
error in ActionFunc: %!s(chromedp.ActionFunc=0x7f25a0)
Query window.CSS outputs: []
error in ActionFunc: %!s(chromedp.ActionFunc=0x7f25a0)
Query window.Array outputs: []

Solution

  • chromedp.Evaluate does not return error. It returns EvaluateAction. It has Do func which accepts context. So you can try this;

    queries := [3]string{"Object.keys(window);", "window.CSS", "window.Array"}
    
        // create context
        ctx, cancel := chromedp.NewContext(context.Background())
        defer cancel()
    
        // run task list
        var res []byte
        err := chromedp.Run(ctx,
            chromedp.Navigate(`https://www.google.com/`),
            chromedp.WaitReady("body"),
            //chromedp.Evaluate("Object.keys(window)", &res),
            chromedp.ActionFunc(func(ctx context.Context) error {
                for _, query := range queries {
    
                    chromedp.Evaluate(query, &res).Do(ctx)
    
                    fmt.Printf("Query %s outputs: %+v\n", query, string(res))
    
                }
                return nil
            }),
        )
        if err != nil {
            log.Fatal(err)
        }