SkillAgentSearch skills...

Chrome

Instrument headless chrome/chromium instances from PHP

Install / Use

/learn @chrome-php/Chrome
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

Chrome PHP

Latest Stable Version License

This library lets you start playing with chrome/chromium in headless mode from PHP.

Can be used synchronously and asynchronously!

Features

  • Open Chrome or Chromium browser from php
  • Create pages and navigate to pages
  • Take screenshots
  • Evaluate javascript on the page
  • Make PDF
  • Emulate mouse
  • Emulate keyboard
  • Always IDE friendly

Happy browsing!

Requirements

Requires PHP 7.4-8.5 and a Chrome/Chromium 65+ executable.

Note that the library is only tested on Linux but is compatible with macOS and Windows.

Installation

The library can be installed with Composer and is available on packagist under chrome-php/chrome:

$ composer require chrome-php/chrome

Usage

It uses a simple and understandable API to start Chrome, to open pages, take screenshots, crawl websites... and almost everything that you can do with Chrome as a human.

use HeadlessChromium\BrowserFactory;

$browserFactory = new BrowserFactory();

// starts headless Chrome
$browser = $browserFactory->createBrowser();

try {
    // creates a new page and navigate to an URL
    $page = $browser->createPage();
    $page->navigate('http://example.com')->waitForNavigation();

    // get page title
    $pageTitle = $page->evaluate('document.title')->getReturnValue();

    // screenshot - Say "Cheese"! 😄
    $page->screenshot()->saveToFile('/foo/bar.png');

    // pdf
    $page->pdf(['printBackground' => false])->saveToFile('/foo/bar.pdf');
} finally {
    // bye
    $browser->close();
}

Using different Chrome executable

When starting, the factory will look for the environment variable "CHROME_PATH" to use as the Chrome executable. If the variable is not found, it will try to guess the correct executable path according to your OS or use "chrome" as the default.

You are also able to explicitly set up any executable of your choice when creating a new object. For instance "chromium-browser":

use HeadlessChromium\BrowserFactory;

// replace default 'chrome' with 'chromium-browser'
$browserFactory = new BrowserFactory('chromium-browser');

Debugging

The following example disables headless mode to ease debugging

use HeadlessChromium\BrowserFactory;

$browserFactory = new BrowserFactory();

$browser = $browserFactory->createBrowser([
    'headless' => false, // disable headless mode
]);

Other debug options:

[
    'connectionDelay' => 0.8,            // add 0.8 second of delay between each instruction sent to Chrome,
    'debugLogger'     => 'php://stdout', // will enable verbose mode
]

About debugLogger: this can be any of a resource string, a resource, or an object implementing LoggerInterface from Psr\Log (such as monolog or apix/log).

API

Browser Factory

Options set directly in the createBrowser method will be used only for a single browser creation. The default options will be ignored.

use HeadlessChromium\BrowserFactory;

$browserFactory = new BrowserFactory();
$browser = $browserFactory->createBrowser([
    'windowSize'   => [1920, 1000],
    'enableImages' => false,
]);

// this browser will be created without any options
$browser2 = $browserFactory->createBrowser();

Options set using the setOptions and addOptions methods will persist.

$browserFactory->setOptions([
    'windowSize' => [1920, 1000],
]);

// both browser will have the same 'windowSize' option
$browser1 = $browserFactory->createBrowser();
$browser2 = $browserFactory->createBrowser();

$browserFactory->addOptions(['enableImages' => false]);

// this browser will have both the 'windowSize' and 'enableImages' options
$browser3 = $browserFactory->createBrowser();

$browserFactory->addOptions(['enableImages' => true]);

// this browser will have the previous 'windowSize', but 'enableImages' will be true
$browser4 = $browserFactory->createBrowser();

Available options

Here are the options available for the browser factory:

