gogoogle-chrome-headlesschromedp

How to detect javascript alert using chromedp


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)
        }

}

Solution

  • 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"),
        )
    }