/** * 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'; 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'; 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'; 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'; import {JSHandle} from './JSHandle.js'; 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'; import {TaskQueue} from './TaskQueue.js'; import {TimeoutSettings} from './TimeoutSettings.js'; import {Tracing} from './Tracing.js'; import {EvaluateFunc, HandleFor, NodeFor} from './types.js'; import { createJSHandle, debugError, evaluationString, getExceptionMessage, getReadableAsBuffer, getReadableFromProtocolStream, 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 */ static async _create( client: CDPSession, target: Target, ignoreHTTPSErrors: boolean, defaultViewport: Viewport | null, screenshotTaskQueue: TaskQueue ): Promise { const page = new CDPPage( client, target, ignoreHTTPSErrors, screenshotTaskQueue ); await page.#initialize(); if (defaultViewport) { try { await page.setViewport(defaultViewport); } catch (err) { if (isErrorLike(err) && isTargetClosedError(err)) { debugError(err); } else { throw err; } } } return page; } #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(); #coverage: Coverage; #javascriptEnabled = true; #viewport: Viewport | null; #screenshotTaskQueue: TaskQueue; #workers = new Map(); #fileChooserPromises = new Set>(); #disconnectPromise?: Promise; #userDragInterceptionEnabled = false; /** * @internal */ constructor( client: CDPSession, target: Target, ignoreHTTPSErrors: boolean, screenshotTaskQueue: TaskQueue ) { super(); 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( client, this, ignoreHTTPSErrors, this.#timeoutSettings ); this.#emulationManager = new EmulationManager(client); this.#tracing = new Tracing(client); this.#coverage = new Coverage(client); this.#screenshotTaskQueue = screenshotTaskQueue; this.#viewport = null; 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); }); 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); } ); 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); }); this.#target._isClosedPromise.then(() => { this.#target ._targetManager() .removeTargetInterceptor(this.#client, this.#onAttachedToTarget); this.#target ._targetManager() .off(TargetManagerEmittedEvents.TargetGone, this.#onDetachedFromTarget); this.emit(PageEmittedEvents.Close); 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 ); } }; async #initialize(): Promise { 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; } } } async #onFileChooser( event: Protocol.Page.FileChooserOpenedEvent ): Promise { if (!this.#fileChooserPromises.size) { return; } 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; const fileChooser = new FileChooser(handle, event); for (const promise of this.#fileChooserPromises) { promise.resolve(fileChooser); } this.#fileChooserPromises.clear(); } /** * @returns `true` if drag events are being intercepted, `false` otherwise. */ override isDragInterceptionEnabled(): boolean { return this.#userDragInterceptionEnabled; } /** * @returns `true` if the page has JavaScript enabled, `false` otherwise. */ override isJavaScriptEnabled(): boolean { return this.#javascriptEnabled; } /** * This method is typically coupled with an action that triggers file * choosing. * * :::caution * * This must be called before the file chooser is launched. It will not return * a currently active file chooser. * * ::: * * @remarks * In non-headless Chromium, this method results in the native file picker * dialog `not showing up` for the user. * * @example * The following example clicks a button that issues a file chooser * and then responds with `/tmp/myfile.pdf` as if a user has selected this file. * * ```ts * const [fileChooser] = await Promise.all([ * page.waitForFileChooser(), * page.click('#upload-file-button'), * // some button that triggers file selection * ]); * await fileChooser.accept(['/tmp/myfile.pdf']); * ``` */ override waitForFileChooser( options: WaitTimeoutOptions = {} ): Promise { const needsEnable = this.#fileChooserPromises.size === 0; const {timeout = this.#timeoutSettings.timeout()} = options; const promise = createDeferredPromise({ message: `Waiting for \`FileChooser\` failed: ${timeout}ms exceeded`, timeout, }); this.#fileChooserPromises.add(promise); let enablePromise: Promise | 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; }); } /** * Sets the page's geolocation. * * @remarks * Consider using {@link BrowserContext.overridePermissions} to grant * permissions for the page to read its geolocation. * * @example * * ```ts * await page.setGeolocation({latitude: 59.95, longitude: 30.31667}); * ``` */ override async setGeolocation(options: GeolocationOptions): Promise { const {longitude, latitude, accuracy = 0} = options; if (longitude < -180 || longitude > 180) { throw new Error( `Invalid longitude "${longitude}": precondition -180 <= LONGITUDE <= 180 failed.` ); } if (latitude < -90 || latitude > 90) { throw new Error( `Invalid latitude "${latitude}": precondition -90 <= LATITUDE <= 90 failed.` ); } if (accuracy < 0) { throw new Error( `Invalid accuracy "${accuracy}": precondition 0 <= ACCURACY failed.` ); } await this.#client.send('Emulation.setGeolocationOverride', { longitude, latitude, accuracy, }); } /** * @returns A target this page was created from. */ override target(): Target { return this.#target; } /** * @internal */ _client(): CDPSession { return this.#client; } /** * Get the browser the page belongs to. */ override browser(): Browser { return this.#target.browser(); } /** * Get the browser context that the page belongs to. */ override browserContext(): BrowserContext { return this.#target.browserContext(); } #onTargetCrashed(): void { this.emit('error', new Error('Page crashed!')); } #onLogEntryAdded(event: Protocol.Log.EntryAddedEvent): void { const {level, text, args, source, url, lineNumber} = event.entry; if (args) { args.map(arg => { return releaseObject(this.#client, arg); }); } if (source !== 'worker') { this.emit( PageEmittedEvents.Console, new ConsoleMessage(level, text, [], [{url, lineNumber}]) ); } } /** * @returns The page's main frame. * * @remarks * Page is guaranteed to have a main frame which persists during navigations. */ override mainFrame(): Frame { return this.#frameManager.mainFrame(); } override get keyboard(): Keyboard { return this.#keyboard; } override get touchscreen(): Touchscreen { return this.#touchscreen; } override get coverage(): Coverage { return this.#coverage; } override get tracing(): Tracing { return this.#tracing; } override get accessibility(): Accessibility { return this.#accessibility; } /** * @returns An array of all frames attached to the page. */ override frames(): Frame[] { return this.#frameManager.frames(); } /** * @returns all of the dedicated {@link * https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API | * WebWorkers} associated with the page. * * @remarks * This does not contain ServiceWorkers */ override workers(): WebWorker[] { return Array.from(this.#workers.values()); } /** * Activating request interception enables {@link HTTPRequest.abort}, * {@link HTTPRequest.continue} and {@link HTTPRequest.respond} methods. This * provides the capability to modify network requests that are made by a page. * * Once request interception is enabled, every request will stall unless it's * continued, responded or aborted; or completed using the browser cache. * * Enabling request interception disables page caching. * * See the * {@link https://pptr.dev/next/guides/request-interception|Request interception guide} * for more details. * * @example * An example of a naïve request interceptor that aborts all image requests: * * ```ts * const puppeteer = require('puppeteer'); * (async () => { * const browser = await puppeteer.launch(); * const page = await browser.newPage(); * await page.setRequestInterception(true); * page.on('request', interceptedRequest => { * if ( * interceptedRequest.url().endsWith('.png') || * interceptedRequest.url().endsWith('.jpg') * ) * interceptedRequest.abort(); * else interceptedRequest.continue(); * }); * await page.goto('https://example.com'); * await browser.close(); * })(); * ``` * * @param value - Whether to enable request interception. */ override async setRequestInterception(value: boolean): Promise { return this.#frameManager.networkManager.setRequestInterception(value); } /** * @param enabled - Whether to enable drag interception. * * @remarks * Activating drag interception enables the `Input.drag`, * methods This provides the capability to capture drag events emitted * on the page, which can then be used to simulate drag-and-drop. */ override async setDragInterception(enabled: boolean): Promise { this.#userDragInterceptionEnabled = enabled; return this.#client.send('Input.setInterceptDrags', {enabled}); } override setOfflineMode(enabled: boolean): Promise { return this.#frameManager.networkManager.setOfflineMode(enabled); } override emulateNetworkConditions( networkConditions: NetworkConditions | null ): Promise { return this.#frameManager.networkManager.emulateNetworkConditions( networkConditions ); } /** * This setting will change the default maximum navigation time for the * following methods and related shortcuts: * * - {@link Page.goBack | page.goBack(options)} * * - {@link Page.goForward | page.goForward(options)} * * - {@link Page.goto | page.goto(url,options)} * * - {@link Page.reload | page.reload(options)} * * - {@link Page.setContent | page.setContent(html,options)} * * - {@link Page.waitForNavigation | page.waitForNavigation(options)} * @param timeout - Maximum navigation time in milliseconds. */ override setDefaultNavigationTimeout(timeout: number): void { this.#timeoutSettings.setDefaultNavigationTimeout(timeout); } /** * @param timeout - Maximum time in milliseconds. */ override setDefaultTimeout(timeout: number): void { this.#timeoutSettings.setDefaultTimeout(timeout); } /** * @returns Maximum time in milliseconds. */ override getDefaultTimeout(): number { return this.#timeoutSettings.timeout(); } /** * Runs `document.querySelector` within the page. If no element matches the * selector, the return value resolves to `null`. * * @param selector - A `selector` to query page for * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector} * to query page for. */ override async $( selector: Selector ): Promise> | null> { return this.mainFrame().$(selector); } /** * The method runs `document.querySelectorAll` within the page. If no elements * match the selector, the return value resolves to `[]`. * @remarks * Shortcut for {@link Frame.$$ | Page.mainFrame().$$(selector) }. * @param selector - A `selector` to query page for */ override async $$( selector: Selector ): Promise>>> { return this.mainFrame().$$(selector); } /** * @remarks * * The only difference between {@link Page.evaluate | page.evaluate} and * `page.evaluateHandle` is that `evaluateHandle` will return the value * wrapped in an in-page object. * * If the function passed to `page.evaluteHandle` returns a Promise, the * function will wait for the promise to resolve and return its value. * * You can pass a string instead of a function (although functions are * recommended as they are easier to debug and use with TypeScript): * * @example * * ```ts * const aHandle = await page.evaluateHandle('document'); * ``` * * @example * {@link JSHandle} instances can be passed as arguments to the `pageFunction`: * * ```ts * const aHandle = await page.evaluateHandle(() => document.body); * const resultHandle = await page.evaluateHandle( * body => body.innerHTML, * aHandle * ); * console.log(await resultHandle.jsonValue()); * await resultHandle.dispose(); * ``` * * Most of the time this function returns a {@link JSHandle}, * but if `pageFunction` returns a reference to an element, * you instead get an {@link ElementHandle} back: * * @example * * ```ts * const button = await page.evaluateHandle(() => * document.querySelector('button') * ); * // can call `click` because `button` is an `ElementHandle` * await button.click(); * ``` * * The TypeScript definitions assume that `evaluateHandle` returns * a `JSHandle`, but if you know it's going to return an * `ElementHandle`, pass it as the generic argument: * * ```ts * const button = await page.evaluateHandle(...); * ``` * * @param pageFunction - a function that is run within the page * @param args - arguments to be passed to the pageFunction */ override async evaluateHandle< Params extends unknown[], Func extends EvaluateFunc = EvaluateFunc >( pageFunction: Func | string, ...args: Params ): Promise>>> { const context = await this.mainFrame().executionContext(); return context.evaluateHandle(pageFunction, ...args); } /** * This method iterates the JavaScript heap and finds all objects with the * given prototype. * * @example * * ```ts * // Create a Map object * await page.evaluate(() => (window.map = new Map())); * // Get a handle to the Map object prototype * const mapPrototype = await page.evaluateHandle(() => Map.prototype); * // Query all map instances into an array * const mapInstances = await page.queryObjects(mapPrototype); * // Count amount of map objects in heap * const count = await page.evaluate(maps => maps.length, mapInstances); * await mapInstances.dispose(); * await mapPrototype.dispose(); * ``` * * @param prototypeHandle - a handle to the object prototype. * @returns Promise which resolves to a handle to an array of objects with * this prototype. */ override async queryObjects( prototypeHandle: JSHandle ): Promise> { 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; } /** * This method runs `document.querySelector` within the page and passes the * result as the first argument to the `pageFunction`. * * @remarks * * If no element is found matching `selector`, the method will throw an error. * * If `pageFunction` returns a promise `$eval` will wait for the promise to * resolve and then return its value. * * @example * * ```ts * const searchValue = await page.$eval('#search', el => el.value); * const preloadHref = await page.$eval('link[rel=preload]', el => el.href); * const html = await page.$eval('.main-container', el => el.outerHTML); * ``` * * If you are using TypeScript, you may have to provide an explicit type to the * first argument of the `pageFunction`. * By default it is typed as `Element`, but you may need to provide a more * specific sub-type: * * @example * * ```ts * // if you don't provide HTMLInputElement here, TS will error * // as `value` is not on `Element` * const searchValue = await page.$eval( * '#search', * (el: HTMLInputElement) => el.value * ); * ``` * * The compiler should be able to infer the return type * from the `pageFunction` you provide. If it is unable to, you can use the generic * type to tell the compiler what return type you expect from `$eval`: * * @example * * ```ts * // The compiler can infer the return type in this case, but if it can't * // or if you want to be more explicit, provide it as the generic type. * const searchValue = await page.$eval( * '#search', * (el: HTMLInputElement) => el.value * ); * ``` * * @param selector - the * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector} * to query for * @param pageFunction - the function to be evaluated in the page context. * Will be passed the result of `document.querySelector(selector)` as its * first argument. * @param args - any additional arguments to pass through to `pageFunction`. * * @returns The result of calling `pageFunction`. If it returns an element it * is wrapped in an {@link ElementHandle}, else the raw value itself is * returned. */ override async $eval< Selector extends string, Params extends unknown[], Func extends EvaluateFunc< [ElementHandle>, ...Params] > = EvaluateFunc<[ElementHandle>, ...Params]> >( selector: Selector, pageFunction: Func | string, ...args: Params ): Promise>> { return this.mainFrame().$eval(selector, pageFunction, ...args); } /** * This method runs `Array.from(document.querySelectorAll(selector))` within * the page and passes the result as the first argument to the `pageFunction`. * * @remarks * If `pageFunction` returns a promise `$$eval` will wait for the promise to * resolve and then return its value. * * @example * * ```ts * // get the amount of divs on the page * const divCount = await page.$$eval('div', divs => divs.length); * * // get the text content of all the `.options` elements: * const options = await page.$$eval('div > span.options', options => { * return options.map(option => option.textContent); * }); * ``` * * If you are using TypeScript, you may have to provide an explicit type to the * first argument of the `pageFunction`. * By default it is typed as `Element[]`, but you may need to provide a more * specific sub-type: * * @example * * ```ts * // if you don't provide HTMLInputElement here, TS will error * // as `value` is not on `Element` * await page.$$eval('input', (elements: HTMLInputElement[]) => { * return elements.map(e => e.value); * }); * ``` * * The compiler should be able to infer the return type * from the `pageFunction` you provide. If it is unable to, you can use the generic * type to tell the compiler what return type you expect from `$$eval`: * * @example * * ```ts * // The compiler can infer the return type in this case, but if it can't * // or if you want to be more explicit, provide it as the generic type. * const allInputValues = await page.$$eval( * 'input', * (elements: HTMLInputElement[]) => elements.map(e => e.textContent) * ); * ``` * * @param selector - the * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector} * to query for * @param pageFunction - the function to be evaluated in the page context. * Will be passed the result of * `Array.from(document.querySelectorAll(selector))` as its first argument. * @param args - any additional arguments to pass through to `pageFunction`. * * @returns The result of calling `pageFunction`. If it returns an element it * is wrapped in an {@link ElementHandle}, else the raw value itself is * returned. */ override async $$eval< Selector extends string, Params extends unknown[], Func extends EvaluateFunc< [Array>, ...Params] > = EvaluateFunc<[Array>, ...Params]> >( selector: Selector, pageFunction: Func | string, ...args: Params ): Promise>> { return this.mainFrame().$$eval(selector, pageFunction, ...args); } /** * The method evaluates the XPath expression relative to the page document as * its context node. If there are no such elements, the method resolves to an * empty array. * * @remarks * Shortcut for {@link Frame.$x | Page.mainFrame().$x(expression) }. * * @param expression - Expression to evaluate */ override async $x(expression: string): Promise>> { return this.mainFrame().$x(expression); } /** * If no URLs are specified, this method returns cookies for the current page * URL. If URLs are specified, only cookies for those URLs are returned. */ override async cookies( ...urls: string[] ): Promise { const originalCookies = ( await this.#client.send('Network.getCookies', { urls: urls.length ? urls : [this.url()], }) ).cookies; const unsupportedCookieAttributes = ['priority']; const filterUnsupportedAttributes = ( cookie: Protocol.Network.Cookie ): Protocol.Network.Cookie => { for (const attr of unsupportedCookieAttributes) { delete (cookie as unknown as Record)[attr]; } return cookie; }; return originalCookies.map(filterUnsupportedAttributes); } override async deleteCookie( ...cookies: Protocol.Network.DeleteCookiesRequest[] ): Promise { const pageURL = this.url(); for (const cookie of cookies) { const item = Object.assign({}, cookie); if (!cookie.url && pageURL.startsWith('http')) { item.url = pageURL; } await this.#client.send('Network.deleteCookies', item); } } /** * @example * * ```ts * await page.setCookie(cookieObject1, cookieObject2); * ``` */ override async setCookie( ...cookies: Protocol.Network.CookieParam[] ): Promise { const pageURL = this.url(); const startsWithHTTP = pageURL.startsWith('http'); const items = cookies.map(cookie => { const item = Object.assign({}, cookie); if (!item.url && startsWithHTTP) { item.url = pageURL; } 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); if (items.length) { await this.#client.send('Network.setCookies', {cookies: items}); } } /** * Adds a `