| Option name | Default | Description | |---------------------------|---------|----------------------------------------------------------------------------------------------------| | connectionDelay | 0 | Delay to apply between each operation for debugging purposes | | customFlags | none | An array of flags to pass to the command line. Eg: ['--option1', '--option2=someValue'] | | debugLogger | null | A string (e.g "php://stdout"), or resource, or PSR-3 logger instance to print debug messages | | disableNotifications | false | Disable browser notifications | | enableImages | true | Toggles loading of images | | envVariables | none | An array of environment variables to pass to the process (example DISPLAY variable) | | headers | none | An array of custom HTTP headers | | headless | true | Enable or disable headless mode | | ignoreCertificateErrors | false | Set Chrome to ignore SSL errors | | keepAlive | false | Set to true to keep alive the Chrome instance when the script terminates | | noSandbox | false | Enable no sandbox mode, useful to run in a docker container | | noProxyServer | false | Don't use a proxy server, always make direct connections. Overrides other proxy settings. | | proxyBypassList | none | Specifies a list of hosts for whom we bypass proxy settings and use direct connections | | proxyServer | none | Proxy server to use. usage: 127.0.0.1:8080 (authorisation with credentials does not work) | | sendSyncDefaultTimeout | 5000 | Default timeout (ms) for sending sync messages | | startupTimeout | 30 | Maximum time in seconds to wait for Chrome to start | | userAgent | none | User agent to use for the whole browser (see page API for alternative) | | userDataDir | none | Chrome user data dir (default: a new empty dir is generated temporarily) | | userCrashDumpsDir | none | The directory crashpad should store dumps in (crash reporter will be enabled automatically) | | windowSize | none | Size of the window. usage: $width, $height - see also Page::setViewport | | excludedSwitches | none | An array of Chrome flags that should be removed from the default set (example --enable-automation) |

Persistent Browser

This example shows how to share a single instance of Chrome for multiple scripts.

The first time the script is started we use the browser factory in order to start Chrome, afterwards we save the uri to connect to this browser in the file system.

The next calls to the script will read the uri from that file in order to connect to the Chrome instance instead of creating a new one. If Chrome was closed or crashed, a new instance is started again.

use \HeadlessChromium\BrowserFactory;
use \HeadlessChromium\Exception\BrowserConnectionFailed;

$socketFile = '/tmp/chrome-php-demo-socket';

// path to the file to store websocket's uri
$socket = \file_get_contents($socketFile);

try {
    $browser = BrowserFactory::connectToBrowser($socket);
} catch (BrowserConnectionFailed $e) {
    // The browser was probably closed, start it again
    $factory = new BrowserFactory();
    $browser = $factory->createBrowser([
        'keepAlive' => true,
    ]);

    // save the uri to be able to connect again to browser
    \file_put_contents($socketFile, $browser->getSocketUri(), LOCK_EX);
}

Browser API

Create a new page (tab)

$page = $browser->createPage();

Get opened pages (tabs)

$pages = $browser->getPages();

Close the browser

$browser->close();

Set a script to evaluate before every page created by this browser will navigate

$browser->setPagePreScript('// Simulate navigator permissions;
const originalQuery = window.navigator.permissions.query;
window.navigator.permissions.query = (parameters) => (
    parameters.name === 'notifications' ?
        Promise.resolve({ state: Notification.permission }) :
        originalQuery(parameters)
);');

Page API

Navigate to an URL

// navigate
$navigation = $page->navigate('http://example.com');

// wait for the page to be loaded
$navigation->waitForNavigation();

When using $navigation->waitForNavigation() you will wait for 30sec until the page event "loaded" is triggered. You can change the timeout or the event to listen for:

use HeadlessChromium\Page;

// wait 10secs for the event "DOMContentLoaded" to be triggered
$navigation->waitForNavigation(Page::DOM_CONTENT_LOADED, 10000);

Available events (in the order they trigger):

  • Page::DOM_CONTENT_LOADED: dom has completely loaded
  • ``Page::FI
View on GitHub
GitHub Stars2.6k
CategoryDevelopment
Updated2d ago
Forks313

Languages

PHP

Security Score

95/100

Audited on Mar 24, 2026

No findings