### Install Puppeteer and Dependencies on Ubuntu Source: https://spatie.be/docs/browsershot/v4/requirements Setup script for installing Node, Puppeteer, Chromium, and required system libraries on Ubuntu v24.04. ```bash # Check if node and npm are installed node -v && npm -v # Install puppeteer sudo npm install -g puppeteer # Install chromium npx puppeteer browsers install chrome # Install dependencies sudo apt update sudo apt install libx11-xcb1 libxcomposite1 libasound2t64 libatk1.0-0 libatk-bridge2.0-0 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgbm1 libgcc1 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 # You may get an error: "No usable sandbox! If you are running on Ubuntu 23.10+ or another Linux distro that has disabled unprivileged user namespaces with AppArmor" # You can fix this by editing /etc/sysctl.conf and add these lines to the end of the file kernel.apparmor_restrict_unprivileged_userns=0 kernel.apparmor_restrict_unprivileged_unconfined=0 ``` -------------------------------- ### Install image manipulation dependency Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Install spatie/image to enable advanced image processing features. ```bash composer require spatie/image ``` -------------------------------- ### Install Puppeteer on MacOS Source: https://spatie.be/docs/browsershot/v4/requirements Commands to install Puppeteer locally or globally on MacOS. ```bash npm install puppeteer ``` ```bash npm install puppeteer --location=global ``` -------------------------------- ### Install Browsershot via Composer Source: https://spatie.be/docs/browsershot/v4/installation-setup Use this command to add the Browsershot package to your project dependencies. ```bash composer require spatie/browsershot ``` -------------------------------- ### Set initial page number Source: https://spatie.be/docs/browsershot/v4/usage/creating-pdfs Configure the starting page number for the generated PDF. ```php Browsershot::html($someHtml) ->showBrowserHeaderAndFooter() ->hideFooter() ->headerHtml('') ->initialPageNumber(8) ->save('example.pdf'); ``` -------------------------------- ### Set Chrome Executable Path Source: https://spatie.be/docs/browsershot/v4/requirements Point to a specific Chrome or Chromium executable instead of the one installed by Puppeteer. ```php Browsershot::html('Foo') ->setChromePath("/path/to/my/chrome") ``` -------------------------------- ### Get screenshot as base64 Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Retrieve the image data as a base64 string instead of saving to disk. ```php $base64Data = Browsershot::url('https://example.com') ->base64Screenshot(); ``` -------------------------------- ### Retrieving Base64 PDF Data Source: https://spatie.be/docs/browsershot/v4/usage/creating-pdfs Use base64pdf to get the PDF content as a string, useful for environments where file system access is restricted. ```php $base64Data = Browsershot::url('https://example.com') ->base64pdf(); ``` -------------------------------- ### Configure Node and NPM Binary Paths Source: https://spatie.be/docs/browsershot/v4/requirements Manually specify the paths to node and npm binaries if they are not automatically detected. ```php Browsershot::html('Foo') ->setNodeBinary('/usr/local/bin/node') ->setNpmBinary('/usr/local/bin/npm'); ``` -------------------------------- ### Create a basic screenshot Source: https://spatie.be/docs/browsershot/v4/usage/creating-images The simplest method to capture a webpage as an image file. ```php Browsershot::url('https://example.com')->save($pathToImage); ``` -------------------------------- ### Emulate a specific device Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Use the device method to apply predefined device settings, or manually configure equivalent parameters. ```php $browsershot = new Browsershot('https://example.com', true); $browsershot ->device('iPhone X') ->save($pathToImage); ``` ```php 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); ``` -------------------------------- ### Import Browsershot Source: https://spatie.be/docs/browsershot/v4/usage/introduction Include the Browsershot class in your PHP file to begin using its functionality. ```php use Spatie\Browsershot\Browsershot; ``` -------------------------------- ### Emulate CSS media type Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/setting-the-css-media-type-of-the-page Use emulateMedia to switch between screen and print styles. Passing null disables the emulation. ```php Browsershot::url('https://example.com') ->emulateMedia('screen') // "screen", "print" (default) or null (passing null disables the emulation). ->savePdf($pathToPdf); ``` -------------------------------- ### Configuring Headers and Footers Source: https://spatie.be/docs/browsershot/v4/usage/creating-pdfs Enable and customize header and footer content for the generated PDF. ```php Browsershot::html($someHtml) ->showBrowserHeaderAndFooter() ->headerHtml($someHtml) ->footerHtml($someHtml) ->save('example.pdf'); ``` -------------------------------- ### Set Binary Path Source: https://spatie.be/docs/browsershot/v4/requirements Define an alternative path for the execution script. ```php Browsershot::html('Foo') ->setBinPath("/path/to/my/project/my_script.js") ``` -------------------------------- ### Configure a proxy server Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/specifying-a-proxy-server Use the setProxyServer method to specify the proxy address for the Chromium instance. ```php Browsershot::url('https://example.com') ->setProxyServer("1.2.3.4:8080") ... ``` -------------------------------- ### Set browser language via environment options Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/changing-the-language-of-the-browser Configures the browser language by passing an environment array to setEnvironmentOptions. ```php Browsershot::url('https://example.com') ->setEnvironmentOptions([ 'LANG' => 'en-GB', ]) ... ``` -------------------------------- ### Capture a mobile screenshot Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Emulate mobile view by setting user agent, viewport, and touch functionality. ```php Browsershot::url('https://example.com') ->userAgent('My Mobile Browser 1.0') ->mobile() ->touch() ->save($pathToImage); ``` -------------------------------- ### Set Include Path Source: https://spatie.be/docs/browsershot/v4/requirements Modify the system include path to help Browsershot locate node and npm. ```php Browsershot::html('Foo') ->setIncludePath('$PATH:/usr/local/bin') ``` -------------------------------- ### evaluateOnNewDocument Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/evaluating-a-script-before-page-load Injects a script that runs before the page loads on every navigation. ```APIDOC ## evaluateOnNewDocument(string $script) ### Description Injects a script that runs before the page loads, on every page Browsershot navigates to. This is useful for stubbing globals, injecting polyfills, or overriding navigator properties. ### Parameters - **$script** (string) - Required - The JavaScript code to be evaluated as a statement. ### Example ```php Browsershot::url('https://example.com') ->evaluateOnNewDocument('window.myFlag = true') ->save($pathToImage); ``` ``` -------------------------------- ### Configure Browsershot to use a pipe Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/using-a-pipe-instead-of-a-websocket Use the usePipe method to switch the communication transport from WebSocket to a pipe. ```php Browsershot::url('https://example.com') ->usePipe() ... ``` -------------------------------- ### Emulate CSS media features Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/setting-the-css-media-type-of-the-page Use emulateMediaFeatures to simulate specific environment settings like dark mode or reduced motion. ```php Browsershot::url('https://example.com') ->emulateMediaFeatures([ ['name' => 'prefers-color-scheme', 'value' => 'dark'] ]) ->save($pathToImage); ``` -------------------------------- ### Using Predefined PDF Formats Source: https://spatie.be/docs/browsershot/v4/usage/creating-pdfs Apply standard paper formats like A4 or Letter. ```php Browsershot::url('https://example.com')->format('A4')->save('example.pdf'); ``` -------------------------------- ### Browsershot PDF Configuration Methods Source: https://spatie.be/docs/browsershot/v4/usage/creating-pdfs Methods to configure PDF output settings such as orientation, scale, page ranges, and initial page numbering. ```APIDOC ## Browsershot::landscape() ### Description Sets the resulting PDF orientation to landscape. ## Browsershot::scale(float $scale) ### Description Sets the scale of the PDF. Defaults to 1. The scale amount must be between 0.1 and 2. ## Browsershot::pages(string $range) ### Description Controls which pages are exported by passing a print range (e.g., '1', '1-3', '1-5, 8, 11-13'). ## Browsershot::initialPageNumber(int $number) ### Description Sets the initial page number for the PDF document. ``` -------------------------------- ### Format the screenshot Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Change the output format to JPEG and specify quality settings. ```php Browsershot::url('https://example.com') ->setScreenshotType('jpeg', 100) ->save($pathToImage); ``` -------------------------------- ### Take a full page screenshot Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Capture the entire length of the webpage. ```php Browsershot::url('https://example.com') ->fullPage() ->save($pathToImage); ``` -------------------------------- ### Save a URL as a PDF Source: https://spatie.be/docs/browsershot/introduction Captures a webpage and saves it as a PDF file by using the .pdf extension in the save path. ```php // a pdf will be saved Browsershot::url('https://example.com')->save('example.pdf'); ``` -------------------------------- ### Output image to browser Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Use the screenshot method to return the image data directly. ```php $image = Browsershot::url('https://example.com')->screenshot() ``` -------------------------------- ### Set user data directory Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Configure the browser session directory using an absolute path. ```php $image = Browsershot::url('https://example.com') ->userDataDir('/tmp/session-1') ->screenshot() ``` -------------------------------- ### Set an arbitrary option in Browsershot Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/setting-an-arbirary-option Use setOption to pass custom configuration keys and values to the underlying browser instance. ```php Browsershot::url('https://example.com') ->setOption('landscape', true) ->save($pathToImage); ``` -------------------------------- ### Set environment variables in Browsershot Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/passing-environment-variables-to-the-browser Use setEnvironmentOptions to pass an array of custom environment variables to the browser instance. ```php Browsershot::url('https://example.com') ->setEnvironmentOptions(['TZ' => 'Pacific/Auckland']) ... ``` -------------------------------- ### Configuring PDF Backgrounds Source: https://spatie.be/docs/browsershot/v4/usage/creating-pdfs Control the visibility of background elements and transparency in the PDF. ```php Browsershot::html($someHtml) ->showBackground() ->save('example.pdf'); ``` ```php Browsershot::html($someHtml) ->transparentBackground() ->save('example.pdf'); ``` -------------------------------- ### Render arbitrary HTML to PDF Source: https://spatie.be/docs/browsershot/introduction Converts raw HTML strings directly into a PDF file. ```php Browsershot::html('

