4

How to catch alert box showing on web page and getting the text inside it by using chromedp

I have noticed that when alert is showing up, I can see that Page.javascriptDialogOpening is showing

I am using

cdp.EvaluateAsDevTools("Page.javascriptDialogOpening", res)

to get the text inside it, but it doesn't work How to handle it in chromedp??

Salis
  • 179
  • 1
  • 20

2 Answers2

2

Inside a Task, use ListenTarget and wait till you a JS dialog event.

printMsg := chromedp.ActionFunc(func(ctx context.Context) error {


    chromedp.ListenTarget(lctx, func(ev interface{}) {

        if _, ok := ev.(*page.EventJavascriptDialogOpening); ok { // page loaded

            fmt.Printf(ev.(*page.EventJavascriptDialogOpening).Message) // holds msg!
        }
    })

}
TCS
  • 5,790
  • 5
  • 54
  • 86
1

I did a workaround by hard-coding some javascript into the browser before anything and then listening to the alert box text in the console.

here the code for reference:

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

    // run task list
    var res interface{}
    err := chromedp.Run(ctx,
    chromedp.Navigate(`https://www.quackit.com/javascript/javascript_alert_box.cfm`), // navigate to random page
    chromedp.EvaluateAsDevTools(`window.alert = function (txt){return txt}`, &res), // set a function to return the text in the alert box as text
    chromedp.EvaluateAsDevTools(`alert('hehe')`, &res), // create an alert box to test the execution
)
    if err != nil {
        log.Fatal(err)
    }
    log.Println(res)

}

it will log in your console the res. Hope it helps ;)

nicolasassi
  • 490
  • 4
  • 14