chrome-php / chrome

Instrument headless chrome/chromium instances from PHP
MIT License
2.2k stars 269 forks source link

getting the initial page would be nice #631

Open divinity76 opened 2 weeks ago

divinity76 commented 2 weeks ago

When a browser is created, a default page is also created, and the first call to browser->createPage() creates a second page. Single-page scripts (which I assume is the majority of scripts) could benefit from accessing the initial page, it would be nice if we could get a

$factory = new \HeadlessChromium\BrowserFactory("chromium-browser");
$browser = $factory->createBrowser();
$page = $browser->getInitialPage();

which would presumably be somewhat faster and use less resources than $page = $browser->createPage();

just a "nice to have" feature, speeding up single-page scripts, but not important.

Also I checked if this initial page is available from $browser->getPages(); - it isn't. (have not looked into why.)

ethaniel commented 1 week ago

I've noticed that in headless mode, $browser->getPages() returns an empty array, so you do need to create a page. When headless is off, $browser->getPages() returns the initial page.

ethaniel commented 1 week ago

Simple workaround:

$pages = $browser->getPages();
if (isset($pages[0])) {
    $page = $pages[0];
} else {
    $page = $browser->createPage();
}