Hello world!!

')->save('example.pdf'); ``` -------------------------------- ### Manipulate the screenshot Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Apply image transformations like greyscale using the spatie/image integration. ```php Browsershot::url('https://example.com') ->windowSize(640, 480) ->greyscale() ->save($pathToImage); ``` -------------------------------- ### Set device scale factor Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Mimic high-density displays by setting a device scale factor. ```php Browsershot::url('https://example.com') ->deviceScaleFactor(2) ->save($pathToImage); ``` -------------------------------- ### Save a URL as an image Source: https://spatie.be/docs/browsershot/introduction Captures a webpage and saves it as an image file. ```php use Spatie\Browsershot\Browsershot; // an image will be saved Browsershot::url('https://example.com')->save($pathToImage); ``` -------------------------------- ### Submit a form with dropdown selection Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/changing-the-value-of-a-dropdown Combine selectOption with type and click to automate form submission workflows. ```php Browsershot::url('https://example.com') ->type('#firstName', 'My name') ->selectOption('#state', 'MT') ->click('#submit') ->delay($millisecondsToWait) ->save($pathToImage); ``` -------------------------------- ### setNpmBinary(string $path) Source: https://spatie.be/docs/browsershot/v4/requirements Sets the path to the npm binary. ```APIDOC ## setNpmBinary ### Description Sets the path to the npm binary used by Browsershot. ### Signature `setNpmBinary(string $path)` ### Example ```php Browsershot::html('Foo') ->setNpmBinary('/usr/local/bin/npm'); ``` ``` -------------------------------- ### Injecting a script with evaluateOnNewDocument Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/evaluating-a-script-before-page-load Executes a script statement on every page navigation before the page's own scripts run. ```php Browsershot::url('https://example.com') ->evaluateOnNewDocument('window.myFlag = true') ->save($pathToImage); ``` -------------------------------- ### Configure Browsershot timeout Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/setting-the-timeout Adjust the default 60-second timeout by chaining the timeout method to the Browsershot instance. ```php Browsershot::url('https://example.com') ->timeout(120) ->save($pathToImage); ``` -------------------------------- ### Submit a form using type and click Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/typing-on-the-page Combine type and click methods to fill out a form and trigger a submission before saving a screenshot. ```php Browsershot::url('https://example.com') ->type('#firstName', 'My name') ->click('#submit') ->delay($millisecondsToWait) ->save($pathToImage); ``` -------------------------------- ### Capture a screenshot with delay Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Use setDelay to pause execution before capturing the screenshot. ```php Browsershot::url('https://example.com') ->setDelay($delayInMilliseconds) ->save($pathToImage); ``` -------------------------------- ### Creating Accessible PDFs Source: https://spatie.be/docs/browsershot/v4/usage/creating-pdfs Generate a tagged PDF for improved accessibility. ```php Browsershot::html($someHtml) ->taggedPdf() ->save('example.pdf'); ``` -------------------------------- ### Simulate clicks on elements Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/clicking-on-the-page Use the click method to interact with elements by selector, supporting custom mouse buttons and click counts. ```php Browsershot::url('https://example.com') ->click('#selector1') // Right click 5 times on #selector2, each click lasting 200 milliseconds. ->click('#selector2', 'right', 5, 200) ``` -------------------------------- ### Inject custom CSS Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Use setOption with addStyleTag to apply custom CSS styles to the page. ```php Browsershot::url('https://example.com') ->setOption('addStyleTag', json_encode(['content' => 'body{ font-size: 14px; }'])) ->save($pathToImage); ``` -------------------------------- ### Set Node Environment Variables Source: https://spatie.be/docs/browsershot/v4/requirements Define custom environment variables for the node process. ```php Browsershot::html('Foo') ->setNodeEnv(['NODE_ENV' => 'production']) ``` -------------------------------- ### Add Chromium Arguments Source: https://spatie.be/docs/browsershot/v4/requirements Pass custom flags to Chromium. Arguments are automatically prefixed with --. ```php Browsershot::html('Foo') ->addChromiumArguments([ 'some-argument-without-a-value', 'keyed-argument' => 'argument-value', ]); ``` ```php Browsershot::html('Foo') ->addChromiumArguments([ 'font-render-hinting' => 'none', ]); ``` -------------------------------- ### Browsershot::pdf() Source: https://spatie.be/docs/browsershot/v4/usage/creating-pdfs Method to output the generated PDF directly to the browser. ```APIDOC ## Browsershot::pdf() ### Description Outputs the generated PDF content directly to the browser. ``` -------------------------------- ### Wait for network idle Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Ensure all resources are loaded by waiting for a period of inactivity in network connections. ```php Browsershot::url('https://example.com') ->waitUntilNetworkIdle() ->save($pathToImage); ``` -------------------------------- ### Set Node Module Path Source: https://spatie.be/docs/browsershot/v4/requirements Specify an alternative directory for node_modules. ```php Browsershot::html('Foo') ->setNodeModulePath("/path/to/my/project/node_modules/") ``` -------------------------------- ### Sending a POST request with Browsershot Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/sending-post-requests Use the post method to send data as application/x-www-form-urlencoded to the specified URL. ```php Browsershot::url('https://example.com') ->post(['foo' => 'bar']) ... ``` -------------------------------- ### Resize the screenshot Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Define custom window dimensions for the captured screenshot. ```php Browsershot::url('https://example.com') ->windowSize(640, 480) ->save($pathToImage); ``` -------------------------------- ### Bypass command line overflow with writeOptionsToFile Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/writing-options-to-a-file Use this method when passing a large number of options to Puppeteer to avoid command line character limits. ```php Browsershot::url('https://example.com') ->writeOptionsToFile() ... ``` -------------------------------- ### Authenticate Browsershot requests Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/using-http-authentication Use the authenticate method to provide credentials for protected URLs. ```php Browsershot::url('https://example.com') ->authenticate('username', 'password') ... ``` -------------------------------- ### Connect to a remote Chrome instance Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/connection-to-a-remote-chrome-instance Use setRemoteInstance to specify the IP and port of a remote Chromium instance configured with --remote-debugging-port. ```php Browsershot::url('https://example.com') ->setRemoteInstance('1.2.3.4', 9222) ... ``` -------------------------------- ### Select an element for screenshot Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Capture a specific DOM element using a CSS selector. ```php Browsershot::url('https://example.com') ->select('.some-selector', $selectorIndex) ->save($pathToImage); ``` -------------------------------- ### setChromePath(string $path) Source: https://spatie.be/docs/browsershot/v4/requirements Sets the path to the chrome or chromium executable. ```APIDOC ## setChromePath ### Description Sets an alternative chrome or chromium executable path. ### Signature `setChromePath(string $path)` ### Example ```php Browsershot::html('Foo') ->setChromePath("/path/to/my/chrome"); ``` ``` -------------------------------- ### Inject custom JavaScript Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Use setOption with addScriptTag to execute custom JavaScript on the page. ```php Browsershot::url('https://example.com') ->setOption('addScriptTag', json_encode(['content' => 'alert("Hello World")'])) ->save($pathToImage); ``` -------------------------------- ### Output PDF directly to browser Source: https://spatie.be/docs/browsershot/v4/usage/creating-pdfs Use the pdf method to stream the generated PDF content directly to the browser. ```php $pdf = Browsershot::url('https://example.com')->pdf() ``` -------------------------------- ### setBinPath(string $path) Source: https://spatie.be/docs/browsershot/v4/requirements Sets an alternative path for the script source. ```APIDOC ## setBinPath ### Description Sets an alternative path for the script source. ### Signature `setBinPath(string $path)` ### Example ```php Browsershot::html('Foo') ->setBinPath("/path/to/my/project/my_script.js"); ``` ``` -------------------------------- ### Clip the screenshot Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Capture only a specific rectangular portion of the page. ```php Browsershot::url('https://example.com') ->clip($x, $y, $width, $height) ->save($pathToImage); ``` -------------------------------- ### Retrieve console messages Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/getting-console-ouput Use the consoleMessages method to capture all console output as an array. ```php $consoleMessages = Browsershot::url('https://example.com')->consoleMessages(); // returns an array ``` -------------------------------- ### Evaluate JavaScript in page Source: https://spatie.be/docs/browsershot/v4/usage/creating-html Executes a JavaScript expression within the page context, optionally after applying browser configurations like device scale factor. ```php Browsershot::url('https://example.com') ->deviceScaleFactor(2) ->evaluate("window.devicePixelRatio"); // returns 2 ``` -------------------------------- ### Browsershot::setEnvironmentOptions Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/passing-environment-variables-to-the-browser Sets custom environment variables that affect the browser instance used by Browsershot. ```APIDOC ## setEnvironmentOptions(array $options) ### Description Sets custom environment variables for the browser instance. ### Parameters - **$options** (array) - Required - An associative array of environment variable names and their values. ### Example ```php Browsershot::url('https://example.com') ->setEnvironmentOptions(['TZ' => 'Pacific/Auckland']); ``` ``` -------------------------------- ### setNodeBinary(string $path) Source: https://spatie.be/docs/browsershot/v4/requirements Sets the path to the node binary. ```APIDOC ## setNodeBinary ### Description Sets the path to the node binary used by Browsershot. ### Signature `setNodeBinary(string $path)` ### Example ```php Browsershot::html('Foo') ->setNodeBinary('/usr/local/bin/node'); ``` ``` -------------------------------- ### Disable Sandboxing in Browsershot Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/disable-sandboxing Use the noSandbox method to disable sandboxing for Browsershot instances. ```php Browsershot::url('https://example.com') ->noSandbox() ... ``` -------------------------------- ### Saving PDFs from URLs or HTML Source: https://spatie.be/docs/browsershot/v4/usage/creating-pdfs Methods to generate PDF files from a URL or raw HTML content. ```php // a pdf will be saved Browsershot::url('https://example.com')->save('example.pdf'); ``` ```php Browsershot::url('https://example.com')->savePdf('example.pdf'); ``` ```php Browsershot::html($someHtml)->savePdf('example.pdf'); ``` -------------------------------- ### Block specific domains Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Prevent connections to entire domains to optimize screenshot creation speed. ```php $domainsList = array("googletagmanager.com", "googlesyndication.com", "doubleclick.net", "google-analytics.com"); Browsershot::url('https://example.com') ->blockDomains($domainsList) ->save($pathToImage); ``` -------------------------------- ### Browsershot::post Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/sending-post-requests The post method allows sending a POST request to the specified URL with form data. The request is sent using the application/x-www-form-urlencoded content type. ```APIDOC ## Browsershot::post ### Description Sends a POST request to the configured URL with the provided data. ### Method POST ### Parameters - **data** (array) - Required - An associative array of key-value pairs to be sent as form data. ### Request Example ```php Browsershot::url('https://example.com') ->post(['foo' => 'bar']); ``` ``` -------------------------------- ### Browsershot::consoleMessages() Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/getting-console-ouput Retrieves an array of console messages captured during the page load process. ```APIDOC ## Browsershot::consoleMessages() ### Description Retrieves all console output generated by the browser while visiting a URL. The method returns an array of messages. ### Method PHP Method ### Signature `public function consoleMessages(): array` ### Return Value Returns an array of arrays, where each item contains: - **type** (string) - The type of output (e.g., 'log', 'error'). - **message** (string) - The content of the console message. - **location** (array) - Information about the trigger source, typically containing a 'url' key. ### Example ```php $consoleMessages = Browsershot::url('https://example.com')->consoleMessages(); ``` ``` -------------------------------- ### Configuring PDF Paper Size Source: https://spatie.be/docs/browsershot/v4/usage/creating-pdfs Set custom dimensions for the PDF output. ```php Browsershot::html($someHtml) ->paperSize($width, $height) ->save('example.pdf'); ``` -------------------------------- ### Retrieve triggered network requests Source: https://spatie.be/docs/browsershot/introduction Fetches an array of all network requests triggered by the page during rendering. ```php $requests = Browsershot::url('https://example.com') ->triggeredRequests(); foreach ($requests as $request) { $url = $request['url']; //https://example.com/ } ``` -------------------------------- ### Retrieve and display redirect history Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/read-redirect-history Use redirectHistory() to fetch an array of redirect data and iterate through the results to inspect URLs, status codes, and headers. ```php $redirects = Browsershot::url('https://www.spatie.be') ->redirectHistory(); foreach ($redirects as $redirect) { print $redirect['url'] . PHP_EOL; print $redirect['status'] . PHP_EOL; print $redirect['reason'] . PHP_EOL; foreach ($redirect['headers'] as $name => $value) { print $name . ' : ' . $value . PHP_EOL; } print PHP_EOL; } ``` -------------------------------- ### Set cookies for a request Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/using-cookies Use the useCookies method to pass an associative array of cookie keys and values to the request. ```php Browsershot::url('https://example.com') ->useCookies(['Cookie-Key' => 'Cookie-Value']) ... ``` ```php Browsershot::url('https://example.com') ->useCookies(['Cookie-Key' => 'Cookie-Value'], 'ui.example.com') ... ``` -------------------------------- ### Add custom headers with setExtraHttpHeaders Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/adding-extra-headers-to-every-request Use this method to pass an associative array of header names and values to every request made by the instance. ```php Browsershot::url('https://example.com') ->setExtraHttpHeaders(['Custom-Header-Name' => 'Custom-Header-Value']) ... ``` -------------------------------- ### setNodeEnv(array $env) Source: https://spatie.be/docs/browsershot/v4/requirements Sets custom environment variables for the node process. ```APIDOC ## setNodeEnv ### Description Sets custom environment variables that the node process should run with. ### Signature `setNodeEnv(array $env)` ### Example ```php Browsershot::html('Foo') ->setNodeEnv(['NODE_ENV' => 'production']); ``` ``` -------------------------------- ### Set a custom user agent Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/setting-the-user-agent Use the userAgent method to define the browser identification string sent during the request. ```php Browsershot::url('https://example.com') ->userAgent('My Special Snowflake Browser 1.0') ->save($pathToImage); ``` -------------------------------- ### Set base URL for HTML content Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/using-url-for-html-content Use setContentUrl to provide a base URL for relative paths when rendering HTML strings. ```php Browsershot::html('... relative paths to fetch ...') ->setContentUrl('https://www.example.com') ... ``` -------------------------------- ### addChromiumArguments(array $arguments) Source: https://spatie.be/docs/browsershot/v4/requirements Passes custom arguments to the Chromium instance. ```APIDOC ## addChromiumArguments ### Description Passes custom arguments to Chromium. Arguments are automatically prefixed with '--'. ### Signature `addChromiumArguments(array $arguments)` ### Example ```php Browsershot::html('Foo') ->addChromiumArguments([ 'some-argument-without-a-value', 'keyed-argument' => 'argument-value', ]); ``` ``` -------------------------------- ### Hide page background Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Capture a screenshot while ignoring the website's background. ```php Browsershot::url('https://example.com') ->hideBackground() ->save($pathToImage); ``` -------------------------------- ### Browsershot::redirectHistory() Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/read-redirect-history Retrieves the history of redirects encountered during the page load process. ```APIDOC ## Browsershot::redirectHistory() ### Description Returns an array of redirects encountered by the browser. Each entry contains the URL, HTTP status, reason, and headers. ### Method `redirectHistory()` ### Returns - **array** - A collection of redirect objects, each containing: - **url** (string) - The URL of the redirect. - **status** (int) - The HTTP status code. - **reason** (string) - The HTTP reason phrase. - **headers** (array) - An associative array of HTTP headers. ### Example ```php $redirects = Browsershot::url('https://www.spatie.be') ->redirectHistory(); foreach ($redirects as $redirect) { print $redirect['url'] . PHP_EOL; print $redirect['status'] . PHP_EOL; print $redirect['reason'] . PHP_EOL; foreach ($redirect['headers'] as $name => $value) { print $name . ' : ' . $value . PHP_EOL; } } ``` ``` -------------------------------- ### setNodeModulePath(string $path) Source: https://spatie.be/docs/browsershot/v4/requirements Sets an alternative path for node_modules. ```APIDOC ## setNodeModulePath ### Description Sets an alternative source for node_modules. ### Signature `setNodeModulePath(string $path)` ### Example ```php Browsershot::html('Foo') ->setNodeModulePath("/path/to/my/project/node_modules/"); ``` ``` -------------------------------- ### Ignore HTTPS errors in Browsershot Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/ignore-https-errors Use this method to bypass SSL certificate validation errors when accessing a URL. ```php Browsershot::url('https://example.com') ->ignoreHttpsErrors() ... ``` -------------------------------- ### Retrieve failed requests with Browsershot Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/getting-failed-requests Call the failedRequests method on a Browsershot instance to obtain an array of failed network requests. ```php $consoleMessages = Browsershot::url('https://example.com')->failedRequests(); // returns an array ``` -------------------------------- ### setExtraNavigationHttpHeaders Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/adding-extra-headers-to-the-navigational-request Adds custom HTTP headers to the initial navigational request. Note that these headers are only applied to the main page request and not to external resources. ```APIDOC ## setExtraNavigationHttpHeaders ### Description Adds custom HTTP headers to the navigational HTTP request. These headers are applied to the main page being rendered. ### Method PHP Method ### Signature `setExtraNavigationHttpHeaders(array $headers)` ### Parameters - **headers** (array) - Required - An associative array where keys are header names and values are header values. ### Example ```php Browsershot::url('https://example.com') ->setExtraNavigationHttpHeaders(['Custom-Header-Name' => 'Custom-Header-Value']); ``` ``` -------------------------------- ### Set PDF orientation to landscape Source: https://spatie.be/docs/browsershot/v4/usage/creating-pdfs Use the landscape method to change the PDF orientation. ```php Browsershot::html($someHtml) ->landscape() ->save('example.pdf'); ``` -------------------------------- ### Set PDF scale Source: https://spatie.be/docs/browsershot/v4/usage/creating-pdfs Adjust the scale of the PDF output, which must be a value between 0.1 and 2. ```php Browsershot::html($someHtml) ->scale(0.5) ->save('example.pdf'); ``` -------------------------------- ### Browsershot::useCookies Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/using-cookies Sets cookies for the Browsershot request. You can optionally specify the domain to register the cookies to. ```APIDOC ## Browsershot::useCookies ### Description Sets cookies to be used in the Browsershot request. Optionally, a domain can be specified to restrict the cookies to that domain. ### Method `useCookies(array $cookies, string $domain = null)` ### Parameters - **$cookies** (array) - Required - An associative array of cookie keys and values. - **$domain** (string) - Optional - The domain to register the cookies to. ### Example ```php // Basic usage Browsershot::url('https://example.com') ->useCookies(['Cookie-Key' => 'Cookie-Value']); // With domain Browsershot::url('https://example.com') ->useCookies(['Cookie-Key' => 'Cookie-Value'], 'ui.example.com'); ``` ``` -------------------------------- ### Setting PDF Margins Source: https://spatie.be/docs/browsershot/v4/usage/creating-pdfs Define margins for the top, right, bottom, and left sides of the PDF. ```php Browsershot::html($someHtml) ->margins($top, $right, $bottom, $left) ->save('example.pdf'); ``` -------------------------------- ### setIncludePath(string $path) Source: https://spatie.be/docs/browsershot/v4/requirements Sets the include path for command execution. ```APIDOC ## setIncludePath ### Description Modifies the include path used when executing commands. ### Signature `setIncludePath(string $path)` ### Example ```php Browsershot::html('Foo') ->setIncludePath('$PATH:/usr/local/bin'); ``` ``` -------------------------------- ### Set extra navigation HTTP headers Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/adding-extra-headers-to-the-navigational-request Applies custom headers to the primary URL request. These headers do not propagate to external assets loaded by the page. ```php Browsershot::url('https://example.com') ->setExtraNavigationHttpHeaders(['Custom-Header-Name' => 'Custom-Header-Value']) ... ``` -------------------------------- ### Export specific pages Source: https://spatie.be/docs/browsershot/v4/usage/creating-pdfs Define a print range to export only specific pages of the document. ```php Browsershot::html($someHtml) ->pages('1-5, 8, 11-13') ->save('example.pdf'); ``` -------------------------------- ### Wait for a DOM selector Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Use waitForSelector to pause until a specific element appears on the page. ```php Browsershot::url('https://example.com') ->waitForSelector('#my_selector') ->save($pathToImage); ``` -------------------------------- ### Wait for a JavaScript function Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Use waitForFunction to pause until a JavaScript expression evaluates to true. ```php Browsershot::url('https://example.com') ->waitForFunction('window.innerWidth < 100', $pollingInMilliseconds, $timeoutInMilliseconds) ->save($pathToImage); ``` -------------------------------- ### Prevent unsuccessful responses in Browsershot Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/prevent-unsuccessful-responses Use this method to ensure that Browsershot throws an exception when the requested URL returns an unsuccessful response. ```php Browsershot::url('https://example.com') ->preventUnsuccessfulResponse() ... ``` -------------------------------- ### setExtraHttpHeaders Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/adding-extra-headers-to-every-request Adds custom HTTP headers to the navigational HTTP request and all resources that make up the page. ```APIDOC ## setExtraHttpHeaders(array $headers) ### Description Adds custom HTTP headers to the navigational HTTP request and all resources that make up the page. ### Parameters - **headers** (array) - Required - An associative array where keys are header names and values are header values. ``` -------------------------------- ### Type text into a selector Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/typing-on-the-page Use the type method to input text into a specific element identified by a CSS selector. ```php Browsershot::url('https://example.com') ->type('#selector1', 'Hello, is it me you are looking for?') ``` -------------------------------- ### Block specific URLs Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Prevent connections to specific URLs to improve performance by blocking trackers or ads. ```php $urlsList = array("example.com/cm-notify?pi=outbrain", "sync.outbrain.com/cookie-sync?p=bidswitch"); Browsershot::url('https://example.com') ->blockUrls($urlsList) ->save($pathToImage); ``` -------------------------------- ### Disable CORS security in Browsershot Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/fixing-cors-options Use the --disable-web-security argument to bypass CORS restrictions during page capture. ```php Browsershot::url('https://example.com') ->setOption('args', ['--disable-web-security']) ->save($pathToImage); ``` -------------------------------- ### Retrieve body HTML after JavaScript execution Source: https://spatie.be/docs/browsershot/introduction Returns the HTML content of the page body after all JavaScript has finished executing. ```php Browsershot::url('https://example.com')->bodyHtml(); // returns the html of the body ``` -------------------------------- ### Change dropdown value Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/changing-the-value-of-a-dropdown Use selectOption to set the value of a dropdown identified by a CSS selector. ```php Browsershot::url('https://example.com') ->selectOption('#selector1', '100') ``` -------------------------------- ### Disable images Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Remove all images and img elements from the captured page. ```php Browsershot::url('https://example.com') ->disableImages() ->save($pathToImage); ``` -------------------------------- ### Dismiss JavaScript dialogs Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Automatically close alerts, prompts, and confirmations to prevent rendering blocks. ```php Browsershot::url('https://example.com') ->dismissDialogs() ->save($pathToImage); ``` -------------------------------- ### Disable JavaScript Source: https://spatie.be/docs/browsershot/v4/usage/creating-images Completely disable JavaScript execution during page capture. ```php Browsershot::url('https://example.com') ->disableJavascript() ->save($pathToImage); ``` -------------------------------- ### failedRequests() Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/getting-failed-requests Retrieves an array of failed network requests encountered while loading a page. ```APIDOC ## failedRequests() ### Description Returns an array containing details of all failed network requests encountered during the page load. ### Returns - **array** - An array of associative arrays, where each item contains: - `status` (integer): The HTTP status code of the failed request. - `url` (string): The URL that failed to load. ### Example ```php $failedRequests = Browsershot::url('https://example.com')->failedRequests(); ``` ``` -------------------------------- ### preventUnsuccessfulResponse() Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/prevent-unsuccessful-responses Configures the Browsershot instance to throw an error if the page response is unsuccessful. ```APIDOC ## preventUnsuccessfulResponse() ### Description Configures the Browsershot instance to throw an error when the page response is unsuccessful. ### Usage ```php Browsershot::url('https://example.com') ->preventUnsuccessfulResponse() ``` ``` -------------------------------- ### Disable URL capturing in Browsershot Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/performance Use this method to prevent Browsershot from capturing requested addresses, reducing memory consumption when processing documents with many data URLs. ```php Browsershot ::html('More data urls exists in this document') ->disableCaptureURLs() ; ``` -------------------------------- ### Disable HTTP redirects in Browsershot Source: https://spatie.be/docs/browsershot/v4/miscellaneous-options/disabling-redirects Use this method to prevent Browsershot from following redirects when loading a URL. ```php Browsershot::url('http://www.spatie.be') ->disableRedirects() ... ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.