2017-05-11 07:06:41 +00:00
|
|
|
/**
|
|
|
|
* Copyright 2017 Google Inc. All rights reserved.
|
|
|
|
*
|
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
* you may not use this file except in compliance with the License.
|
|
|
|
* You may obtain a copy of the License at
|
|
|
|
*
|
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
*
|
|
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
* See the License for the specific language governing permissions and
|
|
|
|
* limitations under the License.
|
|
|
|
*/
|
|
|
|
|
2022-06-22 13:25:44 +00:00
|
|
|
import type {Readable} from 'stream';
|
2023-02-15 23:09:31 +00:00
|
|
|
|
|
|
|
import {Protocol} from 'devtools-protocol';
|
|
|
|
|
2022-10-19 07:06:31 +00:00
|
|
|
import type {Browser} from '../api/Browser.js';
|
|
|
|
import type {BrowserContext} from '../api/BrowserContext.js';
|
2023-09-15 11:00:20 +00:00
|
|
|
import {type CDPSession, CDPSessionEvent} from '../api/CDPSession.js';
|
|
|
|
import {type ElementHandle} from '../api/ElementHandle.js';
|
|
|
|
import {type Frame} from '../api/Frame.js';
|
|
|
|
import {type HTTPRequest} from '../api/HTTPRequest.js';
|
|
|
|
import {type HTTPResponse} from '../api/HTTPResponse.js';
|
|
|
|
import {type JSHandle} from '../api/JSHandle.js';
|
2022-10-10 13:30:12 +00:00
|
|
|
import {
|
2023-09-15 11:00:20 +00:00
|
|
|
type GeolocationOptions,
|
|
|
|
type MediaFeature,
|
|
|
|
type Metrics,
|
|
|
|
type NewDocumentScriptEvaluation,
|
2022-10-10 13:30:12 +00:00
|
|
|
Page,
|
2023-09-13 13:47:55 +00:00
|
|
|
PageEvent,
|
2023-09-15 11:00:20 +00:00
|
|
|
type ScreenshotClip,
|
|
|
|
type ScreenshotOptions,
|
|
|
|
type WaitForOptions,
|
|
|
|
type WaitTimeoutOptions,
|
2022-10-10 13:30:12 +00:00
|
|
|
} from '../api/Page.js';
|
2022-08-17 12:39:41 +00:00
|
|
|
import {assert} from '../util/assert.js';
|
2023-05-31 21:36:19 +00:00
|
|
|
import {Deferred} from '../util/Deferred.js';
|
2022-09-01 15:09:57 +00:00
|
|
|
import {isErrorLike} from '../util/ErrorLike.js';
|
2023-02-15 23:09:31 +00:00
|
|
|
|
2022-09-01 15:09:57 +00:00
|
|
|
import {Accessibility} from './Accessibility.js';
|
2023-02-14 15:54:44 +00:00
|
|
|
import {Binding} from './Binding.js';
|
2023-09-13 19:57:26 +00:00
|
|
|
import {CdpCDPSession} from './CDPSession.js';
|
2023-09-13 13:47:55 +00:00
|
|
|
import {isTargetClosedError} from './Connection.js';
|
2023-09-15 11:00:20 +00:00
|
|
|
import {ConsoleMessage, type ConsoleMessageType} from './ConsoleMessage.js';
|
2022-06-22 13:25:44 +00:00
|
|
|
import {Coverage} from './Coverage.js';
|
2023-09-15 11:00:20 +00:00
|
|
|
import {type DeviceRequestPrompt} from './DeviceRequestPrompt.js';
|
2023-09-13 19:57:26 +00:00
|
|
|
import {CdpDialog} from './Dialog.js';
|
2022-06-22 13:25:44 +00:00
|
|
|
import {EmulationManager} from './EmulationManager.js';
|
2023-05-22 12:52:31 +00:00
|
|
|
import {TargetCloseError} from './Errors.js';
|
2022-06-22 13:25:44 +00:00
|
|
|
import {FileChooser} from './FileChooser.js';
|
2023-09-15 11:00:20 +00:00
|
|
|
import {type CdpFrame} from './Frame.js';
|
2023-09-13 13:47:55 +00:00
|
|
|
import {FrameManager, FrameManagerEvent} from './FrameManager.js';
|
2023-09-13 19:57:26 +00:00
|
|
|
import {CdpKeyboard, CdpMouse, CdpTouchscreen} from './Input.js';
|
2022-11-10 16:11:18 +00:00
|
|
|
import {MAIN_WORLD} from './IsolatedWorlds.js';
|
feat!: type inference for evaluation types (#8547)
This PR greatly improves the types within Puppeteer:
- **Almost everything** is auto-deduced.
- Parameters don't need to be specified in the function. They are deduced from the spread.
- Return types don't need to be specified. They are deduced from the function. (More on this below)
- Selections based on tag names correctly deduce element type, similar to TypeScript's mechanism for `getElementByTagName`.
- [**BREAKING CHANGE**] We've removed the ability to declare return types in type arguments for the following reasons:
1. Setting them will indubitably break auto-deduction.
2. You can just use `as ...` in TypeScript to coerce the correct type (given it makes sense).
- [**BREAKING CHANGE**] `waitFor` is officially gone.
To migrate to these changes, there are only four things you may need to change:
- If you set a return type using the `ReturnType` type parameter, remove it and use `as ...` and `HandleFor` (if necessary).
⛔ `evaluate<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluate(a, b) => {...}, a, b)) as ReturnType`
⛔ `evaluateHandle<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluateHandle(a, b) => {...}, a, b)) as HandleFor<ReturnType>`
- If you set any type parameters in the *parameters* of an evaluation function, remove them.
⛔ `evaluate(a: number, b: number) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
- If you set any type parameters in the method's declaration, remove them.
⛔ `evaluate<(a: number, b: number) => void>((a, b) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
2022-06-23 09:29:46 +00:00
|
|
|
import {
|
2023-09-15 11:00:20 +00:00
|
|
|
type Credentials,
|
|
|
|
type NetworkConditions,
|
2023-09-13 13:47:55 +00:00
|
|
|
NetworkManagerEvent,
|
feat!: type inference for evaluation types (#8547)
This PR greatly improves the types within Puppeteer:
- **Almost everything** is auto-deduced.
- Parameters don't need to be specified in the function. They are deduced from the spread.
- Return types don't need to be specified. They are deduced from the function. (More on this below)
- Selections based on tag names correctly deduce element type, similar to TypeScript's mechanism for `getElementByTagName`.
- [**BREAKING CHANGE**] We've removed the ability to declare return types in type arguments for the following reasons:
1. Setting them will indubitably break auto-deduction.
2. You can just use `as ...` in TypeScript to coerce the correct type (given it makes sense).
- [**BREAKING CHANGE**] `waitFor` is officially gone.
To migrate to these changes, there are only four things you may need to change:
- If you set a return type using the `ReturnType` type parameter, remove it and use `as ...` and `HandleFor` (if necessary).
⛔ `evaluate<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluate(a, b) => {...}, a, b)) as ReturnType`
⛔ `evaluateHandle<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluateHandle(a, b) => {...}, a, b)) as HandleFor<ReturnType>`
- If you set any type parameters in the *parameters* of an evaluation function, remove them.
⛔ `evaluate(a: number, b: number) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
- If you set any type parameters in the method's declaration, remove them.
⛔ `evaluate<(a: number, b: number) => void>((a, b) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
2022-06-23 09:29:46 +00:00
|
|
|
} from './NetworkManager.js';
|
2023-09-15 11:00:20 +00:00
|
|
|
import {type PDFOptions} from './PDFOptions.js';
|
|
|
|
import {type Viewport} from './PuppeteerViewport.js';
|
|
|
|
import {type CdpTarget} from './Target.js';
|
2023-09-13 13:47:55 +00:00
|
|
|
import {TargetManagerEvent} from './TargetManager.js';
|
2023-09-15 11:00:20 +00:00
|
|
|
import {type TaskQueue} from './TaskQueue.js';
|
feat!: type inference for evaluation types (#8547)
This PR greatly improves the types within Puppeteer:
- **Almost everything** is auto-deduced.
- Parameters don't need to be specified in the function. They are deduced from the spread.
- Return types don't need to be specified. They are deduced from the function. (More on this below)
- Selections based on tag names correctly deduce element type, similar to TypeScript's mechanism for `getElementByTagName`.
- [**BREAKING CHANGE**] We've removed the ability to declare return types in type arguments for the following reasons:
1. Setting them will indubitably break auto-deduction.
2. You can just use `as ...` in TypeScript to coerce the correct type (given it makes sense).
- [**BREAKING CHANGE**] `waitFor` is officially gone.
To migrate to these changes, there are only four things you may need to change:
- If you set a return type using the `ReturnType` type parameter, remove it and use `as ...` and `HandleFor` (if necessary).
⛔ `evaluate<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluate(a, b) => {...}, a, b)) as ReturnType`
⛔ `evaluateHandle<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluateHandle(a, b) => {...}, a, b)) as HandleFor<ReturnType>`
- If you set any type parameters in the *parameters* of an evaluation function, remove them.
⛔ `evaluate(a: number, b: number) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
- If you set any type parameters in the method's declaration, remove them.
⛔ `evaluate<(a: number, b: number) => void>((a, b) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
2022-06-23 09:29:46 +00:00
|
|
|
import {TimeoutSettings} from './TimeoutSettings.js';
|
|
|
|
import {Tracing} from './Tracing.js';
|
2023-09-15 11:00:20 +00:00
|
|
|
import {type BindingPayload, type HandleFor} from './types.js';
|
2022-06-14 11:16:21 +00:00
|
|
|
import {
|
2023-09-01 12:12:29 +00:00
|
|
|
createCdpHandle,
|
2023-05-10 08:23:29 +00:00
|
|
|
createClientError,
|
2022-06-14 11:16:21 +00:00
|
|
|
debugError,
|
|
|
|
evaluationString,
|
|
|
|
getReadableAsBuffer,
|
|
|
|
getReadableFromProtocolStream,
|
|
|
|
isString,
|
|
|
|
pageBindingInitString,
|
|
|
|
releaseObject,
|
2023-08-01 13:53:02 +00:00
|
|
|
validateDialogType,
|
2022-06-14 11:16:21 +00:00
|
|
|
valueFromRemoteObject,
|
|
|
|
waitForEvent,
|
|
|
|
waitWithTimeout,
|
2022-08-17 12:39:41 +00:00
|
|
|
} from './util.js';
|
2022-06-22 13:25:44 +00:00
|
|
|
import {WebWorker} from './WebWorker.js';
|
2017-10-11 07:55:48 +00:00
|
|
|
|
2020-06-26 07:24:56 +00:00
|
|
|
/**
|
2022-09-21 06:10:50 +00:00
|
|
|
* @internal
|
2020-06-12 10:10:12 +00:00
|
|
|
*/
|
2023-09-13 19:57:26 +00:00
|
|
|
export class CdpPage extends Page {
|
2022-06-13 09:16:25 +00:00
|
|
|
static async _create(
|
2020-05-07 10:54:55 +00:00
|
|
|
client: CDPSession,
|
2023-09-13 19:57:26 +00:00
|
|
|
target: CdpTarget,
|
2020-05-07 10:54:55 +00:00
|
|
|
ignoreHTTPSErrors: boolean,
|
2021-09-23 12:37:35 +00:00
|
|
|
defaultViewport: Viewport | null,
|
|
|
|
screenshotTaskQueue: TaskQueue
|
2023-09-13 19:57:26 +00:00
|
|
|
): Promise<CdpPage> {
|
|
|
|
const page = new CdpPage(
|
2021-09-23 12:37:35 +00:00
|
|
|
client,
|
|
|
|
target,
|
|
|
|
ignoreHTTPSErrors,
|
|
|
|
screenshotTaskQueue
|
|
|
|
);
|
2022-06-13 09:16:25 +00:00
|
|
|
await page.#initialize();
|
2022-06-14 11:55:35 +00:00
|
|
|
if (defaultViewport) {
|
2022-09-14 12:18:12 +00:00
|
|
|
try {
|
|
|
|
await page.setViewport(defaultViewport);
|
|
|
|
} catch (err) {
|
|
|
|
if (isErrorLike(err) && isTargetClosedError(err)) {
|
|
|
|
debugError(err);
|
|
|
|
} else {
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
}
|
2022-06-14 11:55:35 +00:00
|
|
|
}
|
2017-06-21 20:51:06 +00:00
|
|
|
return page;
|
|
|
|
}
|
|
|
|
|
2022-06-13 09:16:25 +00:00
|
|
|
#closed = false;
|
|
|
|
#client: CDPSession;
|
2023-08-28 06:20:57 +00:00
|
|
|
#tabSession: CDPSession | undefined;
|
2023-09-13 19:57:26 +00:00
|
|
|
#target: CdpTarget;
|
|
|
|
#keyboard: CdpKeyboard;
|
|
|
|
#mouse: CdpMouse;
|
2022-06-13 09:16:25 +00:00
|
|
|
#timeoutSettings = new TimeoutSettings();
|
2023-09-13 19:57:26 +00:00
|
|
|
#touchscreen: CdpTouchscreen;
|
2022-06-13 09:16:25 +00:00
|
|
|
#accessibility: Accessibility;
|
|
|
|
#frameManager: FrameManager;
|
|
|
|
#emulationManager: EmulationManager;
|
|
|
|
#tracing: Tracing;
|
2023-02-14 15:54:44 +00:00
|
|
|
#bindings = new Map<string, Binding>();
|
2023-06-02 12:08:36 +00:00
|
|
|
#exposedFunctions = new Map<string, string>();
|
2022-06-13 09:16:25 +00:00
|
|
|
#coverage: Coverage;
|
|
|
|
#viewport: Viewport | null;
|
|
|
|
#screenshotTaskQueue: TaskQueue;
|
|
|
|
#workers = new Map<string, WebWorker>();
|
2023-05-30 07:03:42 +00:00
|
|
|
#fileChooserDeferreds = new Set<Deferred<FileChooser>>();
|
2023-05-31 21:36:19 +00:00
|
|
|
#sessionCloseDeferred = Deferred.create<TargetCloseError>();
|
2023-05-23 11:51:32 +00:00
|
|
|
#serviceWorkerBypassed = false;
|
2022-06-13 09:16:25 +00:00
|
|
|
#userDragInterceptionEnabled = false;
|
2020-05-05 12:53:22 +00:00
|
|
|
|
2023-09-13 13:47:55 +00:00
|
|
|
#frameManagerHandlers = Object.freeze([
|
2023-08-08 12:02:56 +00:00
|
|
|
[
|
2023-09-13 13:47:55 +00:00
|
|
|
FrameManagerEvent.FrameAttached,
|
2023-09-13 19:57:26 +00:00
|
|
|
(frame: CdpFrame) => {
|
2023-09-13 13:47:55 +00:00
|
|
|
this.emit(PageEvent.FrameAttached, frame);
|
|
|
|
},
|
2023-08-08 12:02:56 +00:00
|
|
|
],
|
|
|
|
[
|
2023-09-13 13:47:55 +00:00
|
|
|
FrameManagerEvent.FrameDetached,
|
2023-09-13 19:57:26 +00:00
|
|
|
(frame: CdpFrame) => {
|
2023-09-13 13:47:55 +00:00
|
|
|
this.emit(PageEvent.FrameDetached, frame);
|
|
|
|
},
|
2023-08-08 12:02:56 +00:00
|
|
|
],
|
|
|
|
[
|
2023-09-13 13:47:55 +00:00
|
|
|
FrameManagerEvent.FrameNavigated,
|
2023-09-13 19:57:26 +00:00
|
|
|
(frame: CdpFrame) => {
|
2023-09-13 13:47:55 +00:00
|
|
|
this.emit(PageEvent.FrameNavigated, frame);
|
|
|
|
},
|
2023-08-08 12:02:56 +00:00
|
|
|
],
|
2023-09-13 13:47:55 +00:00
|
|
|
] as const);
|
2023-08-08 12:02:56 +00:00
|
|
|
|
2023-09-13 13:47:55 +00:00
|
|
|
#networkManagerHandlers = Object.freeze([
|
2023-08-08 12:02:56 +00:00
|
|
|
[
|
2023-09-13 13:47:55 +00:00
|
|
|
NetworkManagerEvent.Request,
|
|
|
|
(request: HTTPRequest) => {
|
|
|
|
this.emit(PageEvent.Request, request);
|
|
|
|
},
|
2023-08-08 12:02:56 +00:00
|
|
|
],
|
|
|
|
[
|
2023-09-13 13:47:55 +00:00
|
|
|
NetworkManagerEvent.RequestServedFromCache,
|
|
|
|
(request: HTTPRequest) => {
|
|
|
|
this.emit(PageEvent.RequestServedFromCache, request);
|
|
|
|
},
|
2023-08-08 12:02:56 +00:00
|
|
|
],
|
|
|
|
[
|
2023-09-13 13:47:55 +00:00
|
|
|
NetworkManagerEvent.Response,
|
|
|
|
(response: HTTPResponse) => {
|
|
|
|
this.emit(PageEvent.Response, response);
|
|
|
|
},
|
2023-08-08 12:02:56 +00:00
|
|
|
],
|
|
|
|
[
|
2023-09-13 13:47:55 +00:00
|
|
|
NetworkManagerEvent.RequestFailed,
|
|
|
|
(request: HTTPRequest) => {
|
|
|
|
this.emit(PageEvent.RequestFailed, request);
|
|
|
|
},
|
2023-08-08 12:02:56 +00:00
|
|
|
],
|
|
|
|
[
|
2023-09-13 13:47:55 +00:00
|
|
|
NetworkManagerEvent.RequestFinished,
|
|
|
|
(request: HTTPRequest) => {
|
|
|
|
this.emit(PageEvent.RequestFinished, request);
|
|
|
|
},
|
2023-08-08 12:02:56 +00:00
|
|
|
],
|
2023-09-13 13:47:55 +00:00
|
|
|
] as const);
|
2023-08-08 12:02:56 +00:00
|
|
|
|
2023-09-13 13:47:55 +00:00
|
|
|
#sessionHandlers = Object.freeze([
|
2023-08-08 12:02:56 +00:00
|
|
|
[
|
2023-09-13 13:47:55 +00:00
|
|
|
CDPSessionEvent.Disconnected,
|
2023-08-08 12:02:56 +00:00
|
|
|
() => {
|
2023-09-13 13:47:55 +00:00
|
|
|
this.#sessionCloseDeferred.resolve(
|
2023-08-08 12:02:56 +00:00
|
|
|
new TargetCloseError('Target closed')
|
|
|
|
);
|
|
|
|
},
|
|
|
|
],
|
|
|
|
[
|
|
|
|
'Page.domContentEventFired',
|
2023-09-13 13:47:55 +00:00
|
|
|
() => {
|
|
|
|
return this.emit(PageEvent.DOMContentLoaded, undefined);
|
|
|
|
},
|
|
|
|
],
|
|
|
|
[
|
|
|
|
'Page.loadEventFired',
|
|
|
|
() => {
|
|
|
|
return this.emit(PageEvent.Load, undefined);
|
|
|
|
},
|
2023-08-08 12:02:56 +00:00
|
|
|
],
|
2023-08-30 10:25:07 +00:00
|
|
|
['Runtime.consoleAPICalled', this.#onConsoleAPI.bind(this)],
|
|
|
|
['Runtime.bindingCalled', this.#onBindingCalled.bind(this)],
|
|
|
|
['Page.javascriptDialogOpening', this.#onDialog.bind(this)],
|
|
|
|
['Runtime.exceptionThrown', this.#handleException.bind(this)],
|
|
|
|
['Inspector.targetCrashed', this.#onTargetCrashed.bind(this)],
|
|
|
|
['Performance.metrics', this.#emitMetrics.bind(this)],
|
|
|
|
['Log.entryAdded', this.#onLogEntryAdded.bind(this)],
|
|
|
|
['Page.fileChooserOpened', this.#onFileChooser.bind(this)],
|
2023-09-13 13:47:55 +00:00
|
|
|
] as const);
|
2023-08-08 12:02:56 +00:00
|
|
|
|
2021-09-23 12:37:35 +00:00
|
|
|
constructor(
|
|
|
|
client: CDPSession,
|
2023-09-13 19:57:26 +00:00
|
|
|
target: CdpTarget,
|
2021-09-23 12:37:35 +00:00
|
|
|
ignoreHTTPSErrors: boolean,
|
|
|
|
screenshotTaskQueue: TaskQueue
|
|
|
|
) {
|
2017-06-21 20:51:06 +00:00
|
|
|
super();
|
2022-06-13 09:16:25 +00:00
|
|
|
this.#client = client;
|
2023-08-28 06:20:57 +00:00
|
|
|
this.#tabSession = client.parentSession();
|
2022-06-13 09:16:25 +00:00
|
|
|
this.#target = target;
|
2023-09-13 19:57:26 +00:00
|
|
|
this.#keyboard = new CdpKeyboard(client);
|
|
|
|
this.#mouse = new CdpMouse(client, this.#keyboard);
|
|
|
|
this.#touchscreen = new CdpTouchscreen(client, this.#keyboard);
|
2023-06-15 11:34:54 +00:00
|
|
|
this.#accessibility = new Accessibility(client);
|
2022-06-13 09:16:25 +00:00
|
|
|
this.#frameManager = new FrameManager(
|
2020-05-07 10:54:55 +00:00
|
|
|
client,
|
|
|
|
this,
|
|
|
|
ignoreHTTPSErrors,
|
2022-06-13 09:16:25 +00:00
|
|
|
this.#timeoutSettings
|
2020-05-07 10:54:55 +00:00
|
|
|
);
|
2022-06-13 09:16:25 +00:00
|
|
|
this.#emulationManager = new EmulationManager(client);
|
2023-06-15 11:34:54 +00:00
|
|
|
this.#tracing = new Tracing(client);
|
2022-06-13 09:16:25 +00:00
|
|
|
this.#coverage = new Coverage(client);
|
|
|
|
this.#screenshotTaskQueue = screenshotTaskQueue;
|
|
|
|
this.#viewport = null;
|
2017-06-21 20:51:06 +00:00
|
|
|
|
2023-08-08 12:02:56 +00:00
|
|
|
this.#setupEventListeners();
|
2023-08-28 06:20:57 +00:00
|
|
|
|
2023-09-13 13:47:55 +00:00
|
|
|
this.#tabSession?.on(CDPSessionEvent.Swapped, async newSession => {
|
2023-08-28 06:20:57 +00:00
|
|
|
this.#client = newSession;
|
|
|
|
assert(
|
2023-09-13 19:57:26 +00:00
|
|
|
this.#client instanceof CdpCDPSession,
|
2023-08-28 06:20:57 +00:00
|
|
|
'CDPSession is not instance of CDPSessionImpl'
|
|
|
|
);
|
|
|
|
this.#target = this.#client._target();
|
|
|
|
assert(this.#target, 'Missing target on swap');
|
|
|
|
this.#keyboard.updateClient(newSession);
|
|
|
|
this.#mouse.updateClient(newSession);
|
|
|
|
this.#touchscreen.updateClient(newSession);
|
|
|
|
this.#accessibility.updateClient(newSession);
|
|
|
|
this.#emulationManager.updateClient(newSession);
|
|
|
|
this.#tracing.updateClient(newSession);
|
|
|
|
this.#coverage.updateClient(newSession);
|
|
|
|
await this.#frameManager.swapFrameTree(newSession);
|
|
|
|
this.#setupEventListeners();
|
|
|
|
});
|
2023-09-13 13:47:55 +00:00
|
|
|
this.#tabSession?.on(CDPSessionEvent.Ready, session => {
|
2023-09-13 19:57:26 +00:00
|
|
|
assert(session instanceof CdpCDPSession);
|
2023-09-13 13:47:55 +00:00
|
|
|
if (session._target()._subtype() !== 'prerender') {
|
|
|
|
return;
|
2023-08-29 16:12:04 +00:00
|
|
|
}
|
2023-09-13 13:47:55 +00:00
|
|
|
this.#frameManager.registerSpeculativeSession(session).catch(debugError);
|
|
|
|
this.#emulationManager
|
|
|
|
.registerSpeculativeSession(session)
|
|
|
|
.catch(debugError);
|
|
|
|
});
|
2023-08-08 12:02:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#setupEventListeners() {
|
2023-09-13 13:47:55 +00:00
|
|
|
this.#client.on(CDPSessionEvent.Ready, this.#onAttachedToTarget);
|
2022-07-21 18:50:46 +00:00
|
|
|
|
|
|
|
this.#target
|
|
|
|
._targetManager()
|
2023-09-13 13:47:55 +00:00
|
|
|
.on(TargetManagerEvent.TargetGone, this.#onDetachedFromTarget);
|
2018-05-21 21:31:11 +00:00
|
|
|
|
2023-08-08 12:02:56 +00:00
|
|
|
for (const [eventName, handler] of this.#frameManagerHandlers) {
|
|
|
|
this.#frameManager.on(eventName, handler);
|
|
|
|
}
|
2017-06-21 20:51:06 +00:00
|
|
|
|
2023-08-08 12:02:56 +00:00
|
|
|
for (const [eventName, handler] of this.#networkManagerHandlers) {
|
2023-09-13 13:47:55 +00:00
|
|
|
// TODO: Remove any.
|
|
|
|
this.#frameManager.networkManager.on(eventName, handler as any);
|
2023-08-08 12:02:56 +00:00
|
|
|
}
|
2017-06-29 06:09:28 +00:00
|
|
|
|
2023-08-08 12:02:56 +00:00
|
|
|
for (const [eventName, handler] of this.#sessionHandlers) {
|
2023-09-13 13:47:55 +00:00
|
|
|
// TODO: Remove any.
|
|
|
|
this.#client.on(eventName, handler as any);
|
2023-08-08 12:02:56 +00:00
|
|
|
}
|
2023-05-30 07:03:42 +00:00
|
|
|
|
2023-05-26 09:42:22 +00:00
|
|
|
this.#target._isClosedDeferred
|
2023-05-26 06:02:17 +00:00
|
|
|
.valueOrThrow()
|
|
|
|
.then(() => {
|
2023-09-13 13:47:55 +00:00
|
|
|
this.#client.off(CDPSessionEvent.Ready, this.#onAttachedToTarget);
|
2023-05-26 06:02:17 +00:00
|
|
|
|
|
|
|
this.#target
|
|
|
|
._targetManager()
|
2023-09-13 13:47:55 +00:00
|
|
|
.off(TargetManagerEvent.TargetGone, this.#onDetachedFromTarget);
|
2023-08-08 12:02:56 +00:00
|
|
|
|
2023-09-13 13:47:55 +00:00
|
|
|
this.emit(PageEvent.Close, undefined);
|
2023-05-26 06:02:17 +00:00
|
|
|
this.#closed = true;
|
|
|
|
})
|
|
|
|
.catch(debugError);
|
2017-08-15 18:13:05 +00:00
|
|
|
}
|
|
|
|
|
2023-09-13 19:57:26 +00:00
|
|
|
#onDetachedFromTarget = (target: CdpTarget) => {
|
2022-07-21 18:50:46 +00:00
|
|
|
const sessionId = target._session()?.id();
|
|
|
|
const worker = this.#workers.get(sessionId!);
|
|
|
|
if (!worker) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
this.#workers.delete(sessionId!);
|
2023-09-13 13:47:55 +00:00
|
|
|
this.emit(PageEvent.WorkerDestroyed, worker);
|
2022-07-21 18:50:46 +00:00
|
|
|
};
|
|
|
|
|
2023-09-13 13:47:55 +00:00
|
|
|
#onAttachedToTarget = (session: CDPSession) => {
|
2023-09-13 19:57:26 +00:00
|
|
|
assert(session instanceof CdpCDPSession);
|
2023-08-29 08:52:47 +00:00
|
|
|
this.#frameManager.onAttachedToTarget(session._target());
|
|
|
|
if (session._target()._getTargetInfo().type === 'worker') {
|
2022-07-21 18:50:46 +00:00
|
|
|
const worker = new WebWorker(
|
|
|
|
session,
|
2023-08-29 08:52:47 +00:00
|
|
|
session._target().url(),
|
2022-07-21 18:50:46 +00:00
|
|
|
this.#addConsoleMessage.bind(this),
|
|
|
|
this.#handleException.bind(this)
|
|
|
|
);
|
|
|
|
this.#workers.set(session.id(), worker);
|
2023-09-13 13:47:55 +00:00
|
|
|
this.emit(PageEvent.WorkerCreated, worker);
|
2022-07-21 18:50:46 +00:00
|
|
|
}
|
2023-09-13 13:47:55 +00:00
|
|
|
session.on(CDPSessionEvent.Ready, this.#onAttachedToTarget);
|
2022-07-21 18:50:46 +00:00
|
|
|
};
|
|
|
|
|
2022-06-13 09:16:25 +00:00
|
|
|
async #initialize(): Promise<void> {
|
2022-09-14 12:18:12 +00:00
|
|
|
try {
|
|
|
|
await Promise.all([
|
2023-08-29 16:12:04 +00:00
|
|
|
this.#frameManager.initialize(this.#client),
|
2022-09-14 12:18:12 +00:00
|
|
|
this.#client.send('Performance.enable'),
|
|
|
|
this.#client.send('Log.enable'),
|
|
|
|
]);
|
|
|
|
} catch (err) {
|
|
|
|
if (isErrorLike(err) && isTargetClosedError(err)) {
|
|
|
|
debugError(err);
|
|
|
|
} else {
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
}
|
2019-07-23 04:30:49 +00:00
|
|
|
}
|
|
|
|
|
2022-06-13 09:16:25 +00:00
|
|
|
async #onFileChooser(
|
2020-07-10 10:51:52 +00:00
|
|
|
event: Protocol.Page.FileChooserOpenedEvent
|
2020-05-07 10:54:55 +00:00
|
|
|
): Promise<void> {
|
2023-05-30 07:03:42 +00:00
|
|
|
if (!this.#fileChooserDeferreds.size) {
|
2022-06-14 11:55:35 +00:00
|
|
|
return;
|
|
|
|
}
|
2022-08-10 21:34:29 +00:00
|
|
|
|
2022-06-13 09:16:25 +00:00
|
|
|
const frame = this.#frameManager.frame(event.frameId);
|
2022-08-10 21:34:29 +00:00
|
|
|
assert(frame, 'This should never happen.');
|
|
|
|
|
2022-08-09 12:55:18 +00:00
|
|
|
// This is guaranteed to be an HTMLInputElement handle by the event.
|
2023-08-30 10:02:59 +00:00
|
|
|
using handle = (await frame.worlds[MAIN_WORLD].adoptBackendNode(
|
2022-08-09 12:55:18 +00:00
|
|
|
event.backendNodeId
|
|
|
|
)) as ElementHandle<HTMLInputElement>;
|
2022-08-10 21:34:29 +00:00
|
|
|
|
2023-08-30 10:02:59 +00:00
|
|
|
const fileChooser = new FileChooser(handle.move(), event);
|
2023-05-30 07:03:42 +00:00
|
|
|
for (const promise of this.#fileChooserDeferreds) {
|
2022-08-10 21:34:29 +00:00
|
|
|
promise.resolve(fileChooser);
|
2022-06-14 11:55:35 +00:00
|
|
|
}
|
2023-05-30 07:03:42 +00:00
|
|
|
this.#fileChooserDeferreds.clear();
|
2019-07-23 04:30:49 +00:00
|
|
|
}
|
|
|
|
|
2022-11-24 12:10:29 +00:00
|
|
|
_client(): CDPSession {
|
|
|
|
return this.#client;
|
|
|
|
}
|
|
|
|
|
2023-05-23 11:51:32 +00:00
|
|
|
override isServiceWorkerBypassed(): boolean {
|
|
|
|
return this.#serviceWorkerBypassed;
|
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override isDragInterceptionEnabled(): boolean {
|
2022-06-13 09:16:25 +00:00
|
|
|
return this.#userDragInterceptionEnabled;
|
2021-07-13 09:37:39 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override isJavaScriptEnabled(): boolean {
|
2023-06-15 12:30:37 +00:00
|
|
|
return this.#emulationManager.javascriptEnabled;
|
2020-06-10 15:15:02 +00:00
|
|
|
}
|
|
|
|
|
2023-09-01 12:12:29 +00:00
|
|
|
override async waitForFileChooser(
|
2022-09-21 06:10:50 +00:00
|
|
|
options: WaitTimeoutOptions = {}
|
|
|
|
): Promise<FileChooser> {
|
2023-05-30 07:03:42 +00:00
|
|
|
const needsEnable = this.#fileChooserDeferreds.size === 0;
|
2022-06-22 13:25:44 +00:00
|
|
|
const {timeout = this.#timeoutSettings.timeout()} = options;
|
2023-05-31 21:36:19 +00:00
|
|
|
const deferred = Deferred.create<FileChooser>({
|
2022-08-30 14:24:51 +00:00
|
|
|
message: `Waiting for \`FileChooser\` failed: ${timeout}ms exceeded`,
|
|
|
|
timeout,
|
|
|
|
});
|
2023-05-30 07:03:42 +00:00
|
|
|
this.#fileChooserDeferreds.add(deferred);
|
2022-09-06 15:03:56 +00:00
|
|
|
let enablePromise: Promise<void> | undefined;
|
|
|
|
if (needsEnable) {
|
|
|
|
enablePromise = this.#client.send('Page.setInterceptFileChooserDialog', {
|
|
|
|
enabled: true,
|
|
|
|
});
|
|
|
|
}
|
2023-09-01 12:12:29 +00:00
|
|
|
try {
|
|
|
|
const [result] = await Promise.all([
|
|
|
|
deferred.valueOrThrow(),
|
|
|
|
enablePromise,
|
|
|
|
]);
|
|
|
|
return result;
|
|
|
|
} catch (error) {
|
|
|
|
this.#fileChooserDeferreds.delete(deferred);
|
|
|
|
throw error;
|
|
|
|
}
|
2019-07-23 04:30:49 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async setGeolocation(options: GeolocationOptions): Promise<void> {
|
2023-06-15 12:30:37 +00:00
|
|
|
return await this.#emulationManager.setGeolocation(options);
|
2018-08-31 17:04:12 +00:00
|
|
|
}
|
|
|
|
|
2023-09-13 19:57:26 +00:00
|
|
|
override target(): CdpTarget {
|
2022-06-13 09:16:25 +00:00
|
|
|
return this.#target;
|
2018-01-11 03:33:22 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override browser(): Browser {
|
2022-06-13 09:16:25 +00:00
|
|
|
return this.#target.browser();
|
2018-04-17 17:37:17 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override browserContext(): BrowserContext {
|
2022-06-13 09:16:25 +00:00
|
|
|
return this.#target.browserContext();
|
2018-12-12 23:08:31 +00:00
|
|
|
}
|
|
|
|
|
2022-06-13 09:16:25 +00:00
|
|
|
#onTargetCrashed(): void {
|
2023-09-13 13:47:55 +00:00
|
|
|
this.emit(PageEvent.Error, new Error('Page crashed!'));
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
|
|
|
|
2022-06-13 09:16:25 +00:00
|
|
|
#onLogEntryAdded(event: Protocol.Log.EntryAddedEvent): void {
|
2022-06-22 13:25:44 +00:00
|
|
|
const {level, text, args, source, url, lineNumber} = event.entry;
|
2022-06-14 11:55:35 +00:00
|
|
|
if (args) {
|
2022-06-22 13:25:44 +00:00
|
|
|
args.map(arg => {
|
2022-06-15 10:42:21 +00:00
|
|
|
return releaseObject(this.#client, arg);
|
|
|
|
});
|
2022-06-14 11:55:35 +00:00
|
|
|
}
|
|
|
|
if (source !== 'worker') {
|
2020-05-07 10:54:55 +00:00
|
|
|
this.emit(
|
2023-09-13 13:47:55 +00:00
|
|
|
PageEvent.Console,
|
2022-06-22 13:25:44 +00:00
|
|
|
new ConsoleMessage(level, text, [], [{url, lineNumber}])
|
2020-05-07 10:54:55 +00:00
|
|
|
);
|
2022-06-14 11:55:35 +00:00
|
|
|
}
|
2018-04-28 04:40:09 +00:00
|
|
|
}
|
|
|
|
|
2023-09-13 19:57:26 +00:00
|
|
|
override mainFrame(): CdpFrame {
|
2022-06-13 09:16:25 +00:00
|
|
|
return this.#frameManager.mainFrame();
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
2017-06-21 20:36:04 +00:00
|
|
|
|
2023-09-13 19:57:26 +00:00
|
|
|
override get keyboard(): CdpKeyboard {
|
2022-06-13 09:16:25 +00:00
|
|
|
return this.#keyboard;
|
2017-07-18 01:49:52 +00:00
|
|
|
}
|
|
|
|
|
2023-09-13 19:57:26 +00:00
|
|
|
override get touchscreen(): CdpTouchscreen {
|
2022-06-13 09:16:25 +00:00
|
|
|
return this.#touchscreen;
|
2017-09-02 02:03:51 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override get coverage(): Coverage {
|
2022-06-13 09:16:25 +00:00
|
|
|
return this.#coverage;
|
2018-01-03 03:53:53 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override get tracing(): Tracing {
|
2022-06-13 09:16:25 +00:00
|
|
|
return this.#tracing;
|
2017-08-02 17:45:11 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override get accessibility(): Accessibility {
|
2022-06-13 09:16:25 +00:00
|
|
|
return this.#accessibility;
|
2018-11-02 01:54:51 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override frames(): Frame[] {
|
2022-06-13 09:16:25 +00:00
|
|
|
return this.#frameManager.frames();
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
2017-06-21 20:36:04 +00:00
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override workers(): WebWorker[] {
|
2022-06-13 09:16:25 +00:00
|
|
|
return Array.from(this.#workers.values());
|
2018-05-21 21:31:11 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async setRequestInterception(value: boolean): Promise<void> {
|
2023-09-01 07:49:33 +00:00
|
|
|
return await this.#frameManager.networkManager.setRequestInterception(
|
|
|
|
value
|
|
|
|
);
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
2017-06-15 07:20:37 +00:00
|
|
|
|
2023-05-23 11:51:32 +00:00
|
|
|
override async setBypassServiceWorker(bypass: boolean): Promise<void> {
|
|
|
|
this.#serviceWorkerBypassed = bypass;
|
2023-09-01 07:49:33 +00:00
|
|
|
return await this.#client.send('Network.setBypassServiceWorker', {bypass});
|
2023-05-23 11:51:32 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async setDragInterception(enabled: boolean): Promise<void> {
|
2022-06-13 09:16:25 +00:00
|
|
|
this.#userDragInterceptionEnabled = enabled;
|
2023-09-01 07:49:33 +00:00
|
|
|
return await this.#client.send('Input.setInterceptDrags', {enabled});
|
2021-06-04 10:25:36 +00:00
|
|
|
}
|
|
|
|
|
2023-09-01 12:12:29 +00:00
|
|
|
override async setOfflineMode(enabled: boolean): Promise<void> {
|
|
|
|
return await this.#frameManager.networkManager.setOfflineMode(enabled);
|
2017-10-13 21:41:39 +00:00
|
|
|
}
|
|
|
|
|
2023-09-01 12:12:29 +00:00
|
|
|
override async emulateNetworkConditions(
|
2021-01-21 09:00:57 +00:00
|
|
|
networkConditions: NetworkConditions | null
|
|
|
|
): Promise<void> {
|
2023-09-01 12:12:29 +00:00
|
|
|
return await this.#frameManager.networkManager.emulateNetworkConditions(
|
2022-08-10 21:34:29 +00:00
|
|
|
networkConditions
|
|
|
|
);
|
2021-01-21 09:00:57 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override setDefaultNavigationTimeout(timeout: number): void {
|
2022-06-13 09:16:25 +00:00
|
|
|
this.#timeoutSettings.setDefaultNavigationTimeout(timeout);
|
2019-01-29 01:16:12 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override setDefaultTimeout(timeout: number): void {
|
2022-06-13 09:16:25 +00:00
|
|
|
this.#timeoutSettings.setDefaultTimeout(timeout);
|
2018-01-10 21:04:01 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override getDefaultTimeout(): number {
|
2022-09-05 17:43:39 +00:00
|
|
|
return this.#timeoutSettings.timeout();
|
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async queryObjects<Prototype>(
|
feat!: type inference for evaluation types (#8547)
This PR greatly improves the types within Puppeteer:
- **Almost everything** is auto-deduced.
- Parameters don't need to be specified in the function. They are deduced from the spread.
- Return types don't need to be specified. They are deduced from the function. (More on this below)
- Selections based on tag names correctly deduce element type, similar to TypeScript's mechanism for `getElementByTagName`.
- [**BREAKING CHANGE**] We've removed the ability to declare return types in type arguments for the following reasons:
1. Setting them will indubitably break auto-deduction.
2. You can just use `as ...` in TypeScript to coerce the correct type (given it makes sense).
- [**BREAKING CHANGE**] `waitFor` is officially gone.
To migrate to these changes, there are only four things you may need to change:
- If you set a return type using the `ReturnType` type parameter, remove it and use `as ...` and `HandleFor` (if necessary).
⛔ `evaluate<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluate(a, b) => {...}, a, b)) as ReturnType`
⛔ `evaluateHandle<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluateHandle(a, b) => {...}, a, b)) as HandleFor<ReturnType>`
- If you set any type parameters in the *parameters* of an evaluation function, remove them.
⛔ `evaluate(a: number, b: number) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
- If you set any type parameters in the method's declaration, remove them.
⛔ `evaluate<(a: number, b: number) => void>((a, b) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
2022-06-23 09:29:46 +00:00
|
|
|
prototypeHandle: JSHandle<Prototype>
|
|
|
|
): Promise<JSHandle<Prototype[]>> {
|
2022-08-25 15:02:44 +00:00
|
|
|
assert(!prototypeHandle.disposed, 'Prototype JSHandle is disposed!');
|
|
|
|
assert(
|
2023-02-15 10:29:18 +00:00
|
|
|
prototypeHandle.id,
|
2022-08-25 15:02:44 +00:00
|
|
|
'Prototype JSHandle must not be referencing primitive value'
|
|
|
|
);
|
2023-09-01 12:12:29 +00:00
|
|
|
const response = await this.mainFrame().client.send(
|
|
|
|
'Runtime.queryObjects',
|
|
|
|
{
|
|
|
|
prototypeObjectId: prototypeHandle.id,
|
|
|
|
}
|
|
|
|
);
|
|
|
|
return createCdpHandle(
|
|
|
|
this.mainFrame().mainRealm(),
|
|
|
|
response.objects
|
|
|
|
) as HandleFor<Prototype[]>;
|
2017-10-11 21:41:20 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async cookies(
|
|
|
|
...urls: string[]
|
|
|
|
): Promise<Protocol.Network.Cookie[]> {
|
2020-05-07 10:54:55 +00:00
|
|
|
const originalCookies = (
|
2022-06-13 09:16:25 +00:00
|
|
|
await this.#client.send('Network.getCookies', {
|
2020-05-07 10:54:55 +00:00
|
|
|
urls: urls.length ? urls : [this.url()],
|
|
|
|
})
|
|
|
|
).cookies;
|
2020-04-16 07:20:27 +00:00
|
|
|
|
|
|
|
const unsupportedCookieAttributes = ['priority'];
|
2020-05-07 10:54:55 +00:00
|
|
|
const filterUnsupportedAttributes = (
|
|
|
|
cookie: Protocol.Network.Cookie
|
|
|
|
): Protocol.Network.Cookie => {
|
2022-05-31 14:34:16 +00:00
|
|
|
for (const attr of unsupportedCookieAttributes) {
|
|
|
|
delete (cookie as unknown as Record<string, unknown>)[attr];
|
|
|
|
}
|
2020-04-16 07:20:27 +00:00
|
|
|
return cookie;
|
|
|
|
};
|
|
|
|
return originalCookies.map(filterUnsupportedAttributes);
|
2017-08-24 19:21:46 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async deleteCookie(
|
2020-07-10 10:51:52 +00:00
|
|
|
...cookies: Protocol.Network.DeleteCookiesRequest[]
|
2020-05-07 10:54:55 +00:00
|
|
|
): Promise<void> {
|
2017-08-24 19:21:46 +00:00
|
|
|
const pageURL = this.url();
|
|
|
|
for (const cookie of cookies) {
|
|
|
|
const item = Object.assign({}, cookie);
|
2022-06-14 11:55:35 +00:00
|
|
|
if (!cookie.url && pageURL.startsWith('http')) {
|
|
|
|
item.url = pageURL;
|
|
|
|
}
|
2022-06-13 09:16:25 +00:00
|
|
|
await this.#client.send('Network.deleteCookies', item);
|
2017-08-24 19:21:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async setCookie(
|
|
|
|
...cookies: Protocol.Network.CookieParam[]
|
|
|
|
): Promise<void> {
|
2017-12-16 09:17:20 +00:00
|
|
|
const pageURL = this.url();
|
|
|
|
const startsWithHTTP = pageURL.startsWith('http');
|
2022-06-22 13:25:44 +00:00
|
|
|
const items = cookies.map(cookie => {
|
2017-08-24 19:21:46 +00:00
|
|
|
const item = Object.assign({}, cookie);
|
2022-06-14 11:55:35 +00:00
|
|
|
if (!item.url && startsWithHTTP) {
|
|
|
|
item.url = pageURL;
|
|
|
|
}
|
2020-05-07 10:54:55 +00:00
|
|
|
assert(
|
|
|
|
item.url !== 'about:blank',
|
|
|
|
`Blank page can not have cookie "${item.name}"`
|
|
|
|
);
|
|
|
|
assert(
|
|
|
|
!String.prototype.startsWith.call(item.url || '', 'data:'),
|
|
|
|
`Data URL page can not have cookie "${item.name}"`
|
|
|
|
);
|
2017-08-24 19:21:46 +00:00
|
|
|
return item;
|
|
|
|
});
|
|
|
|
await this.deleteCookie(...items);
|
2022-06-14 11:55:35 +00:00
|
|
|
if (items.length) {
|
2022-06-22 13:25:44 +00:00
|
|
|
await this.#client.send('Network.setCookies', {cookies: items});
|
2022-06-14 11:55:35 +00:00
|
|
|
}
|
2017-08-24 19:21:46 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async exposeFunction(
|
2020-05-07 10:54:55 +00:00
|
|
|
name: string,
|
feat!: type inference for evaluation types (#8547)
This PR greatly improves the types within Puppeteer:
- **Almost everything** is auto-deduced.
- Parameters don't need to be specified in the function. They are deduced from the spread.
- Return types don't need to be specified. They are deduced from the function. (More on this below)
- Selections based on tag names correctly deduce element type, similar to TypeScript's mechanism for `getElementByTagName`.
- [**BREAKING CHANGE**] We've removed the ability to declare return types in type arguments for the following reasons:
1. Setting them will indubitably break auto-deduction.
2. You can just use `as ...` in TypeScript to coerce the correct type (given it makes sense).
- [**BREAKING CHANGE**] `waitFor` is officially gone.
To migrate to these changes, there are only four things you may need to change:
- If you set a return type using the `ReturnType` type parameter, remove it and use `as ...` and `HandleFor` (if necessary).
⛔ `evaluate<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluate(a, b) => {...}, a, b)) as ReturnType`
⛔ `evaluateHandle<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluateHandle(a, b) => {...}, a, b)) as HandleFor<ReturnType>`
- If you set any type parameters in the *parameters* of an evaluation function, remove them.
⛔ `evaluate(a: number, b: number) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
- If you set any type parameters in the method's declaration, remove them.
⛔ `evaluate<(a: number, b: number) => void>((a, b) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
2022-06-23 09:29:46 +00:00
|
|
|
pptrFunction: Function | {default: Function}
|
2020-05-07 10:54:55 +00:00
|
|
|
): Promise<void> {
|
2023-02-14 15:54:44 +00:00
|
|
|
if (this.#bindings.has(name)) {
|
2020-05-07 10:54:55 +00:00
|
|
|
throw new Error(
|
|
|
|
`Failed to add page binding with name ${name}: window['${name}'] already exists!`
|
|
|
|
);
|
2022-06-14 11:55:35 +00:00
|
|
|
}
|
2021-09-29 16:32:49 +00:00
|
|
|
|
2023-02-14 15:54:44 +00:00
|
|
|
let binding: Binding;
|
feat!: type inference for evaluation types (#8547)
This PR greatly improves the types within Puppeteer:
- **Almost everything** is auto-deduced.
- Parameters don't need to be specified in the function. They are deduced from the spread.
- Return types don't need to be specified. They are deduced from the function. (More on this below)
- Selections based on tag names correctly deduce element type, similar to TypeScript's mechanism for `getElementByTagName`.
- [**BREAKING CHANGE**] We've removed the ability to declare return types in type arguments for the following reasons:
1. Setting them will indubitably break auto-deduction.
2. You can just use `as ...` in TypeScript to coerce the correct type (given it makes sense).
- [**BREAKING CHANGE**] `waitFor` is officially gone.
To migrate to these changes, there are only four things you may need to change:
- If you set a return type using the `ReturnType` type parameter, remove it and use `as ...` and `HandleFor` (if necessary).
⛔ `evaluate<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluate(a, b) => {...}, a, b)) as ReturnType`
⛔ `evaluateHandle<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluateHandle(a, b) => {...}, a, b)) as HandleFor<ReturnType>`
- If you set any type parameters in the *parameters* of an evaluation function, remove them.
⛔ `evaluate(a: number, b: number) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
- If you set any type parameters in the method's declaration, remove them.
⛔ `evaluate<(a: number, b: number) => void>((a, b) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
2022-06-23 09:29:46 +00:00
|
|
|
switch (typeof pptrFunction) {
|
|
|
|
case 'function':
|
2023-02-14 15:54:44 +00:00
|
|
|
binding = new Binding(
|
|
|
|
name,
|
|
|
|
pptrFunction as (...args: unknown[]) => unknown
|
|
|
|
);
|
feat!: type inference for evaluation types (#8547)
This PR greatly improves the types within Puppeteer:
- **Almost everything** is auto-deduced.
- Parameters don't need to be specified in the function. They are deduced from the spread.
- Return types don't need to be specified. They are deduced from the function. (More on this below)
- Selections based on tag names correctly deduce element type, similar to TypeScript's mechanism for `getElementByTagName`.
- [**BREAKING CHANGE**] We've removed the ability to declare return types in type arguments for the following reasons:
1. Setting them will indubitably break auto-deduction.
2. You can just use `as ...` in TypeScript to coerce the correct type (given it makes sense).
- [**BREAKING CHANGE**] `waitFor` is officially gone.
To migrate to these changes, there are only four things you may need to change:
- If you set a return type using the `ReturnType` type parameter, remove it and use `as ...` and `HandleFor` (if necessary).
⛔ `evaluate<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluate(a, b) => {...}, a, b)) as ReturnType`
⛔ `evaluateHandle<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluateHandle(a, b) => {...}, a, b)) as HandleFor<ReturnType>`
- If you set any type parameters in the *parameters* of an evaluation function, remove them.
⛔ `evaluate(a: number, b: number) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
- If you set any type parameters in the method's declaration, remove them.
⛔ `evaluate<(a: number, b: number) => void>((a, b) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
2022-06-23 09:29:46 +00:00
|
|
|
break;
|
|
|
|
default:
|
2023-02-14 15:54:44 +00:00
|
|
|
binding = new Binding(
|
|
|
|
name,
|
|
|
|
pptrFunction.default as (...args: unknown[]) => unknown
|
|
|
|
);
|
feat!: type inference for evaluation types (#8547)
This PR greatly improves the types within Puppeteer:
- **Almost everything** is auto-deduced.
- Parameters don't need to be specified in the function. They are deduced from the spread.
- Return types don't need to be specified. They are deduced from the function. (More on this below)
- Selections based on tag names correctly deduce element type, similar to TypeScript's mechanism for `getElementByTagName`.
- [**BREAKING CHANGE**] We've removed the ability to declare return types in type arguments for the following reasons:
1. Setting them will indubitably break auto-deduction.
2. You can just use `as ...` in TypeScript to coerce the correct type (given it makes sense).
- [**BREAKING CHANGE**] `waitFor` is officially gone.
To migrate to these changes, there are only four things you may need to change:
- If you set a return type using the `ReturnType` type parameter, remove it and use `as ...` and `HandleFor` (if necessary).
⛔ `evaluate<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluate(a, b) => {...}, a, b)) as ReturnType`
⛔ `evaluateHandle<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluateHandle(a, b) => {...}, a, b)) as HandleFor<ReturnType>`
- If you set any type parameters in the *parameters* of an evaluation function, remove them.
⛔ `evaluate(a: number, b: number) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
- If you set any type parameters in the method's declaration, remove them.
⛔ `evaluate<(a: number, b: number) => void>((a, b) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
2022-06-23 09:29:46 +00:00
|
|
|
break;
|
2021-09-29 16:32:49 +00:00
|
|
|
}
|
|
|
|
|
2023-02-14 15:54:44 +00:00
|
|
|
this.#bindings.set(name, binding);
|
2017-06-21 20:51:06 +00:00
|
|
|
|
2022-06-14 11:16:21 +00:00
|
|
|
const expression = pageBindingInitString('exposedFun', name);
|
2023-06-02 12:08:36 +00:00
|
|
|
await this.#client.send('Runtime.addBinding', {name});
|
|
|
|
const {identifier} = await this.#client.send(
|
|
|
|
'Page.addScriptToEvaluateOnNewDocument',
|
|
|
|
{
|
|
|
|
source: expression,
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
this.#exposedFunctions.set(name, identifier);
|
|
|
|
|
2020-05-07 10:54:55 +00:00
|
|
|
await Promise.all(
|
2022-06-22 13:25:44 +00:00
|
|
|
this.frames().map(frame => {
|
2022-06-15 10:42:21 +00:00
|
|
|
return frame.evaluate(expression).catch(debugError);
|
|
|
|
})
|
2020-05-07 10:54:55 +00:00
|
|
|
);
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
2017-06-21 20:36:04 +00:00
|
|
|
|
2023-06-02 12:08:36 +00:00
|
|
|
override async removeExposedFunction(name: string): Promise<void> {
|
|
|
|
const exposedFun = this.#exposedFunctions.get(name);
|
|
|
|
if (!exposedFun) {
|
|
|
|
throw new Error(
|
|
|
|
`Failed to remove page binding with name ${name}: window['${name}'] does not exists!`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
await this.#client.send('Runtime.removeBinding', {name});
|
|
|
|
await this.removeScriptToEvaluateOnNewDocument(exposedFun);
|
|
|
|
|
|
|
|
await Promise.all(
|
|
|
|
this.frames().map(frame => {
|
|
|
|
return frame
|
|
|
|
.evaluate(name => {
|
|
|
|
// Removes the dangling Puppeteer binding wrapper.
|
|
|
|
// @ts-expect-error: In a different context.
|
|
|
|
globalThis[name] = undefined;
|
|
|
|
}, name)
|
|
|
|
.catch(debugError);
|
|
|
|
})
|
|
|
|
);
|
|
|
|
|
|
|
|
this.#exposedFunctions.delete(name);
|
|
|
|
this.#bindings.delete(name);
|
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async authenticate(credentials: Credentials): Promise<void> {
|
2023-09-01 07:49:33 +00:00
|
|
|
return await this.#frameManager.networkManager.authenticate(credentials);
|
2017-09-11 23:32:13 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async setExtraHTTPHeaders(
|
|
|
|
headers: Record<string, string>
|
|
|
|
): Promise<void> {
|
2023-09-01 07:49:33 +00:00
|
|
|
return await this.#frameManager.networkManager.setExtraHTTPHeaders(headers);
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async setUserAgent(
|
2021-06-29 16:29:55 +00:00
|
|
|
userAgent: string,
|
|
|
|
userAgentMetadata?: Protocol.Emulation.UserAgentMetadata
|
|
|
|
): Promise<void> {
|
2023-09-01 07:49:33 +00:00
|
|
|
return await this.#frameManager.networkManager.setUserAgent(
|
2022-08-10 21:34:29 +00:00
|
|
|
userAgent,
|
|
|
|
userAgentMetadata
|
|
|
|
);
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
2017-05-11 07:06:41 +00:00
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async metrics(): Promise<Metrics> {
|
2022-06-13 09:16:25 +00:00
|
|
|
const response = await this.#client.send('Performance.getMetrics');
|
|
|
|
return this.#buildMetricsObject(response.metrics);
|
2017-10-10 21:50:38 +00:00
|
|
|
}
|
|
|
|
|
2022-06-13 09:16:25 +00:00
|
|
|
#emitMetrics(event: Protocol.Performance.MetricsEvent): void {
|
2023-09-13 13:47:55 +00:00
|
|
|
this.emit(PageEvent.Metrics, {
|
2017-10-10 21:50:38 +00:00
|
|
|
title: event.title,
|
2022-06-13 09:16:25 +00:00
|
|
|
metrics: this.#buildMetricsObject(event.metrics),
|
2017-10-10 21:50:38 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-06-13 09:16:25 +00:00
|
|
|
#buildMetricsObject(metrics?: Protocol.Performance.Metric[]): Metrics {
|
2022-05-31 14:34:16 +00:00
|
|
|
const result: Record<
|
|
|
|
Protocol.Performance.Metric['name'],
|
|
|
|
Protocol.Performance.Metric['value']
|
|
|
|
> = {};
|
2017-10-10 21:50:38 +00:00
|
|
|
for (const metric of metrics || []) {
|
2022-05-31 14:34:16 +00:00
|
|
|
if (supportedMetrics.has(metric.name)) {
|
|
|
|
result[metric.name] = metric.value;
|
|
|
|
}
|
2017-10-10 21:50:38 +00:00
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2023-08-30 10:25:07 +00:00
|
|
|
#handleException(exception: Protocol.Runtime.ExceptionThrownEvent): void {
|
|
|
|
this.emit(
|
2023-09-13 13:47:55 +00:00
|
|
|
PageEvent.PageError,
|
2023-08-30 10:25:07 +00:00
|
|
|
createClientError(exception.exceptionDetails)
|
|
|
|
);
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
|
|
|
|
2022-06-13 09:16:25 +00:00
|
|
|
async #onConsoleAPI(
|
2020-07-10 10:51:52 +00:00
|
|
|
event: Protocol.Runtime.ConsoleAPICalledEvent
|
2020-05-07 10:54:55 +00:00
|
|
|
): Promise<void> {
|
2019-01-31 00:19:02 +00:00
|
|
|
if (event.executionContextId === 0) {
|
|
|
|
// DevTools protocol stores the last 1000 console messages. These
|
|
|
|
// messages are always reported even for removed execution contexts. In
|
|
|
|
// this case, they are marked with executionContextId = 0 and are
|
|
|
|
// reported upon enabling Runtime agent.
|
|
|
|
//
|
|
|
|
// Ignore these messages since:
|
|
|
|
// - there's no execution context we can use to operate with message
|
|
|
|
// arguments
|
|
|
|
// - these messages are reported before Puppeteer clients can subscribe
|
|
|
|
// to the 'console'
|
|
|
|
// page event.
|
|
|
|
//
|
2019-11-26 12:12:25 +00:00
|
|
|
// @see https://github.com/puppeteer/puppeteer/issues/3865
|
2019-01-31 00:19:02 +00:00
|
|
|
return;
|
|
|
|
}
|
2023-01-30 10:22:55 +00:00
|
|
|
const context = this.#frameManager.getExecutionContextById(
|
2021-10-28 09:25:49 +00:00
|
|
|
event.executionContextId,
|
2022-06-13 09:16:25 +00:00
|
|
|
this.#client
|
2020-05-07 10:54:55 +00:00
|
|
|
);
|
2023-01-30 10:22:55 +00:00
|
|
|
if (!context) {
|
|
|
|
debugError(
|
|
|
|
new Error(
|
|
|
|
`ExecutionContext not found for a console message: ${JSON.stringify(
|
|
|
|
event
|
|
|
|
)}`
|
|
|
|
)
|
|
|
|
);
|
|
|
|
return;
|
|
|
|
}
|
2022-06-22 13:25:44 +00:00
|
|
|
const values = event.args.map(arg => {
|
2023-09-01 12:12:29 +00:00
|
|
|
return createCdpHandle(context._world, arg);
|
2022-06-15 10:42:21 +00:00
|
|
|
});
|
2022-06-13 09:16:25 +00:00
|
|
|
this.#addConsoleMessage(event.type, values, event.stackTrace);
|
2018-06-07 18:21:35 +00:00
|
|
|
}
|
|
|
|
|
2022-06-13 09:16:25 +00:00
|
|
|
async #onBindingCalled(
|
2020-07-10 10:51:52 +00:00
|
|
|
event: Protocol.Runtime.BindingCalledEvent
|
2020-05-07 10:54:55 +00:00
|
|
|
): Promise<void> {
|
2023-02-14 15:54:44 +00:00
|
|
|
let payload: BindingPayload;
|
2020-10-23 10:45:47 +00:00
|
|
|
try {
|
|
|
|
payload = JSON.parse(event.payload);
|
|
|
|
} catch {
|
|
|
|
// The binding was either called by something in the page or it was
|
|
|
|
// called before our wrapper was initialized.
|
|
|
|
return;
|
|
|
|
}
|
2023-02-14 15:54:44 +00:00
|
|
|
const {type, name, seq, args, isTrivial} = payload;
|
|
|
|
if (type !== 'exposedFun') {
|
2022-06-14 11:55:35 +00:00
|
|
|
return;
|
|
|
|
}
|
2023-02-14 15:54:44 +00:00
|
|
|
|
|
|
|
const context = this.#frameManager.executionContextById(
|
|
|
|
event.executionContextId,
|
|
|
|
this.#client
|
|
|
|
);
|
|
|
|
if (!context) {
|
|
|
|
return;
|
2018-11-15 22:51:34 +00:00
|
|
|
}
|
2023-02-14 15:54:44 +00:00
|
|
|
|
|
|
|
const binding = this.#bindings.get(name);
|
|
|
|
await binding?.run(context, seq, args, isTrivial);
|
2018-06-18 20:41:03 +00:00
|
|
|
}
|
|
|
|
|
2022-06-13 09:16:25 +00:00
|
|
|
#addConsoleMessage(
|
2022-05-31 14:34:16 +00:00
|
|
|
eventType: ConsoleMessageType,
|
2020-05-07 10:54:55 +00:00
|
|
|
args: JSHandle[],
|
|
|
|
stackTrace?: Protocol.Runtime.StackTrace
|
|
|
|
): void {
|
2023-09-13 13:47:55 +00:00
|
|
|
if (!this.listenerCount(PageEvent.Console)) {
|
2022-06-22 13:25:44 +00:00
|
|
|
args.forEach(arg => {
|
2022-06-15 10:42:21 +00:00
|
|
|
return arg.dispose();
|
|
|
|
});
|
2017-07-25 04:43:54 +00:00
|
|
|
return;
|
|
|
|
}
|
2017-10-10 17:54:20 +00:00
|
|
|
const textTokens = [];
|
2023-08-30 10:02:59 +00:00
|
|
|
// eslint-disable-next-line max-len -- The comment is long.
|
|
|
|
// eslint-disable-next-line rulesdir/use-using -- These are not owned by this function.
|
2018-06-07 18:21:35 +00:00
|
|
|
for (const arg of args) {
|
2023-03-10 15:59:02 +00:00
|
|
|
const remoteObject = arg.remoteObject();
|
2022-06-14 11:55:35 +00:00
|
|
|
if (remoteObject.objectId) {
|
|
|
|
textTokens.push(arg.toString());
|
|
|
|
} else {
|
|
|
|
textTokens.push(valueFromRemoteObject(remoteObject));
|
|
|
|
}
|
2017-10-10 17:54:20 +00:00
|
|
|
}
|
2020-09-25 13:27:13 +00:00
|
|
|
const stackTraceLocations = [];
|
|
|
|
if (stackTrace) {
|
|
|
|
for (const callFrame of stackTrace.callFrames) {
|
|
|
|
stackTraceLocations.push({
|
|
|
|
url: callFrame.url,
|
|
|
|
lineNumber: callFrame.lineNumber,
|
|
|
|
columnNumber: callFrame.columnNumber,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2020-05-07 10:54:55 +00:00
|
|
|
const message = new ConsoleMessage(
|
2022-05-31 14:34:16 +00:00
|
|
|
eventType,
|
2020-05-07 10:54:55 +00:00
|
|
|
textTokens.join(' '),
|
|
|
|
args,
|
2020-09-25 13:27:13 +00:00
|
|
|
stackTraceLocations
|
2020-05-07 10:54:55 +00:00
|
|
|
);
|
2023-09-13 13:47:55 +00:00
|
|
|
this.emit(PageEvent.Console, message);
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
|
|
|
|
2022-06-13 09:16:25 +00:00
|
|
|
#onDialog(event: Protocol.Page.JavascriptDialogOpeningEvent): void {
|
2023-08-01 13:53:02 +00:00
|
|
|
const type = validateDialogType(event.type);
|
2023-09-13 19:57:26 +00:00
|
|
|
const dialog = new CdpDialog(
|
2022-06-13 09:16:25 +00:00
|
|
|
this.#client,
|
2023-08-01 13:53:02 +00:00
|
|
|
type,
|
2020-05-07 10:54:55 +00:00
|
|
|
event.message,
|
|
|
|
event.defaultPrompt
|
|
|
|
);
|
2023-09-13 13:47:55 +00:00
|
|
|
this.emit(PageEvent.Dialog, dialog);
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async reload(
|
|
|
|
options?: WaitForOptions
|
|
|
|
): Promise<HTTPResponse | null> {
|
2022-02-09 14:49:25 +00:00
|
|
|
const result = await Promise.all([
|
2020-07-10 10:51:52 +00:00
|
|
|
this.waitForNavigation(options),
|
2022-06-13 09:16:25 +00:00
|
|
|
this.#client.send('Page.reload'),
|
2020-07-10 10:51:52 +00:00
|
|
|
]);
|
2020-03-31 08:48:09 +00:00
|
|
|
|
2020-05-05 12:53:22 +00:00
|
|
|
return result[0];
|
2017-07-19 01:54:24 +00:00
|
|
|
}
|
2017-07-18 01:13:04 +00:00
|
|
|
|
2023-07-21 12:03:52 +00:00
|
|
|
override async createCDPSession(): Promise<CDPSession> {
|
|
|
|
return await this.target().createCDPSession();
|
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async waitForRequest(
|
2021-04-06 19:39:12 +00:00
|
|
|
urlOrPredicate: string | ((req: HTTPRequest) => boolean | Promise<boolean>),
|
2022-06-22 13:25:44 +00:00
|
|
|
options: {timeout?: number} = {}
|
2020-05-29 08:38:40 +00:00
|
|
|
): Promise<HTTPRequest> {
|
2022-06-22 13:25:44 +00:00
|
|
|
const {timeout = this.#timeoutSettings.timeout()} = options;
|
2023-09-01 07:49:33 +00:00
|
|
|
return await waitForEvent(
|
2022-08-10 21:34:29 +00:00
|
|
|
this.#frameManager.networkManager,
|
2023-09-13 13:47:55 +00:00
|
|
|
NetworkManagerEvent.Request,
|
2022-10-05 18:46:34 +00:00
|
|
|
async request => {
|
2022-06-14 11:55:35 +00:00
|
|
|
if (isString(urlOrPredicate)) {
|
|
|
|
return urlOrPredicate === request.url();
|
|
|
|
}
|
|
|
|
if (typeof urlOrPredicate === 'function') {
|
2022-10-05 18:46:34 +00:00
|
|
|
return !!(await urlOrPredicate(request));
|
2022-06-14 11:55:35 +00:00
|
|
|
}
|
2020-05-07 10:54:55 +00:00
|
|
|
return false;
|
|
|
|
},
|
|
|
|
timeout,
|
2023-05-30 07:03:42 +00:00
|
|
|
this.#sessionCloseDeferred.valueOrThrow()
|
2020-05-07 10:54:55 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async waitForResponse(
|
2021-04-06 19:39:12 +00:00
|
|
|
urlOrPredicate:
|
|
|
|
| string
|
|
|
|
| ((res: HTTPResponse) => boolean | Promise<boolean>),
|
2022-06-22 13:25:44 +00:00
|
|
|
options: {timeout?: number} = {}
|
2020-05-29 10:49:30 +00:00
|
|
|
): Promise<HTTPResponse> {
|
2022-06-22 13:25:44 +00:00
|
|
|
const {timeout = this.#timeoutSettings.timeout()} = options;
|
2023-09-01 07:49:33 +00:00
|
|
|
return await waitForEvent(
|
2022-08-10 21:34:29 +00:00
|
|
|
this.#frameManager.networkManager,
|
2023-09-13 13:47:55 +00:00
|
|
|
NetworkManagerEvent.Response,
|
2022-06-22 13:25:44 +00:00
|
|
|
async response => {
|
2022-06-14 11:55:35 +00:00
|
|
|
if (isString(urlOrPredicate)) {
|
|
|
|
return urlOrPredicate === response.url();
|
|
|
|
}
|
|
|
|
if (typeof urlOrPredicate === 'function') {
|
2020-11-25 10:35:47 +00:00
|
|
|
return !!(await urlOrPredicate(response));
|
2022-06-14 11:55:35 +00:00
|
|
|
}
|
2020-05-07 10:54:55 +00:00
|
|
|
return false;
|
|
|
|
},
|
|
|
|
timeout,
|
2023-05-30 07:03:42 +00:00
|
|
|
this.#sessionCloseDeferred.valueOrThrow()
|
2020-05-07 10:54:55 +00:00
|
|
|
);
|
2018-07-12 21:36:31 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async waitForNetworkIdle(
|
2022-06-22 13:25:44 +00:00
|
|
|
options: {idleTime?: number; timeout?: number} = {}
|
2021-09-11 20:28:12 +00:00
|
|
|
): Promise<void> {
|
2022-06-22 13:25:44 +00:00
|
|
|
const {idleTime = 500, timeout = this.#timeoutSettings.timeout()} = options;
|
2021-09-11 20:28:12 +00:00
|
|
|
|
2023-05-30 11:07:55 +00:00
|
|
|
await this._waitForNetworkIdle(
|
|
|
|
this.#frameManager.networkManager,
|
|
|
|
idleTime,
|
|
|
|
timeout,
|
|
|
|
this.#sessionCloseDeferred
|
2021-09-11 20:28:12 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async goBack(
|
|
|
|
options: WaitForOptions = {}
|
|
|
|
): Promise<HTTPResponse | null> {
|
2023-09-01 07:49:33 +00:00
|
|
|
return await this.#go(-1, options);
|
2017-07-19 02:11:37 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async goForward(
|
|
|
|
options: WaitForOptions = {}
|
|
|
|
): Promise<HTTPResponse | null> {
|
2023-09-01 07:49:33 +00:00
|
|
|
return await this.#go(+1, options);
|
2017-07-19 02:11:37 +00:00
|
|
|
}
|
|
|
|
|
2022-06-13 09:16:25 +00:00
|
|
|
async #go(
|
2020-05-07 10:54:55 +00:00
|
|
|
delta: number,
|
|
|
|
options: WaitForOptions
|
2020-05-29 10:49:30 +00:00
|
|
|
): Promise<HTTPResponse | null> {
|
2022-06-13 09:16:25 +00:00
|
|
|
const history = await this.#client.send('Page.getNavigationHistory');
|
2017-07-19 02:11:37 +00:00
|
|
|
const entry = history.entries[history.currentIndex + delta];
|
2022-06-14 11:55:35 +00:00
|
|
|
if (!entry) {
|
|
|
|
return null;
|
|
|
|
}
|
2020-07-10 10:51:52 +00:00
|
|
|
const result = await Promise.all([
|
2017-09-11 23:21:51 +00:00
|
|
|
this.waitForNavigation(options),
|
2022-06-22 13:25:44 +00:00
|
|
|
this.#client.send('Page.navigateToHistoryEntry', {entryId: entry.id}),
|
2017-09-11 23:21:51 +00:00
|
|
|
]);
|
2020-05-05 12:53:22 +00:00
|
|
|
return result[0];
|
2017-07-19 02:11:37 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async bringToFront(): Promise<void> {
|
2022-06-13 09:16:25 +00:00
|
|
|
await this.#client.send('Page.bringToFront');
|
2017-11-07 21:17:36 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async setJavaScriptEnabled(enabled: boolean): Promise<void> {
|
2023-06-15 12:30:37 +00:00
|
|
|
return await this.#emulationManager.setJavaScriptEnabled(enabled);
|
2017-08-23 21:08:56 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async setBypassCSP(enabled: boolean): Promise<void> {
|
2022-06-22 13:25:44 +00:00
|
|
|
await this.#client.send('Page.setBypassCSP', {enabled});
|
2018-04-06 23:35:50 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async emulateMediaType(type?: string): Promise<void> {
|
2023-06-15 12:30:37 +00:00
|
|
|
return await this.#emulationManager.emulateMediaType(type);
|
2019-10-23 11:55:00 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async emulateCPUThrottling(factor: number | null): Promise<void> {
|
2023-06-15 12:30:37 +00:00
|
|
|
return await this.#emulationManager.emulateCPUThrottling(factor);
|
2021-06-22 11:43:11 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async emulateMediaFeatures(
|
|
|
|
features?: MediaFeature[]
|
|
|
|
): Promise<void> {
|
2023-06-15 12:30:37 +00:00
|
|
|
return await this.#emulationManager.emulateMediaFeatures(features);
|
2017-08-18 23:49:02 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async emulateTimezone(timezoneId?: string): Promise<void> {
|
2023-06-15 12:30:37 +00:00
|
|
|
return await this.#emulationManager.emulateTimezone(timezoneId);
|
2019-10-23 13:49:39 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async emulateIdleState(overrides?: {
|
2020-09-14 09:31:23 +00:00
|
|
|
isUserActive: boolean;
|
|
|
|
isScreenUnlocked: boolean;
|
|
|
|
}): Promise<void> {
|
2023-06-15 12:30:37 +00:00
|
|
|
return await this.#emulationManager.emulateIdleState(overrides);
|
2020-09-14 09:31:23 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async emulateVisionDeficiency(
|
2020-07-22 09:04:53 +00:00
|
|
|
type?: Protocol.Emulation.SetEmulatedVisionDeficiencyRequest['type']
|
|
|
|
): Promise<void> {
|
2023-06-15 12:30:37 +00:00
|
|
|
return await this.#emulationManager.emulateVisionDeficiency(type);
|
2020-05-26 15:14:20 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async setViewport(viewport: Viewport): Promise<void> {
|
2022-06-13 09:16:25 +00:00
|
|
|
const needsReload = await this.#emulationManager.emulateViewport(viewport);
|
|
|
|
this.#viewport = viewport;
|
2022-06-14 11:55:35 +00:00
|
|
|
if (needsReload) {
|
|
|
|
await this.reload();
|
|
|
|
}
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override viewport(): Viewport | null {
|
2022-06-13 09:16:25 +00:00
|
|
|
return this.#viewport;
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
2017-06-21 20:36:04 +00:00
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async evaluateOnNewDocument<
|
feat!: type inference for evaluation types (#8547)
This PR greatly improves the types within Puppeteer:
- **Almost everything** is auto-deduced.
- Parameters don't need to be specified in the function. They are deduced from the spread.
- Return types don't need to be specified. They are deduced from the function. (More on this below)
- Selections based on tag names correctly deduce element type, similar to TypeScript's mechanism for `getElementByTagName`.
- [**BREAKING CHANGE**] We've removed the ability to declare return types in type arguments for the following reasons:
1. Setting them will indubitably break auto-deduction.
2. You can just use `as ...` in TypeScript to coerce the correct type (given it makes sense).
- [**BREAKING CHANGE**] `waitFor` is officially gone.
To migrate to these changes, there are only four things you may need to change:
- If you set a return type using the `ReturnType` type parameter, remove it and use `as ...` and `HandleFor` (if necessary).
⛔ `evaluate<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluate(a, b) => {...}, a, b)) as ReturnType`
⛔ `evaluateHandle<ReturnType>(a: number, b: number) => {...}, a, b)`
✅ `(await evaluateHandle(a, b) => {...}, a, b)) as HandleFor<ReturnType>`
- If you set any type parameters in the *parameters* of an evaluation function, remove them.
⛔ `evaluate(a: number, b: number) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
- If you set any type parameters in the method's declaration, remove them.
⛔ `evaluate<(a: number, b: number) => void>((a, b) => {...}, a, b)`
✅ `evaluate(a, b) => {...}, a, b)`
2022-06-23 09:29:46 +00:00
|
|
|
Params extends unknown[],
|
2023-07-17 08:52:54 +00:00
|
|
|
Func extends (...args: Params) => unknown = (...args: Params) => unknown,
|
2023-05-26 07:56:45 +00:00
|
|
|
>(
|
|
|
|
pageFunction: Func | string,
|
|
|
|
...args: Params
|
|
|
|
): Promise<NewDocumentScriptEvaluation> {
|
2022-06-14 11:16:21 +00:00
|
|
|
const source = evaluationString(pageFunction, ...args);
|
2023-05-26 07:56:45 +00:00
|
|
|
const {identifier} = await this.#client.send(
|
|
|
|
'Page.addScriptToEvaluateOnNewDocument',
|
|
|
|
{
|
|
|
|
source,
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
return {identifier};
|
|
|
|
}
|
|
|
|
|
|
|
|
override async removeScriptToEvaluateOnNewDocument(
|
|
|
|
identifier: string
|
|
|
|
): Promise<void> {
|
|
|
|
await this.#client.send('Page.removeScriptToEvaluateOnNewDocument', {
|
|
|
|
identifier,
|
2020-05-07 10:54:55 +00:00
|
|
|
});
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
2017-06-20 01:03:01 +00:00
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async setCacheEnabled(enabled = true): Promise<void> {
|
2022-08-10 21:34:29 +00:00
|
|
|
await this.#frameManager.networkManager.setCacheEnabled(enabled);
|
2018-02-08 05:58:48 +00:00
|
|
|
}
|
|
|
|
|
2023-01-18 14:06:20 +00:00
|
|
|
override screenshot(
|
|
|
|
options: ScreenshotOptions & {encoding: 'base64'}
|
|
|
|
): Promise<string>;
|
|
|
|
override screenshot(
|
|
|
|
options?: ScreenshotOptions & {encoding?: 'binary'}
|
|
|
|
): Promise<Buffer>;
|
2022-09-21 06:10:50 +00:00
|
|
|
override async screenshot(
|
|
|
|
options: ScreenshotOptions = {}
|
|
|
|
): Promise<Buffer | string> {
|
2022-05-31 14:34:16 +00:00
|
|
|
let screenshotType = Protocol.Page.CaptureScreenshotRequestFormat.Png;
|
2017-12-04 22:04:36 +00:00
|
|
|
// options.type takes precedence over inferring the type from options.path
|
2020-06-19 14:39:03 +00:00
|
|
|
// because it may be a 0-length file with no extension created beforehand
|
|
|
|
// (i.e. as a temp file).
|
2017-12-04 22:04:36 +00:00
|
|
|
if (options.type) {
|
2022-05-31 14:34:16 +00:00
|
|
|
screenshotType =
|
|
|
|
options.type as Protocol.Page.CaptureScreenshotRequestFormat;
|
2017-12-04 22:04:36 +00:00
|
|
|
} else if (options.path) {
|
2020-09-14 11:39:33 +00:00
|
|
|
const filePath = options.path;
|
|
|
|
const extension = filePath
|
|
|
|
.slice(filePath.lastIndexOf('.') + 1)
|
|
|
|
.toLowerCase();
|
2022-05-31 14:34:16 +00:00
|
|
|
switch (extension) {
|
|
|
|
case 'png':
|
|
|
|
screenshotType = Protocol.Page.CaptureScreenshotRequestFormat.Png;
|
|
|
|
break;
|
|
|
|
case 'jpeg':
|
|
|
|
case 'jpg':
|
|
|
|
screenshotType = Protocol.Page.CaptureScreenshotRequestFormat.Jpeg;
|
|
|
|
break;
|
|
|
|
case 'webp':
|
|
|
|
screenshotType = Protocol.Page.CaptureScreenshotRequestFormat.Webp;
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
throw new Error(
|
|
|
|
`Unsupported screenshot type for extension \`.${extension}\``
|
|
|
|
);
|
|
|
|
}
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
2017-12-04 22:04:36 +00:00
|
|
|
|
2017-06-21 20:51:06 +00:00
|
|
|
if (options.quality) {
|
2020-05-07 10:54:55 +00:00
|
|
|
assert(
|
2022-05-31 14:34:16 +00:00
|
|
|
screenshotType === Protocol.Page.CaptureScreenshotRequestFormat.Jpeg ||
|
|
|
|
screenshotType === Protocol.Page.CaptureScreenshotRequestFormat.Webp,
|
2020-05-07 10:54:55 +00:00
|
|
|
'options.quality is unsupported for the ' +
|
|
|
|
screenshotType +
|
|
|
|
' screenshots'
|
|
|
|
);
|
|
|
|
assert(
|
|
|
|
typeof options.quality === 'number',
|
|
|
|
'Expected options.quality to be a number but found ' +
|
|
|
|
typeof options.quality
|
|
|
|
);
|
|
|
|
assert(
|
|
|
|
Number.isInteger(options.quality),
|
|
|
|
'Expected options.quality to be an integer'
|
|
|
|
);
|
|
|
|
assert(
|
|
|
|
options.quality >= 0 && options.quality <= 100,
|
|
|
|
'Expected options.quality to be between 0 and 100 (inclusive), got ' +
|
|
|
|
options.quality
|
|
|
|
);
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
2020-05-07 10:54:55 +00:00
|
|
|
assert(
|
|
|
|
!options.clip || !options.fullPage,
|
|
|
|
'options.clip and options.fullPage are exclusive'
|
|
|
|
);
|
2017-06-21 20:51:06 +00:00
|
|
|
if (options.clip) {
|
2020-05-07 10:54:55 +00:00
|
|
|
assert(
|
|
|
|
typeof options.clip.x === 'number',
|
|
|
|
'Expected options.clip.x to be a number but found ' +
|
|
|
|
typeof options.clip.x
|
|
|
|
);
|
|
|
|
assert(
|
|
|
|
typeof options.clip.y === 'number',
|
|
|
|
'Expected options.clip.y to be a number but found ' +
|
|
|
|
typeof options.clip.y
|
|
|
|
);
|
|
|
|
assert(
|
|
|
|
typeof options.clip.width === 'number',
|
|
|
|
'Expected options.clip.width to be a number but found ' +
|
|
|
|
typeof options.clip.width
|
|
|
|
);
|
|
|
|
assert(
|
|
|
|
typeof options.clip.height === 'number',
|
|
|
|
'Expected options.clip.height to be a number but found ' +
|
|
|
|
typeof options.clip.height
|
|
|
|
);
|
|
|
|
assert(
|
|
|
|
options.clip.width !== 0,
|
|
|
|
'Expected options.clip.width not to be 0.'
|
|
|
|
);
|
|
|
|
assert(
|
|
|
|
options.clip.height !== 0,
|
|
|
|
'Expected options.clip.height not to be 0.'
|
|
|
|
);
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
2023-09-01 07:49:33 +00:00
|
|
|
return await this.#screenshotTaskQueue.postTask(() => {
|
2022-06-15 10:42:21 +00:00
|
|
|
return this.#screenshotTask(screenshotType, options);
|
|
|
|
});
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
|
|
|
|
2022-06-13 09:16:25 +00:00
|
|
|
async #screenshotTask(
|
2021-09-21 14:26:20 +00:00
|
|
|
format: Protocol.Page.CaptureScreenshotRequestFormat,
|
2022-05-31 14:34:16 +00:00
|
|
|
options: ScreenshotOptions = {}
|
2020-05-07 10:54:55 +00:00
|
|
|
): Promise<Buffer | string> {
|
2022-06-13 09:16:25 +00:00
|
|
|
await this.#client.send('Target.activateTarget', {
|
|
|
|
targetId: this.#target._targetId,
|
2020-05-07 10:54:55 +00:00
|
|
|
});
|
2019-01-15 22:34:31 +00:00
|
|
|
let clip = options.clip ? processClip(options.clip) : undefined;
|
2022-10-25 10:55:19 +00:00
|
|
|
let captureBeyondViewport = options.captureBeyondViewport ?? true;
|
|
|
|
const fromSurface = options.fromSurface;
|
2017-07-26 22:28:44 +00:00
|
|
|
|
2017-07-17 19:15:06 +00:00
|
|
|
if (options.fullPage) {
|
2021-02-03 13:30:46 +00:00
|
|
|
// Overwrite clip for full page.
|
2022-10-25 10:55:19 +00:00
|
|
|
clip = undefined;
|
2021-04-06 13:14:31 +00:00
|
|
|
|
|
|
|
if (!captureBeyondViewport) {
|
2023-01-02 10:01:36 +00:00
|
|
|
const metrics = await this.#client.send('Page.getLayoutMetrics');
|
|
|
|
// Fallback to `contentSize` in case of using Firefox.
|
|
|
|
const {width, height} = metrics.cssContentSize || metrics.contentSize;
|
2021-05-12 14:48:30 +00:00
|
|
|
const {
|
|
|
|
isMobile = false,
|
|
|
|
deviceScaleFactor = 1,
|
|
|
|
isLandscape = false,
|
2022-06-13 09:16:25 +00:00
|
|
|
} = this.#viewport || {};
|
2021-05-12 14:48:30 +00:00
|
|
|
const screenOrientation: Protocol.Emulation.ScreenOrientation =
|
|
|
|
isLandscape
|
2022-06-22 13:25:44 +00:00
|
|
|
? {angle: 90, type: 'landscapePrimary'}
|
|
|
|
: {angle: 0, type: 'portraitPrimary'};
|
2022-06-13 09:16:25 +00:00
|
|
|
await this.#client.send('Emulation.setDeviceMetricsOverride', {
|
2021-04-06 13:14:31 +00:00
|
|
|
mobile: isMobile,
|
|
|
|
width,
|
|
|
|
height,
|
|
|
|
deviceScaleFactor,
|
|
|
|
screenOrientation,
|
|
|
|
});
|
|
|
|
}
|
2022-10-25 10:55:19 +00:00
|
|
|
} else if (!clip) {
|
|
|
|
captureBeyondViewport = false;
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
2022-10-25 10:55:19 +00:00
|
|
|
|
2020-05-07 10:54:55 +00:00
|
|
|
const shouldSetDefaultBackground =
|
2021-09-21 14:26:20 +00:00
|
|
|
options.omitBackground && (format === 'png' || format === 'webp');
|
2021-03-18 19:57:32 +00:00
|
|
|
if (shouldSetDefaultBackground) {
|
2023-06-15 12:30:37 +00:00
|
|
|
await this.#emulationManager.setTransparentBackgroundColor();
|
2021-03-18 19:57:32 +00:00
|
|
|
}
|
2021-04-06 13:14:31 +00:00
|
|
|
|
2022-06-13 09:16:25 +00:00
|
|
|
const result = await this.#client.send('Page.captureScreenshot', {
|
2020-05-07 10:54:55 +00:00
|
|
|
format,
|
2023-07-03 09:43:34 +00:00
|
|
|
optimizeForSpeed: options.optimizeForSpeed,
|
2020-05-07 10:54:55 +00:00
|
|
|
quality: options.quality,
|
2022-10-25 10:55:19 +00:00
|
|
|
clip: clip && {
|
|
|
|
...clip,
|
|
|
|
scale: clip.scale ?? 1,
|
|
|
|
},
|
2021-04-06 13:14:31 +00:00
|
|
|
captureBeyondViewport,
|
2022-06-27 12:37:37 +00:00
|
|
|
fromSurface,
|
2020-05-07 10:54:55 +00:00
|
|
|
});
|
2021-03-18 19:57:32 +00:00
|
|
|
if (shouldSetDefaultBackground) {
|
2023-06-15 12:30:37 +00:00
|
|
|
await this.#emulationManager.resetDefaultBackgroundColor();
|
2021-03-18 19:57:32 +00:00
|
|
|
}
|
2017-07-17 19:15:06 +00:00
|
|
|
|
2022-06-14 11:55:35 +00:00
|
|
|
if (options.fullPage && this.#viewport) {
|
2022-06-13 09:16:25 +00:00
|
|
|
await this.setViewport(this.#viewport);
|
2022-06-14 11:55:35 +00:00
|
|
|
}
|
2017-07-17 19:15:06 +00:00
|
|
|
|
2023-03-28 11:02:59 +00:00
|
|
|
if (options.encoding === 'base64') {
|
|
|
|
return result.data;
|
2020-09-28 09:35:35 +00:00
|
|
|
}
|
2023-03-28 11:02:59 +00:00
|
|
|
|
|
|
|
const buffer = Buffer.from(result.data, 'base64');
|
|
|
|
await this._maybeWriteBufferToFile(options.path, buffer);
|
|
|
|
|
2017-06-21 20:51:06 +00:00
|
|
|
return buffer;
|
2019-01-15 22:34:31 +00:00
|
|
|
|
2022-09-07 05:27:40 +00:00
|
|
|
function processClip(clip: ScreenshotClip): ScreenshotClip {
|
2019-01-15 22:34:31 +00:00
|
|
|
const x = Math.round(clip.x);
|
|
|
|
const y = Math.round(clip.y);
|
|
|
|
const width = Math.round(clip.width + clip.x - x);
|
|
|
|
const height = Math.round(clip.height + clip.y - y);
|
2022-09-07 05:27:40 +00:00
|
|
|
return {x, y, width, height, scale: clip.scale};
|
2019-01-15 22:34:31 +00:00
|
|
|
}
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async createPDFStream(options: PDFOptions = {}): Promise<Readable> {
|
2023-03-28 11:57:58 +00:00
|
|
|
const {
|
|
|
|
landscape,
|
|
|
|
displayHeaderFooter,
|
|
|
|
headerTemplate,
|
|
|
|
footerTemplate,
|
|
|
|
printBackground,
|
|
|
|
scale,
|
|
|
|
width: paperWidth,
|
|
|
|
height: paperHeight,
|
|
|
|
margin,
|
|
|
|
pageRanges,
|
|
|
|
preferCSSPageSize,
|
|
|
|
omitBackground,
|
|
|
|
timeout,
|
|
|
|
} = this._getPDFOptions(options);
|
2017-06-21 20:51:06 +00:00
|
|
|
|
2023-03-28 11:57:58 +00:00
|
|
|
if (omitBackground) {
|
2023-06-15 12:30:37 +00:00
|
|
|
await this.#emulationManager.setTransparentBackgroundColor();
|
2021-03-18 19:57:32 +00:00
|
|
|
}
|
|
|
|
|
2022-06-13 09:16:25 +00:00
|
|
|
const printCommandPromise = this.#client.send('Page.printToPDF', {
|
2019-06-15 05:36:06 +00:00
|
|
|
transferMode: 'ReturnAsStream',
|
2023-03-28 11:57:58 +00:00
|
|
|
landscape,
|
|
|
|
displayHeaderFooter,
|
|
|
|
headerTemplate,
|
|
|
|
footerTemplate,
|
|
|
|
printBackground,
|
|
|
|
scale,
|
|
|
|
paperWidth,
|
|
|
|
paperHeight,
|
|
|
|
marginTop: margin.top,
|
|
|
|
marginBottom: margin.bottom,
|
|
|
|
marginLeft: margin.left,
|
|
|
|
marginRight: margin.right,
|
|
|
|
pageRanges,
|
|
|
|
preferCSSPageSize,
|
2017-06-21 20:51:06 +00:00
|
|
|
});
|
2021-03-18 19:57:32 +00:00
|
|
|
|
2022-06-14 11:16:21 +00:00
|
|
|
const result = await waitWithTimeout(
|
2021-09-14 16:11:14 +00:00
|
|
|
printCommandPromise,
|
|
|
|
'Page.printToPDF',
|
2023-03-28 11:57:58 +00:00
|
|
|
timeout
|
2021-09-14 16:11:14 +00:00
|
|
|
);
|
|
|
|
|
2023-03-28 11:57:58 +00:00
|
|
|
if (omitBackground) {
|
2023-06-15 12:30:37 +00:00
|
|
|
await this.#emulationManager.resetDefaultBackgroundColor();
|
2021-03-18 19:57:32 +00:00
|
|
|
}
|
|
|
|
|
2022-05-31 14:34:16 +00:00
|
|
|
assert(result.stream, '`stream` is missing from `Page.printToPDF');
|
2023-09-01 07:49:33 +00:00
|
|
|
return await getReadableFromProtocolStream(this.#client, result.stream);
|
2021-06-23 12:51:38 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async pdf(options: PDFOptions = {}): Promise<Buffer> {
|
2022-06-22 13:25:44 +00:00
|
|
|
const {path = undefined} = options;
|
2021-06-23 12:51:38 +00:00
|
|
|
const readable = await this.createPDFStream(options);
|
2022-06-14 11:16:21 +00:00
|
|
|
const buffer = await getReadableAsBuffer(readable, path);
|
2022-05-31 14:34:16 +00:00
|
|
|
assert(buffer, 'Could not create buffer');
|
|
|
|
return buffer;
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override async close(
|
2022-06-22 13:25:44 +00:00
|
|
|
options: {runBeforeUnload?: boolean} = {runBeforeUnload: undefined}
|
2020-05-07 10:54:55 +00:00
|
|
|
): Promise<void> {
|
2022-06-13 09:16:25 +00:00
|
|
|
const connection = this.#client.connection();
|
2020-05-07 10:54:55 +00:00
|
|
|
assert(
|
2022-06-13 09:16:25 +00:00
|
|
|
connection,
|
2020-05-07 10:54:55 +00:00
|
|
|
'Protocol error: Connection closed. Most likely the page has been closed.'
|
|
|
|
);
|
2018-05-02 22:51:45 +00:00
|
|
|
const runBeforeUnload = !!options.runBeforeUnload;
|
|
|
|
if (runBeforeUnload) {
|
2022-06-13 09:16:25 +00:00
|
|
|
await this.#client.send('Page.close');
|
2018-05-02 22:51:45 +00:00
|
|
|
} else {
|
2022-06-13 09:16:25 +00:00
|
|
|
await connection.send('Target.closeTarget', {
|
|
|
|
targetId: this.#target._targetId,
|
2020-05-07 10:54:55 +00:00
|
|
|
});
|
2023-05-26 09:42:22 +00:00
|
|
|
await this.#target._isClosedDeferred.valueOrThrow();
|
2018-05-02 22:51:45 +00:00
|
|
|
}
|
2017-06-21 20:51:06 +00:00
|
|
|
}
|
2017-06-28 01:27:22 +00:00
|
|
|
|
2022-09-21 06:10:50 +00:00
|
|
|
override isClosed(): boolean {
|
2022-06-13 09:16:25 +00:00
|
|
|
return this.#closed;
|
2018-05-25 23:53:57 +00:00
|
|
|
}
|
|
|
|
|
2023-09-13 19:57:26 +00:00
|
|
|
override get mouse(): CdpMouse {
|
2022-06-13 09:16:25 +00:00
|
|
|
return this.#mouse;
|
2017-07-22 03:29:31 +00:00
|
|
|
}
|
|
|
|
|
2023-03-21 09:21:10 +00:00
|
|
|
/**
|
|
|
|
* This method is typically coupled with an action that triggers a device
|
|
|
|
* request from an api such as WebBluetooth.
|
|
|
|
*
|
|
|
|
* :::caution
|
|
|
|
*
|
|
|
|
* This must be called before the device request is made. It will not return a
|
|
|
|
* currently active device prompt.
|
|
|
|
*
|
|
|
|
* :::
|
|
|
|
*
|
|
|
|
* @example
|
|
|
|
*
|
|
|
|
* ```ts
|
|
|
|
* const [devicePrompt] = Promise.all([
|
|
|
|
* page.waitForDevicePrompt(),
|
|
|
|
* page.click('#connect-bluetooth'),
|
|
|
|
* ]);
|
|
|
|
* await devicePrompt.select(
|
|
|
|
* await devicePrompt.waitForDevice(({name}) => name.includes('My Device'))
|
|
|
|
* );
|
|
|
|
* ```
|
|
|
|
*/
|
2023-09-01 12:12:29 +00:00
|
|
|
override async waitForDevicePrompt(
|
2023-03-21 09:21:10 +00:00
|
|
|
options: WaitTimeoutOptions = {}
|
|
|
|
): Promise<DeviceRequestPrompt> {
|
2023-09-01 12:12:29 +00:00
|
|
|
return await this.mainFrame().waitForDevicePrompt(options);
|
2023-03-21 09:21:10 +00:00
|
|
|
}
|
2017-05-11 07:06:41 +00:00
|
|
|
}
|
|
|
|
|
2020-05-05 12:53:22 +00:00
|
|
|
const supportedMetrics = new Set<string>([
|
2017-10-10 21:50:38 +00:00
|
|
|
'Timestamp',
|
2017-10-12 08:17:06 +00:00
|
|
|
'Documents',
|
|
|
|
'Frames',
|
|
|
|
'JSEventListeners',
|
|
|
|
'Nodes',
|
2017-10-10 21:50:38 +00:00
|
|
|
'LayoutCount',
|
|
|
|
'RecalcStyleCount',
|
|
|
|
'LayoutDuration',
|
|
|
|
'RecalcStyleDuration',
|
|
|
|
'ScriptDuration',
|
|
|
|
'TaskDuration',
|
|
|
|
'JSHeapUsedSize',
|
|
|
|
'JSHeapTotalSize',
|
|
|
|
]);
|