### Launch Chromium Browser and Get Context Source: https://github.com/playwright-php/playwright/blob/main/docs/guide/core-concepts.md Launches a Chromium browser instance and returns a default BrowserContext. Ensure Playwright is installed and the browser binaries are available. ```php false]); // ... do stuff ... // Closing the context will also close the associated browser. $context->close(); ``` -------------------------------- ### Local Development Setup for Playwright PHP Source: https://github.com/playwright-php/playwright/blob/main/README.md Commands for setting up the local development environment for Playwright PHP. Installs PHP dependencies and the bundled Playwright server, then downloads browsers and system dependencies. ```bash composer install # installs PHP deps and the bundled Playwright server vendor/bin/playwright-install --with-deps # downloads browsers + optional system deps ``` -------------------------------- ### Install Playwright PHP and Browsers Source: https://context7.com/playwright-php/playwright/llms.txt Install the Playwright PHP library via Composer and download the necessary browser binaries. Use the `--with-deps` flag for CI environments or fresh machines to include system dependencies. ```bash composer require playwright-php/playwright ``` ```bash vendor/bin/playwright-install --browsers ``` ```bash vendor/bin/playwright-install --with-deps ``` ```bash PLAYWRIGHT_BROWSERS_PATH=/path/to/.playwright-browsers vendor/bin/playwright-install --browsers ``` -------------------------------- ### GitHub Actions Workflow for Playwright PHP Tests Source: https://context7.com/playwright-php/playwright/llms.txt This YAML workflow automates the setup and execution of Playwright PHP tests in a GitHub Actions CI/CD pipeline. It includes steps for checking out code, setting up PHP and Node.js, installing dependencies, installing Playwright browsers with system dependencies, and running PHPUnit tests. ```yaml jobs: tests: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: shivammathur/setup-php@v2 with: php-version: '8.2' - uses: actions/setup-node@v4 with: node-version: '20' - run: composer install --no-interaction --prefer-dist # Install Playwright browsers with system dependencies - run: vendor/bin/playwright-install --with-deps # Run PHPUnit tests - run: vendor/bin/phpunit --colors=always # Optional: Cache Playwright browsers # Cache location: ~/.cache/ms-playwright ``` -------------------------------- ### Install Playwright Browsers Source: https://github.com/playwright-php/playwright/blob/main/README.md Installs the necessary Playwright browsers (Chromium, Firefox, WebKit) for your project. Use --with-deps to also install OS dependencies. ```bash vendor/bin/playwright-install --browsers ``` ```bash vendor/bin/playwright-install --with-deps ``` ```bash vendor/bin/playwright-install --dry-run --with-deps ``` -------------------------------- ### GitHub Actions CI Workflow for Playwright PHP Source: https://github.com/playwright-php/playwright/blob/main/README.md Example workflow snippet for setting up a CI environment on GitHub Actions to run Playwright PHP tests. Installs Node.js, Composer dependencies, and Playwright browsers. ```yaml jobs: tests: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: shivammathur/setup-php@v2 with: php-version: '8.2' - uses: actions/setup-node@v4 with: node-version: '20' - run: composer install --no-interaction --prefer-dist # Install browsers for Playwright PHP - run: vendor/bin/playwright-install --with-deps - run: vendor/bin/phpunit --colors=always ``` -------------------------------- ### Start External Browser Server with Playwright Protocol Source: https://github.com/playwright-php/playwright/blob/main/docs/guide/connect-browser.md Launches a browser server instance using Playwright. Copy the printed ws://... value to use as the connection endpoint. ```php launchServer('chromium', ['headless' => true]); echo $server->wsEndpoint().PHP_EOL; while (true) { sleep(1); } ``` -------------------------------- ### Install Playwright Browsers Source: https://github.com/playwright-php/playwright/blob/main/docs/guide/getting-started.md Download the necessary browser binaries for Playwright to function. This command ensures the Playwright server is updated and fetches the latest browser versions. ```bash vendor/bin/playwright-install --browsers ``` ```bash vendor/bin/playwright-install --with-deps ``` -------------------------------- ### Quick Start: Open Page and Get Title Source: https://github.com/playwright-php/playwright/blob/main/README.md Launches a Chromium browser, navigates to a URL, and retrieves the page title. Ensure you have autoload.php included and the Playwright namespace imported. ```php true]); $page = $context->newPage(); $page->goto('https://example.com'); echo $page->title().PHP_EOL; // Example Domain $context->close(); ``` -------------------------------- ### PHPUnit Integration with PlaywrightTestCaseTrait Source: https://github.com/playwright-php/playwright/blob/main/README.md Minimal example demonstrating how to use the PlaywrightTestCaseTrait for E2E tests with PHPUnit. Ensure PHPUnit 10.0+ is installed. Call setUpPlaywright() and tearDownPlaywright() in your test case's setup and teardown methods. ```php setUpPlaywright(); } protected function tearDown(): void { $this->tearDownPlaywright(); parent::tearDown(); } public function test_title_is_correct(): void { $this->page->goto('https://example.com'); $this->expect($this->page)->toHaveTitle('Example Domain'); } } ``` -------------------------------- ### Start Chrome with Remote Debugging Enabled Source: https://github.com/playwright-php/playwright/blob/main/docs/guide/connect-browser.md Launches Google Chrome with the remote debugging port enabled. This is required for connecting via CDP. ```bash "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --remote-debugging-port=9222 --user-data-dir=/tmp/chrome-pw ``` -------------------------------- ### Install Playwright PHP Library Source: https://github.com/playwright-php/playwright/blob/main/docs/guide/getting-started.md Use Composer to add the Playwright PHP library to your project dependencies. ```bash composer require playwright-php/playwright ``` -------------------------------- ### Install Route Server Source: https://github.com/playwright-php/playwright/blob/main/docs/contributing/testing.md Use `RouteServerTestTrait` to fulfill requests directly via Playwright routing, avoiding the need for a PHP built-in web server. The `routeUrl` helper provides stable URLs for routed content. ```php use Playwright\Tests\Support\RouteServerTestTrait; // Inside a test case using PlaywrightTestCaseTrait $this->installRouteServer($this->page, [ '/index.html' => '

Hello

', '/script.js' => 'window.ok = true;', ]); $this->page->goto($this->routeUrl('/index.html')); ``` -------------------------------- ### Perform XHR GET Request Source: https://github.com/playwright-php/playwright/blob/main/tests/Fixtures/html/network.html Initiates an XMLHttpRequest (XHR) GET request to retrieve user data. Updates the UI with the response or an error. ```javascript document.getElementById('xhr-get').addEventListener('click', () => { const result = document.getElementById('xhr-result'); const xhr = new XMLHttpRequest(); xhr.open('GET', '/api/users'); xhr.onload = () => { result.textContent = 'XHR GET: ' + xhr.responseText; }; xhr.onerror = () => { result.textContent = 'XHR Error'; }; xhr.send(); }); ``` -------------------------------- ### Run First Playwright PHP Script Source: https://github.com/playwright-php/playwright/blob/main/docs/guide/getting-started.md Execute a basic Playwright script to navigate to a website, capture a screenshot, and generate a PDF. Ensure you have run 'composer install' and 'vendor/bin/playwright-install --browsers' first. ```php newPage(); // Navigate to a website. $page->goto('https://example.com'); // Get the title of the page and print it to the console. echo $page->title() . PHP_EOL; // Outputs: "Example Domain" // Take a screenshot and save it as 'screenshot.png'. $page->screenshot('screenshot.png'); // Export the page to PDF on disk. $page->pdf('invoice.pdf', ['format' => 'A4']); // Or grab the PDF bytes directly without keeping files around. $pdfBytes = $page->pdfContent(); file_put_contents('inline-invoice.pdf', $pdfBytes); // Close the browser context and all its pages. $context->close(); ``` -------------------------------- ### Load Authentication State in Playwright PHP Tests Source: https://github.com/playwright-php/playwright/blob/main/docs/guide/handling-authentication.md Configure your PlaywrightTestCase to use saved authentication state by overriding the setUp method to load the storage state. This allows tests to start in an authenticated state. ```php context->loadStorageState(__DIR__.'/../auth.json'); } } ``` ```php page->goto('https://my-app.com/profile'); expect($this->page->locator('.username-display'))->toHaveText('test-user'); } } ``` -------------------------------- ### Enable Playwright Debugging via Environment Variable (PHP) Source: https://github.com/playwright-php/playwright/blob/main/docs/inspector.md Set the PWDEBUG environment variable to 1 to enable Playwright debugging for your PHP script. This is an alternative to programmatic setup. ```bash PWDEBUG=1 php your_script.php ``` -------------------------------- ### JavaScript Cookie Management and Authentication Check Source: https://github.com/playwright-php/playwright/blob/main/tests/Fixtures/html/auth.html Utility functions for getting cookies and checking/updating authentication status. Sets up event listeners for login and logout actions. ```javascript function getCookie(name) { const value = ` ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(';').shift(); return null; } function checkAuth() { const authToken = getCookie('auth_token'); const username = getCookie('username'); if (authToken) { document.getElementById('auth-status').textContent = 'Authenticated'; document.getElementById('login-form').style.display = 'none'; document.getElementById('logout-btn').style.display = 'block'; document.getElementById('user-info').style.display = 'block'; document.getElementById('user-info').textContent = 'Logged in as: ' + username; } else { document.getElementById('auth-status').textContent = 'Not authenticated'; document.getElementById('login-form').style.display = 'block'; document.getElementById('logout-btn').style.display = 'none'; document.getElementById('user-info').style.display = 'none'; } } document.getElementById('login-form').addEventListener('submit', (e) => { e.preventDefault(); const username = document.getElementById('username').value; const password = document.getElementById('password').value; // Simple mock authentication if (username && password) { // Set auth cookies document.cookie = `auth_token=token_${Math.random().toString(36).substr(2, 9)}; path=/`; document.cookie = `username=${username}; path=/`; document.cookie = `session_id=sess_${Date.now()}; path=/`; checkAuth(); } }); document.getElementById('logout-btn').addEventListener('click', () => { // Clear auth cookies document.cookie = 'auth_token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'; document.cookie = 'username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'; document.cookie = 'session_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'; checkAuth(); }); // Check auth on load checkAuth(); ``` -------------------------------- ### Interact with Frames using page.frameLocator() Source: https://github.com/playwright-php/playwright/blob/main/docs/guide/advanced-recipes.md Use `$page->frameLocator()` to get a `FrameLocator` for interacting with elements inside an `