puppeteer/packages/puppeteer-core/src/common/Page.ts

1698 lines
48 KiB
TypeScript
Raw Normal View History

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.
*/
import {Protocol} from 'devtools-protocol';
import type {Readable} from 'stream';
import type {Browser} from '../api/Browser.js';
import type {BrowserContext} from '../api/BrowserContext.js';
import {
GeolocationOptions,
MediaFeature,
Metrics,
Page,
PageEmittedEvents,
ScreenshotClip,
ScreenshotOptions,
WaitForOptions,
WaitTimeoutOptions,
} from '../api/Page.js';
import {assert} from '../util/assert.js';
2022-09-01 15:09:57 +00:00
import {
createDeferredPromise,
DeferredPromise,
} from '../util/DeferredPromise.js';
import {isErrorLike} from '../util/ErrorLike.js';
import {Accessibility} from './Accessibility.js';
import {
CDPSession,
CDPSessionEmittedEvents,
isTargetClosedError,
} from './Connection.js';
import {ConsoleMessage, ConsoleMessageType} from './ConsoleMessage.js';
import {Coverage} from './Coverage.js';
import {Dialog} from './Dialog.js';
2022-06-23 09:31:43 +00:00
import {ElementHandle} from './ElementHandle.js';
import {EmulationManager} from './EmulationManager.js';
import {FileChooser} from './FileChooser.js';
import {
Frame,
FrameAddScriptTagOptions,
FrameAddStyleTagOptions,
FrameWaitForFunctionOptions,
} from './Frame.js';
import {FrameManager, FrameManagerEmittedEvents} from './FrameManager.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 {HTTPRequest} from './HTTPRequest.js';
import {HTTPResponse} from './HTTPResponse.js';
import {Keyboard, Mouse, MouseButton, Touchscreen} from './Input.js';
import {WaitForSelectorOptions} from './IsolatedWorld.js';
import {MAIN_WORLD} from './IsolatedWorlds.js';
2022-06-23 09:31:43 +00:00
import {JSHandle} from './JSHandle.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 {
Credentials,
NetworkConditions,
NetworkManagerEmittedEvents,
} from './NetworkManager.js';
import {LowerCasePaperFormat, PDFOptions, _paperFormats} from './PDFOptions.js';
import {Viewport} from './PuppeteerViewport.js';
import {Target} from './Target.js';
import {TargetManagerEmittedEvents} from './TargetManager.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 {TaskQueue} from './TaskQueue.js';
import {TimeoutSettings} from './TimeoutSettings.js';
import {Tracing} from './Tracing.js';
import {EvaluateFunc, HandleFor, NodeFor} from './types.js';
import {
2022-06-27 07:24:23 +00:00
createJSHandle,
debugError,
evaluationString,
getExceptionMessage,
getReadableAsBuffer,
getReadableFromProtocolStream,
2022-09-01 15:09:57 +00:00
importFS,
isNumber,
isString,
pageBindingDeliverErrorString,
pageBindingDeliverErrorValueString,
pageBindingDeliverResultString,
pageBindingInitString,
releaseObject,
valueFromRemoteObject,
waitForEvent,
waitWithTimeout,
} from './util.js';
import {WebWorker} from './WebWorker.js';
/**
* @internal
*/
export class CDPPage extends Page {
/**
* @internal
*/
2022-06-13 09:16:25 +00:00
static async _create(
2020-05-07 10:54:55 +00:00
client: CDPSession,
target: Target,
ignoreHTTPSErrors: boolean,
defaultViewport: Viewport | null,
screenshotTaskQueue: TaskQueue
): Promise<CDPPage> {
const page = new CDPPage(
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) {
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;
#target: Target;
#keyboard: Keyboard;
#mouse: Mouse;
#timeoutSettings = new TimeoutSettings();
#touchscreen: Touchscreen;
#accessibility: Accessibility;
#frameManager: FrameManager;
#emulationManager: EmulationManager;
#tracing: Tracing;
#pageBindings = new Map<string, Function>();
#coverage: Coverage;
#javascriptEnabled = true;
#viewport: Viewport | null;
#screenshotTaskQueue: TaskQueue;
#workers = new Map<string, WebWorker>();
#fileChooserPromises = new Set<DeferredPromise<FileChooser>>();
2022-06-13 09:16:25 +00:00
#disconnectPromise?: Promise<Error>;
#userDragInterceptionEnabled = false;
/**
* @internal
*/
constructor(
client: CDPSession,
target: Target,
ignoreHTTPSErrors: boolean,
screenshotTaskQueue: TaskQueue
) {
2017-06-21 20:51:06 +00:00
super();
2022-06-13 09:16:25 +00:00
this.#client = client;
this.#target = target;
this.#keyboard = new Keyboard(client);
this.#mouse = new Mouse(client, this.#keyboard);
this.#touchscreen = new Touchscreen(client, this.#keyboard);
this.#accessibility = new Accessibility(client);
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);
this.#tracing = new Tracing(client);
this.#coverage = new Coverage(client);
this.#screenshotTaskQueue = screenshotTaskQueue;
this.#viewport = null;
2017-06-21 20:51:06 +00:00
this.#target
._targetManager()
.addTargetInterceptor(this.#client, this.#onAttachedToTarget);
this.#target
._targetManager()
.on(TargetManagerEmittedEvents.TargetGone, this.#onDetachedFromTarget);
this.#frameManager.on(FrameManagerEmittedEvents.FrameAttached, event => {
return this.emit(PageEmittedEvents.FrameAttached, event);
});
this.#frameManager.on(FrameManagerEmittedEvents.FrameDetached, event => {
return this.emit(PageEmittedEvents.FrameDetached, event);
});
this.#frameManager.on(FrameManagerEmittedEvents.FrameNavigated, event => {
return this.emit(PageEmittedEvents.FrameNavigated, event);
});
2017-06-21 20:51:06 +00:00
const networkManager = this.#frameManager.networkManager;
networkManager.on(NetworkManagerEmittedEvents.Request, event => {
return this.emit(PageEmittedEvents.Request, event);
});
networkManager.on(
NetworkManagerEmittedEvents.RequestServedFromCache,
event => {
return this.emit(PageEmittedEvents.RequestServedFromCache, event);
}
2020-05-07 10:54:55 +00:00
);
networkManager.on(NetworkManagerEmittedEvents.Response, event => {
return this.emit(PageEmittedEvents.Response, event);
});
networkManager.on(NetworkManagerEmittedEvents.RequestFailed, event => {
return this.emit(PageEmittedEvents.RequestFailed, event);
});
networkManager.on(NetworkManagerEmittedEvents.RequestFinished, event => {
return this.emit(PageEmittedEvents.RequestFinished, event);
});
client.on('Page.domContentEventFired', () => {
return this.emit(PageEmittedEvents.DOMContentLoaded);
});
client.on('Page.loadEventFired', () => {
return this.emit(PageEmittedEvents.Load);
});
client.on('Runtime.consoleAPICalled', event => {
return this.#onConsoleAPI(event);
});
client.on('Runtime.bindingCalled', event => {
return this.#onBindingCalled(event);
});
client.on('Page.javascriptDialogOpening', event => {
return this.#onDialog(event);
});
client.on('Runtime.exceptionThrown', exception => {
return this.#handleException(exception.exceptionDetails);
});
client.on('Inspector.targetCrashed', () => {
return this.#onTargetCrashed();
});
client.on('Performance.metrics', event => {
return this.#emitMetrics(event);
});
client.on('Log.entryAdded', event => {
return this.#onLogEntryAdded(event);
});
client.on('Page.fileChooserOpened', event => {
return this.#onFileChooser(event);
});
2022-06-13 09:16:25 +00:00
this.#target._isClosedPromise.then(() => {
this.#target
._targetManager()
.removeTargetInterceptor(this.#client, this.#onAttachedToTarget);
this.#target
._targetManager()
.off(TargetManagerEmittedEvents.TargetGone, this.#onDetachedFromTarget);
this.emit(PageEmittedEvents.Close);
2022-06-13 09:16:25 +00:00
this.#closed = true;
});
}
#onDetachedFromTarget = (target: Target) => {
const sessionId = target._session()?.id();
this.#frameManager.onDetachedFromTarget(target);
const worker = this.#workers.get(sessionId!);
if (!worker) {
return;
}
this.#workers.delete(sessionId!);
this.emit(PageEmittedEvents.WorkerDestroyed, worker);
};
#onAttachedToTarget = async (createdTarget: Target) => {
this.#frameManager.onAttachedToTarget(createdTarget);
if (createdTarget._getTargetInfo().type === 'worker') {
const session = createdTarget._session();
assert(session);
const worker = new WebWorker(
session,
createdTarget.url(),
this.#addConsoleMessage.bind(this),
this.#handleException.bind(this)
);
this.#workers.set(session.id(), worker);
this.emit(PageEmittedEvents.WorkerCreated, worker);
}
if (createdTarget._session()) {
this.#target
._targetManager()
.addTargetInterceptor(
createdTarget._session()!,
this.#onAttachedToTarget
);
}
};
2022-06-13 09:16:25 +00:00
async #initialize(): Promise<void> {
try {
await Promise.all([
this.#frameManager.initialize(),
this.#client.send('Performance.enable'),
this.#client.send('Log.enable'),
]);
} catch (err) {
if (isErrorLike(err) && isTargetClosedError(err)) {
debugError(err);
} else {
throw err;
}
}
}
2022-06-13 09:16:25 +00:00
async #onFileChooser(
event: Protocol.Page.FileChooserOpenedEvent
2020-05-07 10:54:55 +00:00
): Promise<void> {
if (!this.#fileChooserPromises.size) {
2022-06-14 11:55:35 +00:00
return;
}
2022-06-13 09:16:25 +00:00
const frame = this.#frameManager.frame(event.frameId);
assert(frame, 'This should never happen.');
// This is guaranteed to be an HTMLInputElement handle by the event.
const handle = (await frame.worlds[MAIN_WORLD].adoptBackendNode(
event.backendNodeId
)) as ElementHandle<HTMLInputElement>;
const fileChooser = new FileChooser(handle, event);
for (const promise of this.#fileChooserPromises) {
promise.resolve(fileChooser);
2022-06-14 11:55:35 +00:00
}
this.#fileChooserPromises.clear();
}
/**
* @internal
*/
_client(): CDPSession {
return this.#client;
}
override isDragInterceptionEnabled(): boolean {
2022-06-13 09:16:25 +00:00
return this.#userDragInterceptionEnabled;
}
override isJavaScriptEnabled(): boolean {
2022-06-13 09:16:25 +00:00
return this.#javascriptEnabled;
}
override waitForFileChooser(
options: WaitTimeoutOptions = {}
): Promise<FileChooser> {
const needsEnable = this.#fileChooserPromises.size === 0;
const {timeout = this.#timeoutSettings.timeout()} = options;
const promise = createDeferredPromise<FileChooser>({
message: `Waiting for \`FileChooser\` failed: ${timeout}ms exceeded`,
timeout,
});
this.#fileChooserPromises.add(promise);
let enablePromise: Promise<void> | undefined;
if (needsEnable) {
enablePromise = this.#client.send('Page.setInterceptFileChooserDialog', {
enabled: true,
});
}
return Promise.all([promise, enablePromise])
.then(([result]) => {
return result;
})
.catch(error => {
this.#fileChooserPromises.delete(promise);
throw error;
});
}
override async setGeolocation(options: GeolocationOptions): Promise<void> {
const {longitude, latitude, accuracy = 0} = options;
2022-06-14 11:55:35 +00:00
if (longitude < -180 || longitude > 180) {
2020-05-07 10:54:55 +00:00
throw new Error(
`Invalid longitude "${longitude}": precondition -180 <= LONGITUDE <= 180 failed.`
);
2022-06-14 11:55:35 +00:00
}
if (latitude < -90 || latitude > 90) {
2020-05-07 10:54:55 +00:00
throw new Error(
`Invalid latitude "${latitude}": precondition -90 <= LATITUDE <= 90 failed.`
);
2022-06-14 11:55:35 +00:00
}
if (accuracy < 0) {
2020-05-07 10:54:55 +00:00
throw new Error(
`Invalid accuracy "${accuracy}": precondition 0 <= ACCURACY failed.`
);
2022-06-14 11:55:35 +00:00
}
2022-06-13 09:16:25 +00:00
await this.#client.send('Emulation.setGeolocationOverride', {
2020-05-07 10:54:55 +00:00
longitude,
latitude,
accuracy,
});
}
override target(): Target {
2022-06-13 09:16:25 +00:00
return this.#target;
}
override browser(): Browser {
2022-06-13 09:16:25 +00:00
return this.#target.browser();
}
override browserContext(): BrowserContext {
2022-06-13 09:16:25 +00:00
return this.#target.browserContext();
}
2022-06-13 09:16:25 +00:00
#onTargetCrashed(): void {
this.emit('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 {
const {level, text, args, source, url, lineNumber} = event.entry;
2022-06-14 11:55:35 +00:00
if (args) {
args.map(arg => {
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(
PageEmittedEvents.Console,
new ConsoleMessage(level, text, [], [{url, lineNumber}])
2020-05-07 10:54:55 +00:00
);
2022-06-14 11:55:35 +00:00
}
}
override mainFrame(): Frame {
2022-06-13 09:16:25 +00:00
return this.#frameManager.mainFrame();
2017-06-21 20:51:06 +00:00
}
override get keyboard(): Keyboard {
2022-06-13 09:16:25 +00:00
return this.#keyboard;
}
override get touchscreen(): Touchscreen {
2022-06-13 09:16:25 +00:00
return this.#touchscreen;
}
override get coverage(): Coverage {
2022-06-13 09:16:25 +00:00
return this.#coverage;
}
override get tracing(): Tracing {
2022-06-13 09:16:25 +00:00
return this.#tracing;
}
override get accessibility(): Accessibility {
2022-06-13 09:16:25 +00:00
return this.#accessibility;
}
override frames(): Frame[] {
2022-06-13 09:16:25 +00:00
return this.#frameManager.frames();
2017-06-21 20:51:06 +00:00
}
override workers(): WebWorker[] {
2022-06-13 09:16:25 +00:00
return Array.from(this.#workers.values());
}
override async setRequestInterception(value: boolean): Promise<void> {
return this.#frameManager.networkManager.setRequestInterception(value);
2017-06-21 20:51:06 +00:00
}
override async setDragInterception(enabled: boolean): Promise<void> {
2022-06-13 09:16:25 +00:00
this.#userDragInterceptionEnabled = enabled;
return this.#client.send('Input.setInterceptDrags', {enabled});
}
override setOfflineMode(enabled: boolean): Promise<void> {
return this.#frameManager.networkManager.setOfflineMode(enabled);
}
override emulateNetworkConditions(
networkConditions: NetworkConditions | null
): Promise<void> {
return this.#frameManager.networkManager.emulateNetworkConditions(
networkConditions
);
}
override setDefaultNavigationTimeout(timeout: number): void {
2022-06-13 09:16:25 +00:00
this.#timeoutSettings.setDefaultNavigationTimeout(timeout);
}
override setDefaultTimeout(timeout: number): void {
2022-06-13 09:16:25 +00:00
this.#timeoutSettings.setDefaultTimeout(timeout);
}
override getDefaultTimeout(): number {
return this.#timeoutSettings.timeout();
}
override async $<Selector extends 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
selector: Selector
): Promise<ElementHandle<NodeFor<Selector>> | null> {
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
return this.mainFrame().$(selector);
}
override async $$<Selector extends 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
selector: Selector
): Promise<Array<ElementHandle<NodeFor<Selector>>>> {
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
return this.mainFrame().$$(selector);
}
override async evaluateHandle<
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[],
Func extends EvaluateFunc<Params> = EvaluateFunc<Params>
>(
pageFunction: Func | string,
2022-06-24 06:40:08 +00:00
...args: Params
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
): Promise<HandleFor<Awaited<ReturnType<Func>>>> {
const context = await this.mainFrame().executionContext();
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
return context.evaluateHandle(pageFunction, ...args);
}
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[]>> {
const context = await this.mainFrame().executionContext();
assert(!prototypeHandle.disposed, 'Prototype JSHandle is disposed!');
const remoteObject = prototypeHandle.remoteObject();
assert(
remoteObject.objectId,
'Prototype JSHandle must not be referencing primitive value'
);
const response = await context._client.send('Runtime.queryObjects', {
prototypeObjectId: remoteObject.objectId,
});
return createJSHandle(context, response.objects) as HandleFor<Prototype[]>;
}
override async $eval<
Selector extends 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
Params extends unknown[],
Func extends EvaluateFunc<
[ElementHandle<NodeFor<Selector>>, ...Params]
> = EvaluateFunc<[ElementHandle<NodeFor<Selector>>, ...Params]>
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
>(
selector: Selector,
pageFunction: Func | string,
2022-06-24 06:40:08 +00:00
...args: Params
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
): Promise<Awaited<ReturnType<Func>>> {
return this.mainFrame().$eval(selector, pageFunction, ...args);
}
override async $$eval<
Selector extends 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
Params extends unknown[],
Func extends EvaluateFunc<
[Array<NodeFor<Selector>>, ...Params]
> = EvaluateFunc<[Array<NodeFor<Selector>>, ...Params]>
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
>(
selector: Selector,
pageFunction: Func | string,
2022-06-24 06:40:08 +00:00
...args: Params
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
): Promise<Awaited<ReturnType<Func>>> {
return this.mainFrame().$$eval(selector, pageFunction, ...args);
}
override async $x(expression: string): Promise<Array<ElementHandle<Node>>> {
return this.mainFrame().$x(expression);
}
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;
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];
}
return cookie;
};
return originalCookies.map(filterUnsupportedAttributes);
}
override async deleteCookie(
...cookies: Protocol.Network.DeleteCookiesRequest[]
2020-05-07 10:54:55 +00:00
): Promise<void> {
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);
}
}
override async setCookie(
...cookies: Protocol.Network.CookieParam[]
): Promise<void> {
const pageURL = this.url();
const startsWithHTTP = pageURL.startsWith('http');
const items = cookies.map(cookie => {
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}"`
);
return item;
});
await this.deleteCookie(...items);
2022-06-14 11:55:35 +00:00
if (items.length) {
await this.#client.send('Network.setCookies', {cookies: items});
2022-06-14 11:55:35 +00:00
}
}
override async addScriptTag(
2022-09-01 15:09:57 +00:00
options: FrameAddScriptTagOptions
): Promise<ElementHandle<HTMLScriptElement>> {
return this.mainFrame().addScriptTag(options);
2017-06-21 20:51:06 +00:00
}
override async addStyleTag(
options: Omit<FrameAddStyleTagOptions, 'url'>
): Promise<ElementHandle<HTMLStyleElement>>;
override async addStyleTag(
options: FrameAddStyleTagOptions
): Promise<ElementHandle<HTMLLinkElement>>;
override async addStyleTag(
options: FrameAddStyleTagOptions
): Promise<ElementHandle<HTMLStyleElement | HTMLLinkElement>> {
return this.mainFrame().addStyleTag(options);
2017-06-21 20:51:06 +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> {
2022-06-14 11:55:35 +00:00
if (this.#pageBindings.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
}
let exposedFunction: Function;
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':
exposedFunction = pptrFunction;
break;
default:
exposedFunction = pptrFunction.default;
break;
}
2022-06-13 09:16:25 +00:00
this.#pageBindings.set(name, exposedFunction);
2017-06-21 20:51:06 +00:00
const expression = pageBindingInitString('exposedFun', name);
await this.#client.send('Runtime.addBinding', {name: name});
2022-06-13 09:16:25 +00:00
await this.#client.send('Page.addScriptToEvaluateOnNewDocument', {
2020-05-07 10:54:55 +00:00
source: expression,
});
await Promise.all(
this.frames().map(frame => {
return frame.evaluate(expression).catch(debugError);
})
2020-05-07 10:54:55 +00:00
);
2017-06-21 20:51:06 +00:00
}
override async authenticate(credentials: Credentials): Promise<void> {
return this.#frameManager.networkManager.authenticate(credentials);
}
override async setExtraHTTPHeaders(
headers: Record<string, string>
): Promise<void> {
return this.#frameManager.networkManager.setExtraHTTPHeaders(headers);
2017-06-21 20:51:06 +00:00
}
override async setUserAgent(
userAgent: string,
userAgentMetadata?: Protocol.Emulation.UserAgentMetadata
): Promise<void> {
return this.#frameManager.networkManager.setUserAgent(
userAgent,
userAgentMetadata
);
2017-06-21 20:51:06 +00:00
}
2017-05-11 07:06:41 +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);
}
2022-06-13 09:16:25 +00:00
#emitMetrics(event: Protocol.Performance.MetricsEvent): void {
this.emit(PageEmittedEvents.Metrics, {
title: event.title,
2022-06-13 09:16:25 +00:00
metrics: this.#buildMetricsObject(event.metrics),
});
}
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']
> = {};
for (const metric of metrics || []) {
2022-05-31 14:34:16 +00:00
if (supportedMetrics.has(metric.name)) {
result[metric.name] = metric.value;
}
}
return result;
}
2022-06-13 09:16:25 +00:00
#handleException(exceptionDetails: Protocol.Runtime.ExceptionDetails): void {
const message = getExceptionMessage(exceptionDetails);
const err = new Error(message);
err.stack = ''; // Don't report clientside error with a node stack attached
this.emit(PageEmittedEvents.PageError, err);
2017-06-21 20:51:06 +00:00
}
2022-06-13 09:16:25 +00:00
async #onConsoleAPI(
event: Protocol.Runtime.ConsoleAPICalledEvent
2020-05-07 10:54:55 +00:00
): Promise<void> {
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
return;
}
2022-06-13 09:16:25 +00:00
const context = this.#frameManager.executionContextById(
event.executionContextId,
2022-06-13 09:16:25 +00:00
this.#client
2020-05-07 10:54:55 +00:00
);
const values = event.args.map(arg => {
2022-06-27 07:24:23 +00:00
return createJSHandle(context, arg);
});
2022-06-13 09:16:25 +00:00
this.#addConsoleMessage(event.type, values, event.stackTrace);
}
2022-06-13 09:16:25 +00:00
async #onBindingCalled(
event: Protocol.Runtime.BindingCalledEvent
2020-05-07 10:54:55 +00:00
): Promise<void> {
let payload: {type: string; name: string; seq: number; args: unknown[]};
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;
}
const {type, name, seq, args} = payload;
2022-06-14 11:55:35 +00:00
if (type !== 'exposedFun' || !this.#pageBindings.has(name)) {
return;
}
let expression = null;
try {
2022-06-13 09:16:25 +00:00
const pageBinding = this.#pageBindings.get(name);
2022-05-31 14:34:16 +00:00
assert(pageBinding);
const result = await pageBinding(...args);
expression = pageBindingDeliverResultString(name, seq, result);
} catch (error) {
2022-06-14 11:55:35 +00:00
if (isErrorLike(error)) {
expression = pageBindingDeliverErrorString(
2020-05-07 10:54:55 +00:00
name,
seq,
error.message,
error.stack
);
2022-06-14 11:55:35 +00:00
} else {
expression = pageBindingDeliverErrorValueString(name, seq, error);
}
}
2022-06-13 09:16:25 +00:00
this.#client
2020-05-07 10:54:55 +00:00
.send('Runtime.evaluate', {
expression,
contextId: event.executionContextId,
})
.catch(debugError);
}
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 {
if (!this.listenerCount(PageEmittedEvents.Console)) {
args.forEach(arg => {
return arg.dispose();
});
return;
}
const textTokens = [];
for (const arg of args) {
const remoteObject = arg.remoteObject();
2022-06-14 11:55:35 +00:00
if (remoteObject.objectId) {
textTokens.push(arg.toString());
} else {
textTokens.push(valueFromRemoteObject(remoteObject));
}
}
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,
stackTraceLocations
2020-05-07 10:54:55 +00:00
);
this.emit(PageEmittedEvents.Console, message);
2017-06-21 20:51:06 +00:00
}
2022-06-13 09:16:25 +00:00
#onDialog(event: Protocol.Page.JavascriptDialogOpeningEvent): void {
let dialogType = null;
const validDialogTypes = new Set<Protocol.Page.DialogType>([
'alert',
'confirm',
'prompt',
'beforeunload',
]);
if (validDialogTypes.has(event.type)) {
dialogType = event.type as Protocol.Page.DialogType;
}
assert(dialogType, 'Unknown javascript dialog type: ' + event.type);
2020-05-07 10:54:55 +00:00
const dialog = new Dialog(
2022-06-13 09:16:25 +00:00
this.#client,
2020-05-07 10:54:55 +00:00
dialogType,
event.message,
event.defaultPrompt
);
this.emit(PageEmittedEvents.Dialog, dialog);
2017-06-21 20:51:06 +00:00
}
/**
* Resets default white background
*/
2022-06-13 09:16:25 +00:00
async #resetDefaultBackgroundColor() {
await this.#client.send('Emulation.setDefaultBackgroundColorOverride');
}
/**
* Hides default white background
*/
2022-06-13 09:16:25 +00:00
async #setTransparentBackgroundColor(): Promise<void> {
await this.#client.send('Emulation.setDefaultBackgroundColorOverride', {
color: {r: 0, g: 0, b: 0, a: 0},
});
}
override url(): string {
return this.mainFrame().url();
2017-06-21 20:51:06 +00:00
}
override async content(): Promise<string> {
2022-06-13 09:16:25 +00:00
return await this.#frameManager.mainFrame().content();
}
override async setContent(
html: string,
options: WaitForOptions = {}
): Promise<void> {
2022-06-13 09:16:25 +00:00
await this.#frameManager.mainFrame().setContent(html, options);
2017-06-21 20:51:06 +00:00
}
override async goto(
2020-05-07 10:54:55 +00:00
url: string,
options: WaitForOptions & {referer?: string} = {}
2022-05-31 14:34:16 +00:00
): Promise<HTTPResponse | null> {
2022-06-13 09:16:25 +00:00
return await this.#frameManager.mainFrame().goto(url, options);
}
override async reload(
options?: WaitForOptions
): Promise<HTTPResponse | null> {
const result = await Promise.all([
this.waitForNavigation(options),
2022-06-13 09:16:25 +00:00
this.#client.send('Page.reload'),
]);
return result[0];
}
override async waitForNavigation(
2020-05-07 10:54:55 +00:00
options: WaitForOptions = {}
): Promise<HTTPResponse | null> {
2022-06-13 09:16:25 +00:00
return await this.#frameManager.mainFrame().waitForNavigation(options);
2017-06-21 20:51:06 +00:00
}
2022-06-13 09:16:25 +00:00
#sessionClosePromise(): Promise<Error> {
2022-06-14 11:55:35 +00:00
if (!this.#disconnectPromise) {
this.#disconnectPromise = new Promise(fulfill => {
return this.#client.once(CDPSessionEmittedEvents.Disconnected, () => {
return fulfill(new Error('Target closed'));
});
});
2022-06-14 11:55:35 +00:00
}
2022-06-13 09:16:25 +00:00
return this.#disconnectPromise;
}
override async waitForRequest(
urlOrPredicate: string | ((req: HTTPRequest) => boolean | Promise<boolean>),
options: {timeout?: number} = {}
): Promise<HTTPRequest> {
const {timeout = this.#timeoutSettings.timeout()} = options;
return waitForEvent(
this.#frameManager.networkManager,
NetworkManagerEmittedEvents.Request,
async request => {
2022-06-14 11:55:35 +00:00
if (isString(urlOrPredicate)) {
return urlOrPredicate === request.url();
}
if (typeof urlOrPredicate === 'function') {
return !!(await urlOrPredicate(request));
2022-06-14 11:55:35 +00:00
}
2020-05-07 10:54:55 +00:00
return false;
},
timeout,
2022-06-13 09:16:25 +00:00
this.#sessionClosePromise()
2020-05-07 10:54:55 +00:00
);
}
override async waitForResponse(
urlOrPredicate:
| string
| ((res: HTTPResponse) => boolean | Promise<boolean>),
options: {timeout?: number} = {}
): Promise<HTTPResponse> {
const {timeout = this.#timeoutSettings.timeout()} = options;
return waitForEvent(
this.#frameManager.networkManager,
NetworkManagerEmittedEvents.Response,
async response => {
2022-06-14 11:55:35 +00:00
if (isString(urlOrPredicate)) {
return urlOrPredicate === response.url();
}
if (typeof urlOrPredicate === 'function') {
return !!(await urlOrPredicate(response));
2022-06-14 11:55:35 +00:00
}
2020-05-07 10:54:55 +00:00
return false;
},
timeout,
2022-06-13 09:16:25 +00:00
this.#sessionClosePromise()
2020-05-07 10:54:55 +00:00
);
}
override async waitForNetworkIdle(
options: {idleTime?: number; timeout?: number} = {}
): Promise<void> {
const {idleTime = 500, timeout = this.#timeoutSettings.timeout()} = options;
const networkManager = this.#frameManager.networkManager;
2022-05-31 14:34:16 +00:00
let idleResolveCallback: () => void;
const idlePromise = new Promise<void>(resolve => {
idleResolveCallback = resolve;
});
2022-05-31 14:34:16 +00:00
let abortRejectCallback: (error: Error) => void;
const abortPromise = new Promise<Error>((_, reject) => {
abortRejectCallback = reject;
});
2022-05-31 14:34:16 +00:00
let idleTimer: NodeJS.Timeout;
const onIdle = () => {
return idleResolveCallback();
};
const cleanup = () => {
idleTimer && clearTimeout(idleTimer);
abortRejectCallback(new Error('abort'));
};
const evaluate = () => {
idleTimer && clearTimeout(idleTimer);
2022-06-14 11:55:35 +00:00
if (networkManager.numRequestsInProgress() === 0) {
idleTimer = setTimeout(onIdle, idleTime);
2022-06-14 11:55:35 +00:00
}
};
evaluate();
const eventHandler = () => {
evaluate();
return false;
};
const listenToEvent = (event: symbol) => {
return waitForEvent(
networkManager,
event,
eventHandler,
timeout,
abortPromise
);
};
const eventPromises = [
listenToEvent(NetworkManagerEmittedEvents.Request),
listenToEvent(NetworkManagerEmittedEvents.Response),
];
await Promise.race([
idlePromise,
...eventPromises,
2022-06-13 09:16:25 +00:00
this.#sessionClosePromise(),
]).then(
r => {
cleanup();
return r;
},
error => {
cleanup();
throw error;
}
);
}
override async waitForFrame(
urlOrPredicate: string | ((frame: Frame) => boolean | Promise<boolean>),
options: {timeout?: number} = {}
): Promise<Frame> {
const {timeout = this.#timeoutSettings.timeout()} = options;
2022-05-31 14:34:16 +00:00
let predicate: (frame: Frame) => Promise<boolean>;
if (isString(urlOrPredicate)) {
predicate = (frame: Frame) => {
return Promise.resolve(urlOrPredicate === frame.url());
};
2022-05-31 14:34:16 +00:00
} else {
predicate = (frame: Frame) => {
const value = urlOrPredicate(frame);
if (typeof value === 'boolean') {
return Promise.resolve(value);
}
return value;
};
}
2022-05-31 14:34:16 +00:00
const eventRace: Promise<Frame> = Promise.race([
waitForEvent(
2022-06-13 09:16:25 +00:00
this.#frameManager,
FrameManagerEmittedEvents.FrameAttached,
predicate,
timeout,
2022-06-13 09:16:25 +00:00
this.#sessionClosePromise()
),
waitForEvent(
2022-06-13 09:16:25 +00:00
this.#frameManager,
FrameManagerEmittedEvents.FrameNavigated,
predicate,
timeout,
2022-06-13 09:16:25 +00:00
this.#sessionClosePromise()
),
...this.frames().map(async frame => {
2022-05-31 14:34:16 +00:00
if (await predicate(frame)) {
return frame;
}
2022-05-31 14:34:16 +00:00
return await eventRace;
}),
]);
2022-05-31 14:34:16 +00:00
return eventRace;
}
override async goBack(
options: WaitForOptions = {}
): Promise<HTTPResponse | null> {
2022-06-13 09:16:25 +00:00
return this.#go(-1, options);
}
override async goForward(
options: WaitForOptions = {}
): Promise<HTTPResponse | null> {
2022-06-13 09:16:25 +00:00
return this.#go(+1, options);
}
2022-06-13 09:16:25 +00:00
async #go(
2020-05-07 10:54:55 +00:00
delta: number,
options: WaitForOptions
): Promise<HTTPResponse | null> {
2022-06-13 09:16:25 +00:00
const history = await this.#client.send('Page.getNavigationHistory');
const entry = history.entries[history.currentIndex + delta];
2022-06-14 11:55:35 +00:00
if (!entry) {
return null;
}
const result = await Promise.all([
this.waitForNavigation(options),
this.#client.send('Page.navigateToHistoryEntry', {entryId: entry.id}),
]);
return result[0];
}
override async bringToFront(): Promise<void> {
2022-06-13 09:16:25 +00:00
await this.#client.send('Page.bringToFront');
}
override async setJavaScriptEnabled(enabled: boolean): Promise<void> {
2022-06-14 11:55:35 +00:00
if (this.#javascriptEnabled === enabled) {
return;
}
2022-06-13 09:16:25 +00:00
this.#javascriptEnabled = enabled;
await this.#client.send('Emulation.setScriptExecutionDisabled', {
2020-05-07 10:54:55 +00:00
value: !enabled,
});
}
override async setBypassCSP(enabled: boolean): Promise<void> {
await this.#client.send('Page.setBypassCSP', {enabled});
}
override async emulateMediaType(type?: string): Promise<void> {
2020-05-07 10:54:55 +00:00
assert(
type === 'screen' ||
type === 'print' ||
(type ?? undefined) === undefined,
2020-05-07 10:54:55 +00:00
'Unsupported media type: ' + type
);
2022-06-13 09:16:25 +00:00
await this.#client.send('Emulation.setEmulatedMedia', {
2020-05-07 10:54:55 +00:00
media: type || '',
});
}
override async emulateCPUThrottling(factor: number | null): Promise<void> {
assert(
factor === null || factor >= 1,
'Throttling rate should be greater or equal to 1'
);
2022-06-13 09:16:25 +00:00
await this.#client.send('Emulation.setCPUThrottlingRate', {
rate: factor !== null ? factor : 1,
});
}
override async emulateMediaFeatures(
features?: MediaFeature[]
): Promise<void> {
2022-06-14 11:55:35 +00:00
if (!features) {
await this.#client.send('Emulation.setEmulatedMedia', {});
}
if (Array.isArray(features)) {
2022-05-31 14:34:16 +00:00
for (const mediaFeature of features) {
const name = mediaFeature.name;
2020-05-07 10:54:55 +00:00
assert(
/^(?:prefers-(?:color-scheme|reduced-motion)|color-gamut)$/.test(
name
),
2020-05-07 10:54:55 +00:00
'Unsupported media feature: ' + name
);
2022-05-31 14:34:16 +00:00
}
2022-06-13 09:16:25 +00:00
await this.#client.send('Emulation.setEmulatedMedia', {
2020-05-07 10:54:55 +00:00
features: features,
});
}
}
override async emulateTimezone(timezoneId?: string): Promise<void> {
try {
2022-06-13 09:16:25 +00:00
await this.#client.send('Emulation.setTimezoneOverride', {
2020-05-07 10:54:55 +00:00
timezoneId: timezoneId || '',
});
} catch (error) {
2022-06-10 13:27:42 +00:00
if (isErrorLike(error) && error.message.includes('Invalid timezone')) {
throw new Error(`Invalid timezone ID: ${timezoneId}`);
2022-06-10 13:27:42 +00:00
}
throw error;
}
}
override async emulateIdleState(overrides?: {
isUserActive: boolean;
isScreenUnlocked: boolean;
}): Promise<void> {
if (overrides) {
2022-06-13 09:16:25 +00:00
await this.#client.send('Emulation.setIdleOverride', {
isUserActive: overrides.isUserActive,
isScreenUnlocked: overrides.isScreenUnlocked,
});
} else {
2022-06-13 09:16:25 +00:00
await this.#client.send('Emulation.clearIdleOverride');
}
}
override async emulateVisionDeficiency(
type?: Protocol.Emulation.SetEmulatedVisionDeficiencyRequest['type']
): Promise<void> {
const visionDeficiencies = new Set<
Protocol.Emulation.SetEmulatedVisionDeficiencyRequest['type']
>([
'none',
'achromatopsia',
'blurredVision',
'deuteranopia',
'protanopia',
'tritanopia',
]);
try {
assert(
!type || visionDeficiencies.has(type),
`Unsupported vision deficiency: ${type}`
);
2022-06-13 09:16:25 +00:00
await this.#client.send('Emulation.setEmulatedVisionDeficiency', {
type: type || 'none',
});
} catch (error) {
throw error;
}
}
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
}
override viewport(): Viewport | null {
2022-06-13 09:16:25 +00:00
return this.#viewport;
2017-06-21 20:51:06 +00:00
}
override async evaluate<
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[],
Func extends EvaluateFunc<Params> = EvaluateFunc<Params>
>(
pageFunction: Func | string,
2022-06-24 06:40:08 +00:00
...args: Params
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
): Promise<Awaited<ReturnType<Func>>> {
return this.#frameManager.mainFrame().evaluate(pageFunction, ...args);
2017-06-21 20:51:06 +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[],
Func extends (...args: Params) => unknown = (...args: Params) => unknown
>(pageFunction: Func | string, ...args: Params): Promise<void> {
const source = evaluationString(pageFunction, ...args);
2022-06-13 09:16:25 +00:00
await this.#client.send('Page.addScriptToEvaluateOnNewDocument', {
2020-05-07 10:54:55 +00:00
source,
});
2017-06-21 20:51:06 +00:00
}
2017-06-20 01:03:01 +00:00
override async setCacheEnabled(enabled = true): Promise<void> {
await this.#frameManager.networkManager.setCacheEnabled(enabled);
}
override async screenshot(
options: ScreenshotOptions = {}
): Promise<Buffer | string> {
2022-05-31 14:34:16 +00:00
let screenshotType = Protocol.Page.CaptureScreenshotRequestFormat.Png;
// options.type takes precedence over inferring the type from options.path
// because it may be a 0-length file with no extension created beforehand
// (i.e. as a temp file).
if (options.type) {
2022-05-31 14:34:16 +00:00
screenshotType =
options.type as Protocol.Page.CaptureScreenshotRequestFormat;
} else if (options.path) {
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-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
}
return this.#screenshotTaskQueue.postTask(() => {
return this.#screenshotTask(screenshotType, options);
});
2017-06-21 20:51:06 +00:00
}
2022-06-13 09:16:25 +00:00
async #screenshotTask(
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
});
let clip = options.clip ? processClip(options.clip) : undefined;
let captureBeyondViewport = options.captureBeyondViewport ?? true;
const fromSurface = options.fromSurface;
if (options.fullPage) {
2022-06-13 09:16:25 +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;
// Overwrite clip for full page.
clip = undefined;
if (!captureBeyondViewport) {
const {
isMobile = false,
deviceScaleFactor = 1,
isLandscape = false,
2022-06-13 09:16:25 +00:00
} = this.#viewport || {};
const screenOrientation: Protocol.Emulation.ScreenOrientation =
isLandscape
? {angle: 90, type: 'landscapePrimary'}
: {angle: 0, type: 'portraitPrimary'};
2022-06-13 09:16:25 +00:00
await this.#client.send('Emulation.setDeviceMetricsOverride', {
mobile: isMobile,
width,
height,
deviceScaleFactor,
screenOrientation,
});
}
} else if (!clip) {
captureBeyondViewport = false;
2017-06-21 20:51:06 +00:00
}
2020-05-07 10:54:55 +00:00
const shouldSetDefaultBackground =
options.omitBackground && (format === 'png' || format === 'webp');
if (shouldSetDefaultBackground) {
2022-06-13 09:16:25 +00:00
await this.#setTransparentBackgroundColor();
}
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,
quality: options.quality,
clip: clip && {
...clip,
scale: clip.scale ?? 1,
},
captureBeyondViewport,
fromSurface,
2020-05-07 10:54:55 +00:00
});
if (shouldSetDefaultBackground) {
2022-06-13 09:16:25 +00:00
await this.#resetDefaultBackgroundColor();
}
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
}
2020-05-07 10:54:55 +00:00
const buffer =
options.encoding === 'base64'
? result.data
: Buffer.from(result.data, 'base64');
if (options.path) {
try {
2022-07-07 19:09:07 +00:00
const fs = (await importFS()).promises;
await fs.writeFile(options.path, buffer);
} catch (error) {
if (error instanceof TypeError) {
throw new Error(
'Screenshots can only be written to a file path in a Node-like environment.'
);
}
throw error;
}
}
2017-06-21 20:51:06 +00:00
return buffer;
function processClip(clip: ScreenshotClip): ScreenshotClip {
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);
return {x, y, width, height, scale: clip.scale};
}
2017-06-21 20:51:06 +00:00
}
override async createPDFStream(options: PDFOptions = {}): Promise<Readable> {
const {
scale = 1,
displayHeaderFooter = false,
headerTemplate = '',
footerTemplate = '',
printBackground = false,
landscape = false,
pageRanges = '',
preferCSSPageSize = false,
margin = {},
omitBackground = false,
timeout = 30000,
} = options;
2017-06-21 20:51:06 +00:00
let paperWidth = 8.5;
let paperHeight = 11;
2017-06-21 20:51:06 +00:00
if (options.format) {
2022-05-31 14:34:16 +00:00
const format =
2022-06-13 09:16:25 +00:00
_paperFormats[options.format.toLowerCase() as LowerCasePaperFormat];
assert(format, 'Unknown paper format: ' + options.format);
2017-06-21 20:51:06 +00:00
paperWidth = format.width;
paperHeight = format.height;
} else {
paperWidth = convertPrintParameterToInches(options.width) || paperWidth;
2020-05-07 10:54:55 +00:00
paperHeight =
convertPrintParameterToInches(options.height) || paperHeight;
2017-06-21 20:51:06 +00:00
}
const marginTop = convertPrintParameterToInches(margin.top) || 0;
const marginLeft = convertPrintParameterToInches(margin.left) || 0;
const marginBottom = convertPrintParameterToInches(margin.bottom) || 0;
const marginRight = convertPrintParameterToInches(margin.right) || 0;
2017-06-21 20:51:06 +00:00
if (omitBackground) {
2022-06-13 09:16:25 +00:00
await this.#setTransparentBackgroundColor();
}
2022-06-13 09:16:25 +00:00
const printCommandPromise = this.#client.send('Page.printToPDF', {
transferMode: 'ReturnAsStream',
landscape,
displayHeaderFooter,
headerTemplate,
footerTemplate,
printBackground,
scale,
paperWidth,
paperHeight,
marginTop,
marginBottom,
marginLeft,
marginRight,
pageRanges,
2020-05-07 10:54:55 +00:00
preferCSSPageSize,
2017-06-21 20:51:06 +00:00
});
const result = await waitWithTimeout(
printCommandPromise,
'Page.printToPDF',
timeout
);
if (omitBackground) {
2022-06-13 09:16:25 +00:00
await this.#resetDefaultBackgroundColor();
}
2022-05-31 14:34:16 +00:00
assert(result.stream, '`stream` is missing from `Page.printToPDF');
return getReadableFromProtocolStream(this.#client, result.stream);
}
override async pdf(options: PDFOptions = {}): Promise<Buffer> {
const {path = undefined} = options;
const readable = await this.createPDFStream(options);
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
}
override async title(): Promise<string> {
return this.mainFrame().title();
2017-06-21 20:51:06 +00:00
}
2017-05-11 07:06:41 +00:00
override async close(
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.'
);
const runBeforeUnload = !!options.runBeforeUnload;
if (runBeforeUnload) {
2022-06-13 09:16:25 +00:00
await this.#client.send('Page.close');
} 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
});
2022-06-13 09:16:25 +00:00
await this.#target._isClosedPromise;
}
2017-06-21 20:51:06 +00:00
}
override isClosed(): boolean {
2022-06-13 09:16:25 +00:00
return this.#closed;
}
override get mouse(): Mouse {
2022-06-13 09:16:25 +00:00
return this.#mouse;
}
override click(
2020-05-07 10:54:55 +00:00
selector: string,
options: {
delay?: number;
button?: MouseButton;
2020-05-07 10:54:55 +00:00
clickCount?: number;
} = {}
): Promise<void> {
return this.mainFrame().click(selector, options);
}
override focus(selector: string): Promise<void> {
return this.mainFrame().focus(selector);
}
override hover(selector: string): Promise<void> {
return this.mainFrame().hover(selector);
}
override select(selector: string, ...values: string[]): Promise<string[]> {
return this.mainFrame().select(selector, ...values);
}
override tap(selector: string): Promise<void> {
return this.mainFrame().tap(selector);
}
override type(
2020-05-07 10:54:55 +00:00
selector: string,
text: string,
options?: {delay: number}
2020-05-07 10:54:55 +00:00
): Promise<void> {
return this.mainFrame().type(selector, text, options);
}
override waitForTimeout(milliseconds: number): Promise<void> {
2020-07-28 08:37:49 +00:00
return this.mainFrame().waitForTimeout(milliseconds);
}
override async waitForSelector<Selector extends 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
selector: Selector,
options: WaitForSelectorOptions = {}
): Promise<ElementHandle<NodeFor<Selector>> | null> {
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
return await this.mainFrame().waitForSelector(selector, options);
}
override waitForXPath(
2020-05-07 10:54:55 +00:00
xpath: string,
options: {
visible?: boolean;
hidden?: boolean;
timeout?: number;
} = {}
): Promise<ElementHandle<Node> | null> {
return this.mainFrame().waitForXPath(xpath, options);
}
override waitForFunction<
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[],
Func extends EvaluateFunc<Params> = EvaluateFunc<Params>
>(
pageFunction: Func | string,
options: FrameWaitForFunctionOptions = {},
2022-06-24 06:40:08 +00:00
...args: Params
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
): Promise<HandleFor<Awaited<ReturnType<Func>>>> {
return this.mainFrame().waitForFunction(pageFunction, options, ...args);
}
2017-05-11 07:06:41 +00:00
}
const supportedMetrics = new Set<string>([
'Timestamp',
'Documents',
'Frames',
'JSEventListeners',
'Nodes',
'LayoutCount',
'RecalcStyleCount',
'LayoutDuration',
'RecalcStyleDuration',
'ScriptDuration',
'TaskDuration',
'JSHeapUsedSize',
'JSHeapTotalSize',
]);
const unitToPixels = {
2020-05-07 10:54:55 +00:00
px: 1,
in: 96,
cm: 37.8,
mm: 3.78,
};
2020-05-07 10:54:55 +00:00
function convertPrintParameterToInches(
parameter?: string | number
): number | undefined {
2022-06-14 11:55:35 +00:00
if (typeof parameter === 'undefined') {
return undefined;
}
let pixels;
if (isNumber(parameter)) {
2017-06-21 20:51:06 +00:00
// Treat numbers as pixel values to be aligned with phantom's paperSize.
pixels = parameter;
} else if (isString(parameter)) {
const text = parameter;
let unit = text.substring(text.length - 2).toLowerCase();
let valueText = '';
2022-05-31 14:34:16 +00:00
if (unit in unitToPixels) {
2017-06-21 20:51:06 +00:00
valueText = text.substring(0, text.length - 2);
} else {
2017-06-21 20:51:06 +00:00
// In case of unknown unit try to parse the whole parameter as number of pixels.
// This is consistent with phantom's paperSize behavior.
unit = 'px';
valueText = text;
}
const value = Number(valueText);
assert(!isNaN(value), 'Failed to parse parameter value: ' + text);
2022-05-31 14:34:16 +00:00
pixels = value * unitToPixels[unit as keyof typeof unitToPixels];
2017-06-21 20:51:06 +00:00
} else {
2020-05-07 10:54:55 +00:00
throw new Error(
'page.pdf() Cannot handle parameter type: ' + typeof parameter
);
2017-06-21 20:51:06 +00:00
}
return pixels / 96;
}