Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How can I use Browsershot to capture a webpage with JavaScript executed
    Browsershot JavaScript webpage capture HTML body screenshot device emulation custom JavaScript


How can I use Browsershot to capture a webpage with JavaScript executed


Browsershot can be used to capture a webpage with JavaScript executed. Here's how you can do it:

To get the HTML body of a page after JavaScript has been executed, you can use the `bodyHtml()` method:

php
$html = Browsershot::url('https://example.com')->bodyHtml();

This will return the HTML of the page after the JavaScript has finished executing.

If you want to capture a screenshot of the page with JavaScript executed, you can use the `save()` method:

php
Browsershot::url('https://example.com')
    ->waitUntilNetworkIdle()
    ->save($pathToImage);

The `waitUntilNetworkIdle()` method ensures that the screenshot is taken after all network requests have completed and the page has fully loaded.[2]

You can also customize the screenshot further by setting options like the window size, device emulation, and more:

php
Browsershot::url('https://example.com')
    ->windowSize(1920, 1080)
    ->deviceScaleFactor(2)
    ->mobile()
    ->waitUntilNetworkIdle()
    ->save($pathToImage);

This will capture a screenshot of the page in mobile view, with a device scale factor of 2, and wait until the network is idle before taking the screenshot.[2]

Additionally, you can add custom JavaScript to be executed on the page before taking the screenshot:

php
Browsershot::url('https://example.com')
    ->setJavaScriptValue('window.myVariable = "hello";')
    ->save($pathToImage);

This will execute the provided JavaScript on the page before taking the screenshot.[2]

Overall, Browsershot provides a flexible and powerful way to capture webpages with JavaScript executed, allowing you to customize the screenshot process to your specific needs.

Citations:
[1] https://stackoverflow.com/questions/tagged/browsershot
[2] https://spatie.be/docs/browsershot/v4/usage/creating-images
[3] https://github.com/spatie/browsershot/activity
[4] https://dev.to/kubeden/how-to-make-screenshots-in-laravel-with-browsershot-1ai2
[5] https://github.com/spatie/browsershot