Creating images | browsershot | Spatie

 SPATIE

  Browsershot
==============

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Browsershot](https://spatie.be/docs/browsershot/v4)  Usage  Creating images

 Version   v4   v3

 Other versions for crawler [v4](https://spatie.be/docs/browsershot/v4) [v3](https://spatie.be/docs/browsershot/v3)

- [ Introduction ](https://spatie.be/docs/browsershot/v4/introduction)
- [ Support us ](https://spatie.be/docs/browsershot/v4/support-us)
- [ Requirements ](https://spatie.be/docs/browsershot/v4/requirements)
- [ Installation &amp; setup ](https://spatie.be/docs/browsershot/v4/installation-setup)
- [ Upgrading ](https://spatie.be/docs/browsershot/v4/upgrading)
- [ Questions and issues ](https://spatie.be/docs/browsershot/v4/questions-issues)
- [ Changelog ](https://spatie.be/docs/browsershot/v4/changelog)
- [ About us ](https://spatie.be/docs/browsershot/v4/about-us)

Usage
-----

- [ Introduction ](https://spatie.be/docs/browsershot/v4/usage/introduction)
- [ Creating images ](https://spatie.be/docs/browsershot/v4/usage/creating-images)
- [ Creating PDFs ](https://spatie.be/docs/browsershot/v4/usage/creating-pdfs)
- [ Creating HTML ](https://spatie.be/docs/browsershot/v4/usage/creating-html)

Miscellaneous options
---------------------

- [ Adding extra headers to every request ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/adding-extra-headers-to-every-request)
- [ Adding extra headers to the navigational request ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/adding-extra-headers-to-the-navigational-request)
- [ Changing the language of the browser ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/changing-the-language-of-the-browser)
- [ Changing the value of a dropdown ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/changing-the-value-of-a-dropdown)
- [ Clicking on the page ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/clicking-on-the-page)
- [ Connection to a remote chromium/chrome instance ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/connection-to-a-remote-chrome-instance)
- [ Disable sandboxing ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/disable-sandboxing)
- [ Fixing cors issues ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/fixing-cors-options)
- [ Getting console output ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/getting-console-ouput)
- [ Getting failed requests ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/getting-failed-requests)
- [ Ignore HTTPS errors ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/ignore-https-errors)
- [ Passing environment variables to the browser ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/passing-environment-variables-to-the-browser)
- [ Performance ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/performance)
- [ Prevent unsuccessful responses ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/prevent-unsuccessful-responses)
- [ Sending POST requests ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/sending-post-requests)
- [ Setting an arbitrary option ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/setting-an-arbirary-option)
- [ Setting the CSS media type of the page ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/setting-the-css-media-type-of-the-page)
- [ Setting the timeout ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/setting-the-timeout)
- [ Setting the user agent ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/setting-the-user-agent)
- [ Specifying-a-proxy-server ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/specifying-a-proxy-server)
- [ Typing on the page ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/typing-on-the-page)
- [ Using a pipe instead of a WebSocket ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/using-a-pipe-instead-of-a-websocket)
- [ Using cookies ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/using-cookies)
- [ Using HTTP Authentication ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/using-http-authentication)
- [ Using url for html content ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/using-url-for-html-content)
- [ Writing options to a file ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/writing-options-to-a-file)
- [ Disabling redirects ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/disabling-redirects)
- [ Read redirect history ](https://spatie.be/docs/browsershot/v4/miscellaneous-options/read-redirect-history)

 Creating images
===============

###  On this page

1. [ Formatting the image ](#content-formatting-the-image)
2. [ Sizing the image ](#content-sizing-the-image)
3. [ Manipulating the image ](#content-manipulating-the-image)
4. [ Taking a full page screenshot ](#content-taking-a-full-page-screenshot)
5. [ Setting the device scale ](#content-setting-the-device-scale)
6. [ Mobile emulation ](#content-mobile-emulation)
7. [ Device emulation ](#content-device-emulation)
8. [ Backgrounds ](#content-backgrounds)
9. [ Dismiss dialogs ](#content-dismiss-dialogs)
10. [ Disable Javascript ](#content-disable-javascript)
11. [ Disable Images ](#content-disable-images)
12. [ Block Urls ](#content-block-urls)
13. [ Block Domains ](#content-block-domains)
14. [ Waiting for lazy-loaded resources ](#content-waiting-for-lazy-loaded-resources)
15. [ Delayed screenshots ](#content-delayed-screenshots)
16. [ Waiting for javascript function ](#content-waiting-for-javascript-function)
17. [ Waiting for a selector ](#content-waiting-for-a-selector)
18. [ Adding JS ](#content-adding-js)
19. [ Adding CSS ](#content-adding-css)
20. [ Output directly to the browser ](#content-output-directly-to-the-browser)
21. [ Setting the user data directory ](#content-setting-the-user-data-directory)

Here's the easiest way to create an image of a webpage:

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

Formatting the image
--------------------------------------------------------------------------------------------------------------------

By default, the screenshot's type will be a `png`. (According to [Puppeteer's Config](https://github.com/puppeteer/puppeteer/blob/main/docs/api/puppeteer.screenshotoptions.md)) But you can change it to `jpeg` with quality option.

```
Browsershot::url('https://example.com')
    ->setScreenshotType('jpeg', 100)
    ->save($pathToImage);
```

Sizing the image
--------------------------------------------------------------------------------------------------------

By default the screenshot's size will match the resolution you use for your desktop. Want another size of screenshot? No problem!

```
Browsershot::url('https://example.com')
    ->windowSize(640, 480)
    ->save($pathToImage);
```

You can screenshot only a portion of the page by using `clip`.

```
Browsershot::url('https://example.com')
    ->clip($x, $y, $width, $height)
    ->save($pathToImage);
```

You can take a screenshot of an element matching a selector using `select` and an optional `$selectorIndex` which is used to select the nth element (e.g. use `$selectorIndex = 3` to get the fourth element like `div:eq(3)`). By default `$selectorIndex` is `0` which represents the first matching element.

```
Browsershot::url('https://example.com')
    ->select('.some-selector', $selectorIndex)
    ->save($pathToImage);
```

### Getting a screenshot as base64

If you need the base64 version of a screenshot you can use the `base64Screenshot` method. This can come in handy when you don't want to save the screenshot on disk.

```
$base64Data = Browsershot::url('https://example.com')
    ->base64Screenshot();
```

Manipulating the image
--------------------------------------------------------------------------------------------------------------------------

To perform image manipulation on the screenshot, you need to install the optional dependency [spatie/image](https://spatie.be/docs/image). v3 or higher is required.

```
composer require spatie/image
```

You can use all the methods [spatie/image](https://docs.spatie.be/image) provides. Here's an example where we create a greyscale image:

```
Browsershot::url('https://example.com')
    ->windowSize(640, 480)
    ->greyscale()
    ->save($pathToImage);
```

Taking a full page screenshot
-----------------------------------------------------------------------------------------------------------------------------------------------

You can take a screenshot of the full length of the page by using `fullPage()`.

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

Setting the device scale
--------------------------------------------------------------------------------------------------------------------------------

You can also capture the webpage at higher pixel densities by passing a device scale factor value of 2 or 3. This mimics how the webpage would be displayed on a retina/xhdpi display.

```
Browsershot::url('https://example.com')
    ->deviceScaleFactor(2)
    ->save($pathToImage);
```

Mobile emulation
--------------------------------------------------------------------------------------------------------

You can emulate a mobile view with the `mobile` and `touch` methods. `mobile` will set the display to take into account the page's meta viewport, as Chrome mobile would. `touch` will set the browser to emulate touch functionality, hence allowing spoofing for pages that check for touch. Along with the `userAgent` method, these can be used to effectively take a mobile screenshot of the page.

```
Browsershot::url('https://example.com')
    ->userAgent('My Mobile Browser 1.0')
    ->mobile()
    ->touch()
    ->save($pathToImage);
```

Device emulation
--------------------------------------------------------------------------------------------------------

You can emulate a device view with the `device` method. The devices' names can be found [Here](https://github.com/puppeteer/puppeteer/blob/main/docs/api/puppeteer.knowndevices.md).

```
$browsershot = new Browsershot('https://example.com', true);
$browsershot
        ->device('iPhone X')
        ->save($pathToImage);
```

is the same as

```
Browsershot::url('https://example.com')
    ->userAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1')
    ->windowSize(375, 812)
    ->deviceScaleFactor(3)
    ->mobile()
    ->touch()
    ->landscape(false)
    ->save($pathToImage);
```

Backgrounds
-----------------------------------------------------------------------------------------

If you want to ignore the website's background when capturing a screenshot, use the `hideBackground()` method.

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

Dismiss dialogs
-----------------------------------------------------------------------------------------------------

Javascript pop ups such as alerts, prompts and confirmations cause rendering of the site to stop, which leads to an empty screenshot. Calling `dismissDialogs()` method automatically closes such popups allowing the screenshot to be taken.

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

Disable Javascript
--------------------------------------------------------------------------------------------------------------

If you want to completely disable javascript when capturing the page, use the `disableJavascript()` method. Be aware that some sites will not render correctly without javascript.

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

Disable Images
--------------------------------------------------------------------------------------------------

You can completely remove all images and ![]() elements when capturing a page using the `disableImages()` method.

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

Block Urls
--------------------------------------------------------------------------------------

You can completely block connections to specific Urls using the `blockUrls()` method. Useful to block advertisements and trackers to make screenshot creation faster.

```
$urlsList = array("example.com/cm-notify?pi=outbrain", "sync.outbrain.com/cookie-sync?p=bidswitch");
Browsershot::url('https://example.com')
    ->blockUrls($urlsList)
    ->save($pathToImage);
```

Block Domains
-----------------------------------------------------------------------------------------------

You can completely block connections to specific domains using the `blockDomains()` method. Useful to block advertisements and trackers to make screenshot creation faster.

```
$domainsList = array("googletagmanager.com", "googlesyndication.com", "doubleclick.net", "google-analytics.com");
Browsershot::url('https://example.com')
    ->blockDomains($domainsList)
    ->save($pathToImage);
```

Waiting for lazy-loaded resources
-----------------------------------------------------------------------------------------------------------------------------------------------------------

Some websites lazy-load additional resources via ajax or use webfonts, which might not be loaded in time for the screenshot. Using the `waitUntilNetworkIdle()` method you can tell Browsershot to wait for a period of 500 ms with no network activity before taking the screenshot, ensuring all additional resources are loaded.

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

Alternatively you can use less strict `waitUntilNetworkIdle(false)`, which allows 2 network connections in the 500 ms waiting period, useful for websites with scripts periodically pinging an ajax endpoint.

Delayed screenshots
-----------------------------------------------------------------------------------------------------------------

You can delay the taking of screenshot by `setDelay()`. This is useful if you need to wait for completion of javascript or if you are attempting to capture lazy-loaded resources.

```
Browsershot::url('https://example.com')
    ->setDelay($delayInMilliseconds)
    ->save($pathToImage);
```

Waiting for javascript function
-----------------------------------------------------------------------------------------------------------------------------------------------------

You can also wait for a javascript function until is returns true by using `waitForFunction()`. This is useful if you need to wait for task on javascript which is not related to network status.

```
Browsershot::url('https://example.com')
    ->waitForFunction('window.innerWidth < 100', $pollingInMilliseconds, $timeoutInMilliseconds)
    ->save($pathToImage);
```

Waiting for a selector
--------------------------------------------------------------------------------------------------------------------------

You can also wait for a selector by using `waitForSelector()`. This is useful if you need to wait for the selector to appear in page.

```
Browsershot::url('https://example.com')
    ->waitForSelector('#my_selector')
    ->save($pathToImage);
```

Adding JS
-----------------------------------------------------------------------------------

You can add javascript prior to your screenshot or output using the syntax for [Puppeteer's addScriptTag](https://github.com/puppeteer/puppeteer/blob/v1.9.0/docs/api.md#pageaddscripttagoptions).

```
Browsershot::url('https://example.com')
    ->setOption('addScriptTag', json_encode(['content' => 'alert("Hello World")']))
    ->save($pathToImage);
```

Adding CSS
--------------------------------------------------------------------------------------

You can add CSS styles prior to your screenshot or output using the syntax for [Puppeteer's addStyleTag](https://github.com/puppeteer/puppeteer/blob/v1.9.0/docs/api.md#pageaddstyletagoptions).

```
Browsershot::url('https://example.com')
    ->setOption('addStyleTag', json_encode(['content' => 'body{ font-size: 14px; }']))
    ->save($pathToImage);
```

Output directly to the browser
--------------------------------------------------------------------------------------------------------------------------------------------------

You can output the image directly to the browser using the `screenshot()` method.

```
$image = Browsershot::url('https://example.com')->screenshot()
```

Setting the user data directory
-----------------------------------------------------------------------------------------------------------------------------------------------------

You can set the [user data directory](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/docs/user_data_dir.md) that is used to store the browser session and additional data. Setting this to a static value may introduce cache problems, could also increase performance. It needs to be an absolute path.

```
$image = Browsershot::url('https://example.com')
    ->userDataDir('/tmp/session-1')
    ->screenshot()
```
