Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Chrome Laravel Package

chrome-php/chrome

Control headless Chrome from PHP. chrome-php/chrome launches Chromium/Chrome, lets you navigate pages, evaluate JavaScript, take screenshots/PDFs, intercept network events, and automate workflows via the DevTools protocol—ideal for scraping, testing, and rendering.

Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require chrome-php/chrome

Requires PHP 8.1+ and Chromium/Chrome installed on the system.

  1. First Use Case: Launch Headless Chrome

    use ChromePhp\Chrome\Chrome;
    
    $chrome = new Chrome();
    $chrome->launch([
        'headless' => true,
        'args' => ['--no-sandbox', '--disable-setuid-sandbox']
    ]);
    
    $tab = $chrome->createTab();
    $tab->navigate('https://example.com');
    
    // Wait for page to load
    $tab->waitForNavigation();
    
    // Capture screenshot
    $screenshot = $tab->screenshot();
    file_put_contents('screenshot.png', $screenshot);
    
    $chrome->close();
    
  2. Key Entry Points

    • Chrome::launch(): Start a Chrome instance.
    • Chrome::createTab(): Create a new tab.
    • Tab::navigate(): Load a URL.
    • Tab::waitFor*(): Wait for DOM/network conditions (e.g., waitForSelector, waitForNavigation).
    • Tab::evaluate(): Run JavaScript in the page context.
    • Tab::screenshot()/Tab::pdf(): Capture artifacts.
  3. Where to Look First

    • Official Documentation (if available).
    • src/ChromePhp/Chrome/ for core classes (Chrome, Tab, Page).
    • Example scripts in /tests for real-world usage patterns.

Implementation Patterns

Core Workflows

1. Scraping Dynamic Content

$chrome = new Chrome();
$chrome->launch(['headless' => true]);

$tab = $chrome->createTab();
$tab->navigate('https://example.com/dynamic-page');

$tab->waitForSelector('#dynamic-content'); // Wait for element to load
$content = $tab->evaluate('() => document.querySelector("#dynamic-content").innerText');
$chrome->close();

return $content;

2. Server-Side Rendering (SSR)

$chrome = new Chrome();
$chrome->launch(['headless' => true]);

$tab = $chrome->createTab();
$tab->navigate('https://example.com/ssr-page');
$tab->waitForNavigation();

$html = $tab->evaluate('() => document.documentElement.outerHTML');
$chrome->close();

return $html; // Use in Laravel views or APIs

3. Testing with Laravel

use ChromePhp\Chrome\Chrome;
use Illuminate\Support\Facades\Http;

public function testHeadless()
{
    $chrome = new Chrome();
    $chrome->launch(['headless' => true]);

    $tab = $chrome->createTab();
    $tab->navigate(url('/api/test-endpoint'));

    $tab->waitForSelector('body'); // Wait for API response to render
    $screenshot = $tab->screenshot();

    $chrome->close();

    // Assert screenshot or content
    Storage::put('test-screenshot.png', $screenshot);
}

4. Reusable Chrome Service (Laravel)

// app/Services/ChromeService.php
namespace App\Services;

use ChromePhp\Chrome\Chrome;

class ChromeService
{
    protected ?Chrome $chrome = null;

    public function getChrome(): Chrome
    {
        if (!$this->chrome) {
            $this->chrome = new Chrome();
            $this->chrome->launch(['headless' => true]);
        }
        return $this->chrome;
    }

    public function close(): void
    {
        $this->chrome?->close();
        $this->chrome = null;
    }
}

5. Handling Multiple Tabs

$chrome = new Chrome();
$chrome->launch(['headless' => true]);

$tabs = [];
foreach (['url1', 'url2', 'url3'] as $url) {
    $tab = $chrome->createTab();
    $tab->navigate($url);
    $tabs[] = $tab;
}

// Process tabs in parallel (e.g., with Laravel Queues)
foreach ($tabs as $tab) {
    $tab->waitForNavigation();
    $title = $tab->evaluate('() => document.title');
    // Store $title...
}

$chrome->close();

6. Configuring Chrome Options

$chrome->launch([
    'headless' => env('CHROME_HEADLESS', true),
    'args' => [
        '--disable-gpu',
        '--window-size=1920,1080',
        '--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    ],
    'timeout' => 30000, // 30 seconds
]);

7. Integrating with Laravel Queues

// app/Jobs/ScrapeJob.php
namespace App\Jobs;

use ChromePhp\Chrome\Chrome;
use Illuminate\Bus\Queueable;

class ScrapeJob implements Queueable
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function handle()
    {
        $chrome = new Chrome();
        $chrome->launch(['headless' => true]);

        try {
            $tab = $chrome->createTab();
            $tab->navigate('https://example.com/scrape');
            $data = $tab->evaluate('() => scrapeData()'); // Custom JS
            // Save $data to DB...
        } finally {
            $chrome->close();
        }
    }
}

8. Waiting for Network Conditions

$tab->navigate('https://example.com/api-heavy-page');
$tab->waitForNetworkIdle(); // Wait for network to settle
$tab->waitForSelector('.loaded-data'); // Wait for DOM update

9. Running JavaScript in Page Context

$tab->navigate('https://example.com');
$tab->waitForNavigation();

// Execute JS and return result
$results = $tab->evaluate(<<<'JS'
    () => {
        const data = [];
        document.querySelectorAll('.item').forEach(el => {
            data.push({
                text: el.textContent,
                href: el.href
            });
        });
        return data;
    }
JS);

// $results is now an array of objects

10. Generating PDFs

$tab->navigate('https://example.com/invoice');
$tab->waitForNavigation();

$pdf = $tab->pdf([
    'format' => 'A4',
    'margin' => ['top' => '1cm', 'right' => '1cm', 'bottom' => '1cm', 'left' => '1cm'],
]);

file_put_contents('invoice.pdf', $pdf);

Gotchas and Tips

Pitfalls

  1. Chrome/Chromium Installation

    • Ensure Chromium/Chrome is installed and accessible via which chromium or which chrome.
    • On Linux, install via:
      sudo apt-get install chromium-chromedriver
      
    • On macOS, use Homebrew:
      brew install chromedriver
      
  2. Sandboxing Issues

    • Headless Chrome often fails with sandbox errors. Add these args:
      'args' => ['--no-sandbox', '--disable-setuid-sandbox']
      
    • Security Note: Only use --no-sandbox in trusted environments (e.g., local development, CI).
  3. Memory Leaks

    • Always call $chrome->close() to free resources. Forgetting this can exhaust system memory.
    • For long-running processes (e.g., queues), use a service container (as shown in the Laravel example).
  4. Timeouts

    • Default timeouts are short (e.g., 30s for navigation). Increase with:
      $chrome->launch(['timeout' => 60000]); // 60 seconds
      
    • Use waitFor* methods with custom timeouts:
      $tab->waitForSelector('#element', 10000); // 10s timeout
      
  5. JavaScript Evaluation

    • evaluate() runs in the page context. Avoid window or document in the returned JS to prevent security errors.
    • Example of bad JS:
      () => window.someUnsafeFunction() // May throw "Access to 'window' denied"
      
    • Example of good JS:
      () => document.querySelector('.safe-element').textContent
      
  6. Headless vs. Non-Headless

    • Headless mode ('headless' => true) is faster but may miss some rendering issues.
    • For debugging, launch visibly:
      $chrome->launch(['headless' => false]);
      
  7. Viewport and Emulation

    • Set viewport before navigation:
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware