通过 Chrome DevTools 协议与 Chrome 或无头 Chrome 通信

此包的规范存储库似乎已丢失,因此该包已被冻结。

v0.3.3 2018-08-14 13:22 UTC

This package is auto-updated.

Last update: 2023-05-29 00:52:23 UTC


README

DevTools PHP 库允许 PHP 通过 Chrome DevTools 协议与 Chrome 或无头 Chrome 通信。

示例

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');

开发和测试

构建镜像并安装依赖项。

docker-compose build
docker-compose run --rm php composer install

运行测试。

# All tests
docker-compose run --rm php phpunit
# A single test
docker-compose run --rm php phpunit test/tests/ClientTest.php

PHPUnit 将在 coverage 目录中生成代码覆盖率报告。

参考

有关 DevTools API 的详细信息以及如何在 PHP 中处理 WebSocket,请参阅以下资源