Search code examples
phpcsslaravelpuppeteerspatie-browsershot

Using Spatie/Browsershot with laravel. Injected HTML is rendering correctly when in Chrome, but not in Browsershot


I have a laravel app that reads a webpage, replaces all relative URLs with absolute URLs from the original webpage and returns the HTML.

This works well and exactly how I want. Trying to also grab a screenshot of the resulting rendered HTML using spatie/Browsershot (which uses Puppeteer via headless Chrome browser).

The result of the screenshot shows that the CSS is not being rendered.

The code in question looks like this:

 //Create Screenshot 
 $browserShot = Browsershot::html($html);
 $browserShot->setChromePath(config('browsershot.chrome_path'))->setOption('args', ['--disable-web-security'])->waitUntilNetworkIdle()->emulateMedia(null)->fullPage()->save($fileName.".png");

// Output HTML content
return $html;

The HTML returned to the user gets rendered fine by Chrome. But for some reason in the headless chrome browser it is not picking up the CSS.


Solution

  • The issue was the default userAgent. After updating that rendering works as expected:

    //Create Screenshot
     $browserShot = Browsershot::html($boundingBoxHtml);
     $browserShot->setChromePath(config('browsershot.chrome_path'))->waitUntilNetworkIdle()->userAgent($userAgent)->emulateMedia('screen')->fullPage()->save($fileName.".png");