1

I'm trying to identify that an alert popped up after navigating to a URL using chromedp. I tried using a listener as follows but I'm new to Golang so I'm not sure why it didn't work.

package main

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

func main() {
        // create context
        url := "https://grey-acoustics.surge.sh/?__proto__[onload]=alert('hello')"
        ctx, cancel := chromedp.NewContext(context.Background())
        defer cancel()

        chromedp.ListenTarget(ctx, func(ev interface{}) {
                if ev, ok := ev.(*page.EventJavascriptDialogOpening); ok {
                        fmt.Println("Got an alert: %s", ev.Message)
                }
        })

        // run task list
        err := chromedp.Run(ctx,
                chromedp.Navigate(url),
        )
        if err != nil {
                log.Fatal(err)
        }

}
Raywando
  • 129
  • 5

1 Answers1

1

For your specific URL it helped to wait for the iframe to load to receive the event, otherwise chromedp seems to stop because it is finished with its task list.

    // run task list
    err := chromedp.Run(ctx,
        chromedp.Navigate(url),
        chromedp.WaitVisible("iframe"),
    )
}
ResamVi
  • 86
  • 4
  • Thanks! it worked. But is there a way to do that for any URL? I was thinking about setting a timeout if the element `body` for example didnt show up, but i don't think this is the best way – Raywando Apr 17 '21 at 18:55
  • It's hard to say for "any URL", as the steps until an alert occurs differ for each one but I would declare all necessary tasks to trigger the alert and as a makeshit use [Sleep](https://pkg.go.dev/github.com/knq/chromedp?utm_source=godoc#Sleep) or - better yet - Wait for any other more tangible change after an alert is triggered – ResamVi Apr 18 '21 at 12:33