var x = `<h1>Hello World</h1>`
How to navigate chromedp to x
without saving x
as file?
This works fine for me.. thanks a lot for the keyword @Zeke Lu
package main
import (
"context"
"log"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
)
func main() {
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.Flag("headless", false),
)
ctx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
defer cancel()
ctx, cancel = chromedp.NewContext(ctx)
defer cancel()
htmlContent := `<h1>Hello World</h1>`
if err := chromedp.Run(ctx,
chromedp.Navigate("about:blank"),
loadHTMLFromStringActionFunc(htmlContent),
); err != nil {
log.Fatal(err)
}
}
func loadHTMLFromStringActionFunc(content string) chromedp.ActionFunc {
return chromedp.ActionFunc(func(ctx context.Context) error {
ch := make(chan bool, 1)
defer close(ch)
go chromedp.ListenTarget(ctx, func(ev interface{}) {
if _, ok := ev.(*page.EventLoadEventFired); ok {
ch <- true
}
})
frameTree, err := page.GetFrameTree().Do(ctx)
if err != nil {
return err
}
if err := page.SetDocumentContent(frameTree.Frame.ID, content).Do(ctx); err != nil {
return err
}
select {
case <-ch:
return nil
case <-ctx.Done():
return context.DeadlineExceeded
}
})
}