Skip to content

Commit

Permalink
added demo for persisting browser #42
Browse files Browse the repository at this point in the history
  • Loading branch information
gsouf committed Oct 13, 2018
1 parent d19ec0c commit a6e7b32
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

## 0.3.0

> *20xx-xx-xx* (not released)
> *2018-08-13*
> Make a crawl instance sharable among multiple scripts
Expand Down
50 changes: 50 additions & 0 deletions examples/persistent-browser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

/*
* This exemple 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,
* afterwhat we save the uri to connect to this browser in the file system.
*
* 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.
*/

require(__DIR__ . '/../vendor/autoload.php');

// path to the file to store websocket's uri
$socketFile = '/tmp/chrome-php-demo-socket';

// initialize $browser variable
$browser = null;

// try to connect to chrome instance if it exists
if (file_exists($socketFile)) {
$socket = file_get_contents($socketFile);

try {
$browser = \HeadlessChromium\BrowserFactory::connectToBrowser($socket, [
'debugLogger' => 'php://stdout'
]);
} catch (\HeadlessChromium\Exception\BrowserConnectionFailed $e) {
// The browser was probably closed
// Keep $browser null and start it again bellow
}
}

// if $browser is null then create a new chrome instance
if (!$browser) {
$factory = new \HeadlessChromium\BrowserFactory();
$browser = $factory->createBrowser([
'headless' => false,
'keepAlive' => true
]);

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

// do something with the browser
$page = $browser->createPage();

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

0 comments on commit a6e7b32

Please sign in to comment.