Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created June 1, 2019 20:19
Show Gist options
  • Save xeoncross/61e177b207875952288bfe37912a0d51 to your computer and use it in GitHub Desktop.
Save xeoncross/61e177b207875952288bfe37912a0d51 to your computer and use it in GitHub Desktop.
Example of using chromedp to prerender a create-react-app frontend using fake SSR via chrome headless
package main
import (
"context"
"io/ioutil"
"log"
"strings"
"testing"
"github.com/chromedp/cdproto/dom"
"github.com/chromedp/chromedp"
)
func TestSSRofCRA(t *testing.T) {
// create context, this would come from client if using HTTP
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
// create-react-app uses port 3000 by default
var res string
err := chromedp.Run(ctx, scrapIt("http://localhost:3000/", &res))
if err != nil {
t.Fatal(err)
}
ioutil.WriteFile("rendered.html", []byte(res), 0664)
log.Println(strings.TrimSpace(res))
}
func scrapIt(url string, str *string) chromedp.Tasks {
return chromedp.Tasks{
chromedp.Navigate(url),
chromedp.ActionFunc(func(ctx context.Context) error {
node, err := dom.GetDocument().Do(ctx)
if err != nil {
return err
}
*str, err = dom.GetOuterHTML().WithNodeID(node.NodeID).Do(ctx)
return err
}),
}
}
// Alternative, less-stable fetch using chrome directly
// out, err := exec.Command("sh", "-c", "/root/tools/chromium-latest-linux/latest/chrome --headless --no-sandbox --dump-dom "+url).Output()
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("%s\n", out)