Skip to content
Merged
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
- WebP screenshots through `type: 'webp'` in `ScreenshotOptions` and `LocatorScreenshotOptions` (#206)
- `ScreenshotOptions::$style` applies CSS while a page screenshot is taken, like `LocatorScreenshotOptions::$style` (#210)
- `Page::screenshotAuto()` accepts `ScreenshotOptions`, like `Page::screenshot()` (#210)
- `PageEventHandlerInterface::onDownload()` receives each `Download` a page starts (#211)
- `PageInterface::waitForDownload()` runs an action and returns the `Download` it starts, with `path()`, `saveAs()`, `failure()`, `cancel()`, `delete()` and `createReadStream()` working end to end (#211)

### Changed
- `ScreenshotHelper::cleanupOldScreenshots()` and `getDirectoryInfo()` include `.jpeg`, `.jpg` and `.webp` files along with `.png`; cleanup now deletes old files of these formats (#208)
Expand Down
62 changes: 61 additions & 1 deletion bin/lib/handlers.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const fs = require('fs/promises');
const { logger, ErrorHandler, CommandRegistry, BaseHandler, PromiseUtils, FrameUtils, RouteUtils } = require('./core');
const { globalCoordinator } = require('./coordination');
const { PopupCoordinator } = require('./popup-coordinator');
Expand Down Expand Up @@ -460,6 +461,7 @@ class PageHandler extends BaseHandler {
frames: () => this.getFrames(page),
frame: () => this.getFrame(page, command),
waitForPopup: () => this.waitForPopup(page, command),
waitForDownload: () => this.waitForDownload(page, command),
bringToFront: () => page.bringToFront(),
ariaSnapshot: () => PromiseUtils.wrapValue(page.ariaSnapshot(command.options)),
hideHighlight: () => page.hideHighlight(),
Expand Down Expand Up @@ -706,6 +708,45 @@ class PageHandler extends BaseHandler {
return FrameUtils.selectorForNativeFrame(frame, mainFrame);
}

// Same callback coordination as waitForPopup: the listener is armed first,
// then PHP runs the action that starts the download.
async waitForDownload(page, command) {
const requestId = command.requestId || this.generateId('download_req');
const timeout = command.timeout ?? 30000;
const registerDownload = this.registerDownload;

globalCoordinator.registerAsyncCommand(requestId, [
{
name: 'setupListener',
handler: async () => {
const downloadPromise = page.waitForEvent('download', { timeout });
// PHP may still be running the action when this rejects. Observe it
// now; awaiting the promise in the next phase still throws it.
downloadPromise.catch(() => {});
return { downloadPromise };
},
waitForCallback: true,
callbackType: 'readyForAction'
},
{
name: 'waitForDownload',
handler: async (data) => {
const download = await data.downloadPromise;

return {
page: undefined,
downloadPromise: undefined,
timeout: undefined,
...registerDownload(download, page)
};
},
waitForCallback: false
}
]);

return await globalCoordinator.executeNextPhase(requestId, { page, timeout });
}

async waitForPopup(page, command) {
const timeout = command.timeout || 30000;
const requestId = command.requestId || this.generateId('popup_req');
Expand Down Expand Up @@ -1157,6 +1198,25 @@ class SelectorsHandler extends BaseHandler {
}
}

class DownloadHandler extends BaseHandler {
async handle(command, method) {
const download = this.validateResource(this.downloads, command.downloadId, 'Download');

const registry = CommandRegistry.create({
path: async () => ({ path: await download.path() }),
saveAs: () => download.saveAs(command.path),
// Not "error": the PHP transport reads that key as a failed command.
failure: async () => ({ failure: await download.failure() }),
cancel: () => download.cancel(),
delete: () => download.delete(),
readStream: async () => ({ stream: (await fs.readFile(await download.path())).toString('base64') })
});

const result = await ErrorHandler.safeExecute(() => this.executeWithRegistry(registry, method), { method, downloadId: command.downloadId });
return this.wrapResult(result);
}
}

class VideoHandler extends BaseHandler {
async handle(command, method) {
const video = this.validateResource(this.videos, command.videoId, 'Video');
Expand All @@ -1175,4 +1235,4 @@ class VideoHandler extends BaseHandler {
}
}

module.exports = { APIRequestHandler, ContextHandler, PageHandler, LocatorHandler, InteractionHandler, FrameHandler, JSHandleHandler, SelectorsHandler, VideoHandler };
module.exports = { APIRequestHandler, ContextHandler, PageHandler, LocatorHandler, InteractionHandler, FrameHandler, JSHandleHandler, SelectorsHandler, VideoHandler, DownloadHandler };
28 changes: 23 additions & 5 deletions bin/playwright-server.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const {chromium, firefox, webkit, request} = require('playwright');
const { logger, ErrorHandler, LspFraming, sendFramedResponse, CommandRegistry, NavigationRedirects, BaseHandler, RouteUtils } = require('./lib/core');
const { APIRequestHandler, ContextHandler, PageHandler, LocatorHandler, InteractionHandler, FrameHandler, JSHandleHandler, SelectorsHandler, VideoHandler } = require('./lib/handlers');
const { APIRequestHandler, ContextHandler, PageHandler, LocatorHandler, InteractionHandler, FrameHandler, JSHandleHandler, SelectorsHandler, VideoHandler, DownloadHandler } = require('./lib/handlers');
const { globalCoordinator } = require('./lib/coordination');

class PlaywrightServer extends BaseHandler {
Expand All @@ -24,16 +24,18 @@ class PlaywrightServer extends BaseHandler {
this.navigationRedirects = new NavigationRedirects();
this.servers = new Map();
this.videos = new Map();
this.downloads = new Map();
this.downloadIds = new WeakMap();
this.apiContexts = new Map();
this.counters = { api: 0, browser: 0, context: 0, page: 0, response: 0, route: 0, element: 0, server: 0, video: 0 };
this.counters = { api: 0, browser: 0, context: 0, page: 0, response: 0, route: 0, element: 0, server: 0, video: 0, download: 0, download_req: 0 };
}

initHandlers() {
const deps = {
contexts: this.contexts, contextThrottling: this.contextThrottling, pages: this.pages,
apiContexts: this.apiContexts, apiRequest: request,
pageContexts: this.pageContexts, dialogs: this.dialogs, elementHandles: this.elementHandles,
responses: this.responses, routes: this.routes, routeHandlers: this.routeHandlers, videos: this.videos, generateId: this.generateId.bind(this),
responses: this.responses, routes: this.routes, routeHandlers: this.routeHandlers, videos: this.videos, downloads: this.downloads, registerDownload: this.registerDownload.bind(this), generateId: this.generateId.bind(this),
navigationRedirects: this.navigationRedirects,
extractRequestData: this.extractRequestData.bind(this), serializeResponse: this.serializeResponse.bind(this),
serializeConsoleMessage: this.serializeConsoleMessage.bind(this),
Expand All @@ -49,6 +51,7 @@ class PlaywrightServer extends BaseHandler {
this.jsHandleHandler = new JSHandleHandler(deps);
this.selectorsHandler = new SelectorsHandler(deps);
this.videoHandler = new VideoHandler(deps);
this.downloadHandler = new DownloadHandler(deps);
}

async handleCommand(command) {
Expand Down Expand Up @@ -90,6 +93,7 @@ class PlaywrightServer extends BaseHandler {
credentials: () => this.contextHandler.handleCredentials(command, actionMethod),
screencast: () => this.pageHandler.handleScreencast(command, actionMethod),
video: () => this.videoHandler.handle(command, actionMethod),
download: () => this.downloadHandler.handle(command, actionMethod),
// Tracing actions are flat names (no dot), sent by the PHP Tracing class
tracingStart: () => this.contextHandler.handleTracing(command, 'start'),
tracingStartChunk: () => this.contextHandler.handleTracing(command, 'startChunk'),
Expand Down Expand Up @@ -169,9 +173,9 @@ class PlaywrightServer extends BaseHandler {
}

setupPageEventListeners(page, pageId) {
['console', 'dialog', 'request', 'response', 'requestfailed'].forEach(eventName => {
['console', 'dialog', 'request', 'response', 'requestfailed', 'download'].forEach(eventName => {
page.on(eventName, ErrorHandler.wrapHandler((eventData) => {
const params = this.formatEventParams(eventName, eventData);
const params = eventName === 'download' ? this.registerDownload(eventData, page) : this.formatEventParams(eventName, eventData);
sendFramedResponse({ objectId: pageId, event: eventName, params });
}));
});
Expand All @@ -195,6 +199,20 @@ class PlaywrightServer extends BaseHandler {
context.once('close', () => RouteUtils.forgetRoutes(this.routes, this.routeHandlers, contextId));
}

// One id per download, whether PHP learns about it from the page event or from
// waitForDownload(). The file lives as long as its browser context.
registerDownload(download, page) {
let downloadId = this.downloadIds.get(download);
if (!downloadId) {
downloadId = this.generateId('download');
this.downloadIds.set(download, downloadId);
this.downloads.set(downloadId, download);
page.context().once('close', () => this.downloads.delete(downloadId));
}

return { downloadId, suggestedFilename: download.suggestedFilename(), url: download.url() };
}

registerPage(page, contextId) {
const pageId = this.generateId('page');
this.pages.set(pageId, page);
Expand Down
2 changes: 1 addition & 1 deletion src/Download/Download.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public function failure(): ?string
'downloadId' => $this->downloadId,
]);

return isset($response['error']) && is_string($response['error']) ? $response['error'] : null;
return isset($response['failure']) && is_string($response['failure']) ? $response['failure'] : null;
}

public function page(): PageInterface
Expand Down
54 changes: 54 additions & 0 deletions src/Page/Options/WaitForDownloadOptions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?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\Page\Options;

final readonly class WaitForDownloadOptions
{
/**
* @param float|null $timeout Maximum time to wait for the download to start, in milliseconds. 30000 by default, 0 waits forever.
*/
public function __construct(
public ?float $timeout = null,
) {
}

/**
* @return array<string, mixed>
*/
public function toArray(): array
{
$options = [];
if (null !== $this->timeout) {
$options['timeout'] = $this->timeout;
}

return $options;
}

/**
* @param array<string, mixed>|self $options
*/
public static function from(array|self $options = []): self
{
if ($options instanceof self) {
return $options;
}

/** @var float|int|null $timeout */
$timeout = $options['timeout'] ?? null;

return new self(null === $timeout ? null : (float) $timeout);
}
}
37 changes: 37 additions & 0 deletions src/Page/Page.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
use Playwright\Console\ConsoleMessage;
use Playwright\Cookie;
use Playwright\Dialog\Dialog;
use Playwright\Download\Download;
use Playwright\Download\DownloadInterface;
use Playwright\Event\EventDispatcherInterface;
use Playwright\Exception\NetworkException;
use Playwright\Exception\PlaywrightException;
Expand Down Expand Up @@ -65,6 +67,7 @@
use Playwright\Page\Options\SetInputFilesOptions;
use Playwright\Page\Options\StyleTagOptions;
use Playwright\Page\Options\TypeOptions;
use Playwright\Page\Options\WaitForDownloadOptions;
use Playwright\Page\Options\WaitForFunctionOptions;
use Playwright\Page\Options\WaitForLoadStateOptions;
use Playwright\Page\Options\WaitForPopupOptions;
Expand Down Expand Up @@ -192,6 +195,11 @@ public function dispatchEvent(string $eventName, array $params): void
$this->eventHandler->publicEmit('requestfailed', [$this->createRequest($params['request'])]);
}
break;
case 'download':
if (is_string($params['downloadId'] ?? null)) {
$this->eventHandler->publicEmit('download', [new Download($this->transport, $this, $params['downloadId'], $params)]);
}
break;
case 'close':
$this->isClosed = true;
$this->routeHandlers = [];
Expand Down Expand Up @@ -1371,6 +1379,35 @@ public function waitForPopup(callable $action, array|WaitForPopupOptions $option
return $popup;
}

/**
* @param array<string, mixed>|WaitForDownloadOptions $options
*/
public function waitForDownload(callable $action, array|WaitForDownloadOptions $options = []): DownloadInterface
{
$options = WaitForDownloadOptions::from($options)->toArray();
$requestId = uniqid('download_', true);

if (method_exists($this->transport, 'storePendingCallback')) {
$this->transport->storePendingCallback($requestId, $action);
} else {
$action();
}

$response = $this->transport->send([
'action' => 'page.waitForDownload',
'pageId' => $this->pageId,
'timeout' => $options['timeout'] ?? 30000,
'requestId' => $requestId,
]);

$downloadId = $response['downloadId'] ?? null;
if (!is_string($downloadId)) {
throw new ProtocolErrorException('No download id returned from transport', 0);
}

return new Download($this->transport, $this, $downloadId, $response);
}

/**
* @param array<string, mixed>|SetInputFilesOptions $options
*/
Expand Down
5 changes: 5 additions & 0 deletions src/Page/PageEventHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,9 @@ public function onRoute(callable $handler): void
{
$this->on('route', $handler);
}

public function onDownload(callable $handler): void
{
$this->on('download', $handler);
}
}
7 changes: 7 additions & 0 deletions src/Page/PageEventHandlerInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,11 @@ public function onRequestFailed(callable $handler): void;
* fulfill, abort, continue or fall back the route themselves.
*/
public function onRoute(callable $handler): void;

/**
* Called with a DownloadInterface each time the page starts a download.
* Events reach PHP while it talks to the browser, so the handler runs
* during a later call on the page, not at the moment of the click.
*/
public function onDownload(callable $handler): void;
}
14 changes: 14 additions & 0 deletions src/Page/PageInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Playwright\Browser\BrowserContextInterface;
use Playwright\Clock\ClockInterface;
use Playwright\Console\ConsoleMessage;
use Playwright\Download\DownloadInterface;
use Playwright\Frame\FrameInterface;
use Playwright\Frame\FrameLocatorInterface;
use Playwright\Input\KeyboardInterface;
Expand All @@ -44,6 +45,7 @@
use Playwright\Page\Options\SetInputFilesOptions;
use Playwright\Page\Options\StyleTagOptions;
use Playwright\Page\Options\TypeOptions;
use Playwright\Page\Options\WaitForDownloadOptions;
use Playwright\Page\Options\WaitForFunctionOptions;
use Playwright\Page\Options\WaitForLoadStateOptions;
use Playwright\Page\Options\WaitForPopupOptions;
Expand Down Expand Up @@ -398,6 +400,18 @@ public function waitForEvents(): void;
*/
public function waitForPopup(callable $action, array|WaitForPopupOptions $options = []): self;

/**
* Runs $action and returns the download it starts.
*
* The listener is armed before $action runs, so a download that starts
* right away is not missed. Throws a TimeoutException when no download
* starts within the timeout.
*
* @param callable(): mixed $action Starts the download, for example a click on a link
* @param array<string, mixed>|WaitForDownloadOptions $options
*/
public function waitForDownload(callable $action, array|WaitForDownloadOptions $options = []): DownloadInterface;

/**
* @param string|callable $url
* @param array<string, mixed>|WaitForResponseOptions $options
Expand Down
10 changes: 10 additions & 0 deletions tests/Fixtures/html/download.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!doctype html>
<html>
<head><meta charset="utf-8"><title>Downloads</title></head>
<body>
<a id="report" href="/download/report.csv">Report</a>
<a id="slow" href="/download/slow.bin">Slow file</a>
<a id="inline" href="data:text/plain,hello%20world" download="hello.txt">Inline file</a>
<button id="nothing" type="button">Does nothing</button>
</body>
</html>
Loading
Loading