PHP code example of infostars / headless-chromium-php

1. Go to this page and download the library: Download infostars/headless-chromium-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

infostars / headless-chromium-php example snippets


    use HeadlessChromium\BrowserFactory;

    $browserFactory = new BrowserFactory();

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

    // 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');
    
    // bye
    $browser->close();

    use HeadlessChromium\BrowserFactory;

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

    use HeadlessChromium\BrowserFactory;

    $browserFactory = new BrowserFactory();

    $browser = $browserFactory->createBrowser([
        'headless'        => false,         // disable headless mode
        'connectionDelay' => 0.8,           // add 0.8 second of delay between each instruction sent to chrome,
        'debugLogger'     => 'php://stdout' // will enable verbose mode
    ]);

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

    $page = $browser->createPage();
    
    // destination can be specified
    $uri = 'http://example.com';
    $page = $browser->createPage($uri);

    $browser->close();

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

    $browser->setPagePreScript($script);

    // navigate
    $navigation = $page->navigate('http://example.com');
    
    // wait for the page to be loaded
    $navigation->waitForNavigation();

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

  use HeadlessChromium\Exception\OperationTimedOut;
  use HeadlessChromium\Exception\NavigationExpired;

  try {
    $navigation->waitForNavigation()
  } catch (OperationTimedOut $e) {
    // too long to load
  } catch (NavigationExpired $e) {
    // An other page was loaded
  }

    // navigate
    $navigation = $page->navigate('http://example.com');
        
    // wait for the page to be loaded
    $navigation->waitForNavigation();
    
    // evaluate script in the browser
    $evaluation = $page->evaluate('document.documentElement.innerHTML');
    
    // wait for the value to return and get it
    $value = $evaluation->getReturnValue();

    $evaluation = $page->callFunction(
      'function(a, b) {
          window.foo = a + b;
       }', 
      [1, 2]
    );
    
    $value = $evaluation->getReturnValue();

    $page->addScriptTag([
        'content' => file_get_contents('path/to/jquery.js')
    ])->waitForResponse();
    
    $page->evaluate('$(".my.element").html()');

    $page->addScriptTag([
        'url' => 'https://code.jquery.com/jquery-3.3.1.min.js'
    ])->waitForResponse();
    
    $page->evaluate('$(".my.element").html()');

    $script = 
     '// 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->addPreScript($script);

    $page->addPreScript($script, ['onLoad' => true]);

    $width = 600;
    $height = 300;
    $page->setViewportSize($width, $height)
        ->await(); // wait for operation to complete

    // navigate
    $navigation = $page->navigate('http://example.com');
        
    // wait for the page to be loaded
    $navigation->waitForNavigation();
    
    // take a screenshot
    $screenshot = $page->screenshot([
        'format'  => 'jpeg',  // default to 'png' - possible values: 'png', 'jpeg',
        'quality' => 80       // only if format is 'jpeg' - default 100 
    ]);
    
    // save the screenshot
    $screenshot->saveToFile('/some/place/file.jpg');


    use HeadlessChromium\Clip;

    // navigate
    $navigation = $page->navigate('http://example.com');
        
    // wait for the page to be loaded
    $navigation->waitForNavigation();
    
    // create a rectangle by specifying to left corner coordinates + width and height
    $x = 10;
    $y = 10;
    $width = 100;
    $height = 100;
    $clip = new Clip($x, $y, $width, $height);
    
    // take the screenshot (in memory binaries)
    $screenshot = $page->screenshot([
        'clip'  => $clip'
    ]);
    
    // save the screenshot
    $screenshot->saveToFile('/some/place/file.jpg');

    // navigate
    $navigation = $page->navigate('http://example.com');
        
    // wait for the page to be loaded
    $navigation->waitForNavigation();
    
    $options = [
                  'landscape'       => true,  // default to false
                  'printBackground' => true,   // default to false
                  'displayHeaderFooter' => true, // default to false
                  'preferCSSPageSize' => true, // default to false ( reads parameters directly from @page )
                  'marginTop' => 0.0, // defaults to ~0.4 (must be float, value in inches)
                  'marginBottom' => 1.4, // defaults to ~0.4 (must be float, value in inches)
                  'marginLeft' => 5.0, // defaults to ~0.4 (must be float, value in inches)
                  'marginRight' => 1.0 // defaults to ~0.4 (must be float, value in inches)
               ];
    
    // print as pdf (in memory binaries)
    $pdf = $page->pdf($options);
    
    // save the pdf
    $pdf->saveToFile('/some/place/file.pdf');
    
    // or directly output pdf without saving
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename=filename.pdf');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    
    echo base64_decode($pdf->getBase64());

    $page->mouse()
        ->move(10, 20)                              // Moves mouse to position x=10;y=20
        ->click()                                   // left click on position set above
        ->move(100, 200, ['steps' => 5])            // move mouse to x=100;y=200 in 5 equal steps
        ->click(['button' => Mouse::BUTTON_RIGHT];  // right click on position set above
        
    // given the last click was on a link, the next step will wait for the page to load after the link was clicked
    $page->waitForReload();

    use HeadlessChromium\Cookies\Cookie;

    $page = $browser->createPage();
    
    // example 1: set cookies for a given domain
    
    $page->setCookies([
        Cookie::create('name', 'value', [
            'domain' => 'example.com',
            'expires' => time() + 3600 // expires in 1 day
        ])
    ])->await();
    
    
    // example 2: set cookies for the current page
    
    $page->navigate('http://example.com')->waitForNavigation();
    
    $page->setCookies([
        Cookie::create('name', 'value', ['expires'])
    ])->await();
    

    use HeadlessChromium\Cookies\Cookie;

    $page = $browser->createPage();
    
    // example 1: get all cookies for the browser
    
    $cookies = $page->getAllCookies();
    
    // example 2: get cookies for the current page
    
    $page->navigate('http://example.com')->waitForNavigation();
    $cookies = $page->getCookies();
    
    // filter cookies with name == 'foo'
    $cookiesFoo = $cookies->filterBy('name', 'foo'); 

    // find first cookie with name == 'bar'
    $cookieBar = $cookies->findOneBy('name', 'bar');
    if ($cookieBar) {
        // do something
    }
    

$page->setUserAgent('my user agent');

  use HeadlessChromium\Communication\Connection;
  use HeadlessChromium\Communication\Message;

  // chrome devtools uri
  $webSocketUri = 'ws://127.0.0.1:9222/devtools/browser/xxx';

  // create a connection
  $connection = new Connection($webSocketUri);
  $connection->connect();

  // send method "Target.activateTarget"
  $responseReader = $connection->sendMessage(new Message('Target.activateTarget', ['targetId' => 'xxx']));

  // wait up to 1000ms for a response
  $response = $responseReader->waitForResponse(1000);

  if ($response) {
    // ok
  }else {
    // not ok
  }

  // given a target id
  $targetId = 'yyy';

  // create a session for this target (attachToTarget)
  $session = $connection->createSession($targetId);

  // send message to this target (Target.sendMessageToTarget)
  $response = $session->sendMessageSync(new Message('Page.reload'));

  $connection->setConnectionDelay(500); // wait for 500 ms between each operation to ease debugging

    use HeadlessChromium\Communication\Connection;
    use HeadlessChromium\Browser;

    // chrome devtools uri
    $webSocketUri = 'ws://127.0.0.1:9222/devtools/browser/xxx';

    // create connection given a web socket uri
    $connection = new Connection($webSocketUri);
    $connection->connect();

    // create browser
    $browser = new Browser($connection);