Chrome PHP

repository·1.16·Indexed 25 days ago

https://github.com/chrome-php/chrome

A PHP library for controlling Chrome or Chromium browsers in headless mode. It supports synchronous and asynchronous operations for web crawling, screenshotting, PDF generation, and JavaScript evaluation. Key features include BrowserFactory for instance configuration, DOM element interaction, mouse and keyboard control, and the ability to connect to persistent Chrome instances via WebSockets.

Tokens
4.7K
Snippets
11
Records
32
Agent score
83%

What's inside chrome-php/chrome

  1. Configure the Chrome executable path

    1.16

    You can specify which Chrome/Chromium executable to use in three ways:

    1. Environment Variable: Set the CHROME_PATH environment variable.
    2. Constructor Argument: Pass the executable path or name directly to the BrowserFactory constructor.
    3. Default Behavior: If no path is provided, the factory attempts to guess the path based on your OS or defaults to chrome.
    use HeadlessChromiumrowserFactory;
    
    // replace default 'chrome' with 'chromium-browser'
    $browserFactory = new BrowserFactory('chromium-browser');
  2. Basic Usage of Chrome PHP

    1.16

    Use BrowserFactory to start a headless Chrome instance, create pages, navigate to URLs, evaluate JavaScript, take screenshots, and generate PDFs.

    use HeadlessChromiumrowserFactory;
    
    $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();
    }
  3. Debug Chrome PHP sessions

    1.16

    To debug your automation, you can disable headless mode or enable verbose logging.

    Use the following options when calling createBrowser():

    • 'headless' => false: Disables headless mode so you can see the browser window.
    • 'connectionDelay' => float: Adds a delay (in seconds) between instructions sent to Chrome.
    • 'debugLogger' => mixed: Enables verbose mode. Accepts a resource string (e.g., 'php://stdout'), a resource, or a Psr\Log\LoggerInterface implementation.
    use HeadlessChromiumrowserFactory;
    
    $browserFactory = new BrowserFactory();
    
    $browser = $browserFactory->createBrowser([
        'headless' => false,            // disable headless mode
        'connectionDelay' => 0.8,       // add 0.8 second of delay between each instruction
        'debugLogger'     => 'php://stdout', // enable verbose mode
    ]);
  4. Connect to a persistent Chrome instance

    1.16

    To share a single Chrome instance across multiple scripts, save the WebSocket URI to a file. Subsequent scripts can then connect to the existing instance using BrowserFactory::connectToBrowser() instead of starting a new one.

    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);
    }
  5. Take screenshots (Area, Full-page, or Viewport)

    1.16

    Capture screenshots in png, jpeg, or webp formats. You can capture the viewport, a specific clipped area, or the entire page layout.

    // standard screenshot
    $screenshot = $page->screenshot([
        'format'  => 'jpeg',
        'quality' => 80,
        'optimizeForSpeed' => true
    ]);
    $screenshot->saveToFile('/some/place/file.jpg');
    
    // full-page screenshot
    $screenshot = $page->screenshot([
        'captureBeyondViewport' => true,
        'clip' => $page->getFullPageClip(),
        'format' => 'jpeg',
    ]);
  6. Evaluate JavaScript on a page

    1.16

    Execute arbitrary JavaScript in the context of the current page using $page->evaluate(). To call a specific function with arguments, use $page->callFunction().

    // evaluate script in the browser
    $evaluation = $page->evaluate('document.documentElement.innerHTML');
    $value = $evaluation->getReturnValue();
    
    // call a function with arguments
    $evaluation = $page->callFunction(
        "function(a, b) {\n    window.foo = a + b;\n}",
        [1, 2]
    );
    $value = $evaluation->getReturnValue();
  7. Navigate to a URL and wait for load

    1.16

    Use $page->navigate() to load a URL. You can then use waitForNavigation() to wait for the page to reach a specific state. By default, it waits for the Page::LOAD event for 30 seconds.

    Available Navigation Events:

    • Page::DOM_CONTENT_LOADED: DOM is completely loaded.
    • Page::FIRST_CONTENTFUL_PAINT: First non-white content element is painted.
    • Page::FIRST_IMAGE_PAINT: First image is painted.
    • Page::FIRST_MEANINGFUL_PAINT: Primary content is visible.
    • Page::FIRST_PAINT: Any pixel is painted.
    • Page::INIT: Connection to DevTools protocol is initialized.
    • Page::INTERACTIVE_TIME: Scripts finished loading and main thread is not blocked.
    • Page::LOAD: (Default) Page and all resources are loaded.
    • Page::NETWORK_IDLE: Page loaded and no network activity for at least 500ms.
    use HeadlessChromium\Page;
    
    // navigate
    $navigation = $page->navigate('http://example.com');
    
    // wait 10secs for the event "DOMContentLoaded" to be triggered
    $navigation->waitForNavigation(Page::DOM_CONTENT_LOADED, 10000);
  8. Control the Mouse and Keyboard

    1.16

    The Mouse and Keyboard APIs allow for user-like interaction.

    Mouse:

    • move(x, y): Move cursor.
    • click(): Perform a click.
    • scrollDown(px) / scrollUp(px): Scroll the page.
    • find(selector): Finds an element via CSS selector and moves the mouse to a random position over it.

    Keyboard:

    • typeText('text'): Type text.
    • press('key') / release('key'): Handle key combinations (e.g., Ctrl+C).
    • setKeyInterval(ms): Add delay between keystrokes to impersonate a real user.
  9. Manage Cookies

    1.16

    You can set cookies for specific domains or the current page, and retrieve all cookies or cookies for the current page.

    use HeadlessChromium\Cookies\Cookie;
    
    // set cookies for a given domain
    $page->setCookies([
        Cookie::create('name', 'value', [
            'domain' => 'example.com',
            'expires' => time() + 3600
        ])
    ])->await();
    
    // get cookies for the current page
    $cookies = $page->getCookies();
    $cookieBar = $cookies->findOneBy('name', 'bar');
  10. Configure BrowserFactory options

    1.16

    The BrowserFactory allows you to create browser instances with specific configurations. You can pass options directly to createBrowser() for single-use settings, or use setOptions() and addOptions() to persist settings across multiple browser creations.

    Single-use options:

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

    Persistent options:

    // Sets options for all subsequent browser creations
    $browserFactory->setOptions(['windowSize' => [1920, 1000]]);
    
    // Appends options to existing persistent options
    $browserFactory->addOptions(['enableImages' => false]);
    use HeadlessChromium\BrowserFactory;
    
    $browserFactory = new BrowserFactory();
    $browser = $browserFactory->createBrowser([
        'windowSize'   => [1920, 1000],
        'enableImages' => false,
    ]);