How can I take screenshot upon chromedp.Run failure?

113 Views Asked by At

I'd like to have a screenshot of how the browser looked like when an error (context deadline exceeded) occurs (preferably in both headless and headed modes).

I added chromedp.Screenshot(...) to the chromedp.Run flow and the screenshot it taken properly when the run passes, however when it fails, the error occurs before the Screenshot step and causes the browser to be closed so it's too late to capture the screenshot. Thank you!

1

There are 1 best solutions below

0
Zeke Lu On

A workaround is utilize the screencast feature and save the last frame (or several frames) when something goes wrong:

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "os"

    "github.com/chromedp/cdproto/page"
    "github.com/chromedp/chromedp"
)

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

    var screenshot string

    chromedp.ListenTarget(ctx, func(ev interface{}) {
        if ev, ok := ev.(*page.EventScreencastFrame); ok {
            // Only keep the last frame.
            // You can modify the code to keep several frames or all the frames.
            screenshot = ev.Data

            go func() {
                _ = chromedp.Run(ctx, page.ScreencastFrameAck(ev.SessionID))
            }()
        }
    })

    if err := chromedp.Run(ctx,
        page.StartScreencast(),
        // Put your actions here.
        page.StopScreencast(),
    ); err != nil {
        if screenshot != "" {
            buf, err := base64.StdEncoding.DecodeString(screenshot)
            if err != nil {
                fmt.Printf("failed to decode the screenshot data: %v\n", err)
            } else {
                _ = os.WriteFile("screenshot.png", buf, 0o644)
            }
        }
        panic(err)
    }
}