americanreading / devtools
Communicate with Chrome or headless Chrome via the Chrome DevTools protocol
This package's canonical repository appears to be gone and the package has been frozen as a result.
v0.3.3
2018-08-14 13:22 UTC
Requires
- php: ^7
- symfony/process: ^3
- wrench/wrench: ^2
Requires (Dev)
- phpunit/phpunit: ^6
This package is auto-updated.
Last update: 2023-05-29 00:52:23 UTC
README
The DevTools PHP library allows PHP to communicate with Chrome or headless Chrome via the Chrome DevTools protocol.
Example
use AmericanReading\DevTools\Browser;
use AmericanReading\DevTools\Client;
// Launch an instance of Chrome with default options.
$browser = new Browser();
$browser->start();
// Retrieve the WebSocket address for the browser.
$address = $browser->getWebSocketAddress();
// Connect a Client to the browser via the WebSocket address.
$client = new Client($address);
$client->connect();
// Create "target" and "session." This allows the Client to send messages
// in the context of a specific tab.
$client->createSession();
// Send messages to set cookies and navigate to a new page.
// Note that send() is a synchronous method that sends a message to Chrome and
// waits for a corresponding response.
$client->send('Network.setCookie', [
'name' => 'my-cookie',
'value' => 'some-value',
'domain' => '.example.com'
]);
$client->send('Page.navigate', [
'url' => 'https://www.example.com/some/page'
]);
// In order to wait until the page is finished loading, send a "Page.enable"
// message, then wait to receieve a "Page.loadEventFired" event. Disable events
// afterward to prevent Chrome from sending additional events to the Client.
$client->send('Page.enable');
$client->waitForEvent('Page.loadEventFired');
$client->send('Page.disable');
// Send a message to create the PDF. The response will include a base64-encoded
// string as $response['result']['data'].
$response = $client->send('Page.printToPDF', [
'landscape' => true,
'displayHeaderFooter' => false,
'printBackground' => true
]);
$data = $response['result']['data'];
$decoded = base64_decode($data);
file_put_contents($outputFilePath, $decoded);
// Detach from the target and session to send messages directly to the browser.
$client->detachFromSession();
// Send a message to close the browser.
$client->send('Browser.close');
Development and Testing
Build images and install dependencies.
docker-compose build
docker-compose run --rm php composer install
Run tests.
# All tests
docker-compose run --rm php phpunit
# A single test
docker-compose run --rm php phpunit test/tests/ClientTest.php
PHPUnit will generate code coverage report in the coverage
directory.
References
For detailed information on the DevTools API and working with WebSockers in PHP, see these resouces: