Skip to content

Instantly share code, notes, and snippets.

@NaniteFactory
Created October 21, 2019 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NaniteFactory/16124ad6d60fb78f97bc4f0f60bbea52 to your computer and use it in GitHub Desktop.
Save NaniteFactory/16124ad6d60fb78f97bc4f0f60bbea52 to your computer and use it in GitHub Desktop.
chromedp screenshot example
package main
import (
"context"
"io/ioutil"
"log"
"math"
"time"
"github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
)
func main() {
// create chrome instance
ctx, cancel := chromedp.NewContext(
context.Background(),
chromedp.WithLogf(log.Printf),
)
defer cancel()
// create a timeout
ctx, cancel = context.WithTimeout(ctx, 15*time.Second)
defer cancel()
var img []byte
err := chromedp.Run(ctx,
chromedp.Navigate(`https://golang.org/pkg/time/`),
chromedp.WaitVisible(`body > footer`), // wait for footer element is visible (ie, page is loaded)
FullScreenshot(90, &img),
)
if err != nil {
log.Fatal(err)
}
if err := ioutil.WriteFile("fullScreenshot.png", img, 0644); err != nil {
log.Fatal(err)
}
}
func FullScreenshot(quality int64, result *[]byte) chromedp.Action {
return chromedp.ActionFunc(func(ctx context.Context) error {
// get layout metrics
_, _, contentSize, err := page.GetLayoutMetrics().Do(ctx)
if err != nil {
return err
}
width, height := int64(math.Ceil(contentSize.Width)), int64(math.Ceil(contentSize.Height))
// force viewport emulation
err = emulation.SetDeviceMetricsOverride(width, height, 1, false).
WithScreenOrientation(&emulation.ScreenOrientation{
Type: emulation.OrientationTypePortraitPrimary,
Angle: 0,
}).
Do(ctx)
if err != nil {
return err
}
// capture screenshot
*result, err = page.CaptureScreenshot().
WithQuality(quality).
WithClip(&page.Viewport{
X: contentSize.X,
Y: contentSize.Y,
Width: contentSize.Width,
Height: contentSize.Height,
Scale: 1,
}).Do(ctx)
if err != nil {
return err
}
return nil
})
}
@nikolay-turpitko
Copy link

contentSize is nil with recent versions of chromerdp / chromium

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment