Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 11 additions & 16 deletions docs/examples/drag-and-drop.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,17 +129,17 @@
');

// Take initial screenshot
$page->screenshot('/tmp/drag-drop-initial.png');
echo "Initial screenshot saved: /tmp/drag-drop-initial.png\n";
$screenshotPath = $page->screenshotAuto('drag-drop-initial');
echo "Initial screenshot saved: $screenshotPath\n";

// Example 1: Basic drag and drop
echo "Performing basic drag and drop...\n";
$draggableItem = $page->locator('#item1');
$dropZone = $page->locator('#dropzone1');

$draggableItem->dragTo($dropZone);
$page->screenshot('/tmp/drag-drop-after-item1.png');
echo "Screenshot after dragging item1: /tmp/drag-drop-after-item1.png\n";
$screenshotPath = $page->screenshotAuto('drag-drop-after-item1');
echo "Screenshot after dragging item1: $screenshotPath\n";

// Example 2: Drag with specific positions
echo "Performing drag with specific source and target positions...\n";
Expand All @@ -150,8 +150,8 @@
'sourcePosition' => ['x' => 50, 'y' => 50], // Center of source element
'targetPosition' => ['x' => 100, 'y' => 100], // Center of target element
]);
$page->screenshot('/tmp/drag-drop-after-item2.png');
echo "Screenshot after dragging item2 with positions: /tmp/drag-drop-after-item2.png\n";
$screenshotPath = $page->screenshotAuto('drag-drop-after-item2');
echo "Screenshot after dragging item2 with positions: $screenshotPath\n";

// Example 3: Force drag (bypass actionability checks)
echo "Performing forced drag and drop...\n";
Expand All @@ -161,8 +161,8 @@
'force' => true,
'timeout' => 5000,
]);
$page->screenshot('/tmp/drag-drop-after-item3.png');
echo "Screenshot after forced drag of item3: /tmp/drag-drop-after-item3.png\n";
$screenshotPath = $page->screenshotAuto('drag-drop-after-item3');
echo "Screenshot after forced drag of item3: $screenshotPath\n";

// Example 4: Verify drop results
echo "Verifying drop results...\n";
Expand All @@ -176,17 +176,12 @@
echo "Drop Zone 2 contains $zone2Count items\n";

// Take final screenshot
$page->screenshot('/tmp/drag-drop-final.png');
echo "Final screenshot saved: /tmp/drag-drop-final.png\n";
$screenshotPath = $page->screenshotAuto('drag-drop-final');
echo "Final screenshot saved: $screenshotPath\n";

// Cleanup
$page->close();
$browser->close();

echo "\nDrag and drop examples completed successfully!\n";
echo "Screenshots saved in /tmp/ directory:\n";
echo "- drag-drop-initial.png\n";
echo "- drag-drop-after-item1.png\n";
echo "- drag-drop-after-item2.png\n";
echo "- drag-drop-after-item3.png\n";
echo "- drag-drop-final.png\n";
echo "Screenshots saved in the configured screenshot directory.\n";
4 changes: 4 additions & 0 deletions docs/guide/core-concepts.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,7 @@ $signInButton->click();

By understanding and using these four core concepts, you can build powerful, reliable, and maintainable browser
automation scripts and tests.

## Private browser output

Automatic screenshots and PDFs use a private, randomly named temporary directory unless `screenshotDir` is configured. Generated names include the hostname, without URL credentials, paths, query parameters, or fragments. `pdfContent()` returns bytes directly without creating a temporary file.
4 changes: 4 additions & 0 deletions docs/guide/handling-authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,7 @@ class ProfilePageTest extends AuthenticatedTestCase
* Use **UI Login** when you are specifically testing the login, password-reset, or logout features.
* Use **Reusing Authentication State** for all other tests that require an authenticated user. It will make your test
suite significantly faster and more stable.

## Saved state

Storage-state exports are written atomically with owner-only file permissions. Store them in a private directory, exclude them from version control, and remove them when the sessions are no longer needed. Filesystem access controls on Windows must also restrict access to the owning account.
7 changes: 6 additions & 1 deletion src/API/APIRequestContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

namespace Playwright\API;

use Playwright\Browser\StorageStateFile;
use Playwright\Exception\ProtocolErrorException;
use Playwright\Tracing\Tracing;
use Playwright\Tracing\TracingInterface;
Expand Down Expand Up @@ -137,7 +138,7 @@ public function storageState(?string $path = null): array
$response = $this->transport->send([
'action' => 'api.storageState',
'contextId' => $this->contextId,
'path' => $path,
'path' => null,
]);

$storageState = $response['storageState'] ?? null;
Expand All @@ -152,6 +153,10 @@ public function storageState(?string $path = null): array
}
}

if (null !== $path) {
StorageStateFile::save($path, $result);
}

return $result;
}

Expand Down
6 changes: 5 additions & 1 deletion src/Browser/BrowserContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,7 @@ public function storageState(?string $path = null): array
$response = $this->transport->send([
'action' => 'context.storageState',
'contextId' => $this->contextId,
'options' => $path ? ['path' => $path] : [],
'options' => [],
]);

if (!is_array($response['storageState'])) {
Expand All @@ -508,6 +508,10 @@ public function storageState(?string $path = null): array
}
}

if (null !== $path) {
StorageStateFile::save($path, $storageState);
}

return $storageState;
}

Expand Down
10 changes: 1 addition & 9 deletions src/Browser/StorageState.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,15 +114,7 @@ public function toArray(): array

public function saveToFile(string $filePath): void
{
$directory = \dirname($filePath);
if (!\is_dir($directory) && !\mkdir($directory, 0755, true) && !\is_dir($directory)) {
throw new RuntimeException(\sprintf('Failed to create directory: %s', $directory));
}

$result = \file_put_contents($filePath, $this->toJson(JSON_PRETTY_PRINT));
if (false === $result) {
throw new RuntimeException(\sprintf('Failed to write storage state file: %s', $filePath));
}
StorageStateFile::save($filePath, $this->toArray());
}

public function isEmpty(): bool
Expand Down
67 changes: 67 additions & 0 deletions src/Browser/StorageStateFile.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

declare(strict_types=1);

/*
* This file is part of the community-maintained Playwright PHP project.
* It is not affiliated with or endorsed by Microsoft.
*
* (c) 2025-Present - Playwright PHP - https://github.com/playwright-php
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Playwright\Browser;

use Playwright\Exception\RuntimeException;
use Playwright\Filesystem\PrivateDirectory;

/** @internal */
final class StorageStateFile
{
/** @param array<string, mixed> $state */
public static function save(string $path, array $state): void
{
$json = json_encode($state, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
$parent = dirname($path);

if (!is_dir($parent) && !mkdir($parent, 0700, true) && !is_dir($parent)) {
throw new RuntimeException(sprintf('Failed to create directory: %s', $parent));
}

$directory = PrivateDirectory::create($parent);
$temporary = $directory.DIRECTORY_SEPARATOR.'state.json';

try {
self::write($temporary, $json);

if (!rename($temporary, $path)) {
throw new RuntimeException(sprintf('Failed to save storage state file: %s', $path));
}
} finally {
if (file_exists($temporary)) {
unlink($temporary);
}

rmdir($directory);
}
}

private static function write(string $path, string $json): void
{
$stream = fopen($path, 'xb');

if (false === $stream) {
throw new RuntimeException('Failed to create storage state file.');
}

try {
if (!chmod($path, 0600) || strlen($json) !== fwrite($stream, $json)) {
throw new RuntimeException('Failed to write private storage state file.');
}
} finally {
fclose($stream);
}
}
}
3 changes: 2 additions & 1 deletion src/Configuration/PlaywrightConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
namespace Playwright\Configuration;

use Playwright\Browser\BrowserType;
use Playwright\Filesystem\PrivateDirectory;
use Psr\Log\LoggerInterface;

/**
Expand Down Expand Up @@ -75,7 +76,7 @@ public function getScreenshotDirectory(): string
return $this->screenshotDir;
}

return rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.'playwright';
return PrivateDirectory::artifacts();
}

/**
Expand Down
39 changes: 39 additions & 0 deletions src/Filesystem/PrivateDirectory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

/*
* This file is part of the community-maintained Playwright PHP project.
* It is not affiliated with or endorsed by Microsoft.
*
* (c) 2025-Present - Playwright PHP - https://github.com/playwright-php
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Playwright\Filesystem;

use Playwright\Exception\RuntimeException;

/** @internal */
final class PrivateDirectory
{
private static ?string $artifactDirectory = null;

public static function create(string $parent): string
{
$directory = rtrim($parent, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.'playwright-'.bin2hex(random_bytes(16));

if (!mkdir($directory, 0700) || !chmod($directory, 0700)) {
throw new RuntimeException('Failed to create a private Playwright directory.');
}

return $directory;
}

public static function artifacts(): string
{
return self::$artifactDirectory ??= self::create(sys_get_temp_dir());
}
}
31 changes: 10 additions & 21 deletions src/Page/Page.php
Original file line number Diff line number Diff line change
Expand Up @@ -470,7 +470,7 @@ public function screenshotAuto(string $suffix = '', array|ScreenshotOptions $opt
$milliseconds = sprintf('%03d', ($now - floor($now)) * 1000);

$urlSlug = ScreenshotHelper::slugifyUrl($currentUrl, 20);
$suffixSlug = $suffix ? '-'.ScreenshotHelper::slugifyUrl($suffix, 20) : '';
$suffixSlug = $suffix ? '-'.ScreenshotHelper::slugifyName($suffix, 20) : '';

$extension = ScreenshotHelper::extensionFor($options['type'] ?? null);
$filename = sprintf('%s_%s_%s%s.%s', $datetime, $milliseconds, $urlSlug, $suffixSlug, $extension);
Expand Down Expand Up @@ -528,31 +528,20 @@ public function pdfContent(array|PdfOptions $options = []): string
throw new RuntimeException('Do not provide a "path" option when requesting inline PDF content.');
}

$directory = $this->getPdfDirectory();
ScreenshotHelper::ensureDirectoryExists($directory);
$response = $this->sendCommand('pdf', ['options' => $options->toArray()]);
$binary = $response['binary'] ?? null;

$tempPath = tempnam($directory, 'pw_pdf_');
if (false === $tempPath) {
throw new RuntimeException('Failed to allocate a temporary PDF file.');
if (!is_string($binary)) {
throw new ProtocolErrorException('Invalid PDF content response', 0);
}

// Remove the placeholder so Playwright can create the file fresh.
@unlink($tempPath);
$content = base64_decode($binary, true);

try {
$this->pdf($tempPath, $options);

$content = file_get_contents($tempPath);
if (false === $content) {
throw new RuntimeException('Unable to read generated PDF content.');
}

return $content;
} finally {
if (file_exists($tempPath)) {
@unlink($tempPath);
}
if (false === $content) {
throw new ProtocolErrorException('Invalid PDF content encoding', 0);
}

return $content;
}

/**
Expand Down
9 changes: 8 additions & 1 deletion src/Screenshot/ScreenshotHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,14 @@ public static function generateFilename(string $url, string $directory, string $
*/
public static function slugifyUrl(string $url, int $maxLength = 40): string
{
$slug = preg_replace('#^(https?://)?(www\.)?#i', '', $url);
$host = parse_url($url, PHP_URL_HOST);

return self::slugifyName(is_string($host) ? $host : '', $maxLength);
}

public static function slugifyName(string $name, int $maxLength = 40): string
{
$slug = preg_replace('#^www\.#i', '', $name);
if (null === $slug) {
$slug = 'invalid-url';
}
Expand Down
5 changes: 3 additions & 2 deletions tests/Integration/Page/ScreenshotIntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -224,14 +224,15 @@ public function itGeneratesUniqueFilenames(): void
}

#[Test]
public function itHandlesDifferentUrlsInFilenames(): void
public function itUsesTheHostnameWithoutTheUrlPathInFilenames(): void
{
$this->page->goto($this->routeUrl('/page2.html'));

$screenshotPath = $this->page->screenshot();
$basename = basename($screenshotPath);

$this->assertStringContainsString('page2', $basename);
$this->assertStringContainsString('localhost', $basename);
$this->assertStringNotContainsString('page2', $basename);
$this->assertFileExists($screenshotPath);
$this->assertPngFileIsValid($screenshotPath);
}
Expand Down
11 changes: 9 additions & 2 deletions tests/Unit/API/APIRequestContextTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,11 +170,18 @@ public function testStorageStateReturnsCookiesAndOrigins(): void
->with([
'action' => 'api.storageState',
'contextId' => 'context_1',
'path' => '/tmp/state.json',
'path' => null,
])
->willReturn(['storageState' => $state]);

$this->assertSame($state, $this->context->storageState('/tmp/state.json'));
$path = sys_get_temp_dir().'/playwright-api-state-'.bin2hex(random_bytes(8)).'.json';

try {
$this->assertSame($state, $this->context->storageState($path));
$this->assertSame($state, json_decode((string) file_get_contents($path), true));
} finally {
@unlink($path);
}
}

public function testStorageStateRejectsAnInvalidResponse(): void
Expand Down
13 changes: 10 additions & 3 deletions tests/Unit/Browser/BrowserContextTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -399,12 +399,19 @@ public function testStorageState(): void
->with([
'action' => 'context.storageState',
'contextId' => 'context_1',
'options' => ['path' => '/tmp/state.json'],
'options' => [],
])
->willReturn(['storageState' => $expectedState]);

$result = $this->context->storageState('/tmp/state.json');
$this->assertEquals($expectedState, $result);
$path = sys_get_temp_dir().'/playwright-state-'.bin2hex(random_bytes(8)).'.json';

try {
$result = $this->context->storageState($path);
$this->assertEquals($expectedState, $result);
$this->assertSame($expectedState, json_decode((string) file_get_contents($path), true));
} finally {
@unlink($path);
}
}

public function testStorageStateWithoutPath(): void
Expand Down
Loading
Loading