- 
      
 - 
        
Save SamHwang1990/821f8637c970edf3a99ddecb059f630a 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
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment