Using chromedp with a timeout

I am using chromedp to launch a new browser context when opening a link in a new tab. While debugging this, I am running remotely so I can see visually see what is present on the screen.

This is a separate issue, but even though the link is present and at the same xpath as I am using, my app hangs indefinitely. So, I tried to merely wrap the existing context with a context.WithTimeout(…), but am having issues with that.

I am presently wrapping the WaitVisible function with an ActionFunc and processing the timeout there. Lastly, I use a select block to either get the target id of the newly opened tab or a timeout, whichever occurs first.

This is presently my code:

func (i Instance) tryLaunch() error {
log.Info().Msgf(“launching instance: %d → %d @ [%s]”, i, i.Index, action.Location(i.session.ctx))
targetElementXpath := fmt.Sprintf("//
[@id="home-screen"]/div[2]/section[5]/div[5]/div/ul/li[%d]/a[1]", i.Index)
targetIDChannel := chromedp.WaitNewTarget(i.session.ctx, matchTabWithNonEmptyURL)

waitTime := 5*time.Second

err := chromedp.Run(i.session.ctx, chromedp.ActionFunc(func(ctx context.Context) error {
timeLimitedCtx, timeLimitedCancel := context.WithTimeout(i.session.ctx, waitTime)
defer timeLimitedCancel()

log.Info().Msgf("waiting for target element to be visible: %s", targetElementXpath)
return chromedp.WaitVisible(targetElementXpath).Do(timeLimitedCtx)

}),
chromedp.Click(targetElementXpath),
)

if err != nil {
return err
}

log.Info().Msg(“initializing new context from new tab”)

select {
case targetId := <-targetIDChannel:
newInstance, newCancelFunc := chromedp.NewContext(i.session.ctx, chromedp.WithTargetID(targetId))
i.ctx = newInstance
i.cancel = newCancelFunc
return nil
case <-time.After(waitTime):
log.Warn().Msg(“timed out waiting for targetID”)
return errors.New(“operation timed out”)
}
}

Prior to this block of code, I tried to merely pass in the timeLimitedContext without wrapping WaitVisible in an ActionFunc. When done that way, it seemed to have no effect whatsoever. In the current state it is in, I end up with this error:

panic: interface conversion: interface is nil, not cdp.Executor

That error occurs on this line:

err := chromedp.Run(i.session.ctx, chromedp.ActionFunc(func(ctx context.Context) error {

Thanks,

Hello,

The panic: interface conversion: interface is nil, not cdp.Executor error in your code suggests that the ctx passed into the inner chromedp.ActionFunc no longer contains a valid cdp.Executor. This typically happens when you’re improperly managing or re-wrapping the context, such as by calling context.WithTimeout on a parent context that has been stripped of the browser’s executor/session bindings.

Best Regards
cat translation app