"use strict"; /** * 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. */ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; }; var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var _CDPPage_instances, _CDPPage_closed, _CDPPage_client, _CDPPage_target, _CDPPage_keyboard, _CDPPage_mouse, _CDPPage_timeoutSettings, _CDPPage_touchscreen, _CDPPage_accessibility, _CDPPage_frameManager, _CDPPage_emulationManager, _CDPPage_tracing, _CDPPage_pageBindings, _CDPPage_coverage, _CDPPage_javascriptEnabled, _CDPPage_viewport, _CDPPage_screenshotTaskQueue, _CDPPage_workers, _CDPPage_fileChooserPromises, _CDPPage_disconnectPromise, _CDPPage_userDragInterceptionEnabled, _CDPPage_onDetachedFromTarget, _CDPPage_onAttachedToTarget, _CDPPage_initialize, _CDPPage_onFileChooser, _CDPPage_onTargetCrashed, _CDPPage_onLogEntryAdded, _CDPPage_emitMetrics, _CDPPage_buildMetricsObject, _CDPPage_handleException, _CDPPage_onConsoleAPI, _CDPPage_onBindingCalled, _CDPPage_addConsoleMessage, _CDPPage_onDialog, _CDPPage_resetDefaultBackgroundColor, _CDPPage_setTransparentBackgroundColor, _CDPPage_sessionClosePromise, _CDPPage_go, _CDPPage_screenshotTask; Object.defineProperty(exports, "__esModule", { value: true }); exports.CDPPage = void 0; const assert_js_1 = require("../util/assert.js"); const DeferredPromise_js_1 = require("../util/DeferredPromise.js"); const ErrorLike_js_1 = require("../util/ErrorLike.js"); const Accessibility_js_1 = require("./Accessibility.js"); const Connection_js_1 = require("./Connection.js"); const ConsoleMessage_js_1 = require("./ConsoleMessage.js"); const Coverage_js_1 = require("./Coverage.js"); const Dialog_js_1 = require("./Dialog.js"); const EmulationManager_js_1 = require("./EmulationManager.js"); const FileChooser_js_1 = require("./FileChooser.js"); const FrameManager_js_1 = require("./FrameManager.js"); const Input_js_1 = require("./Input.js"); const IsolatedWorld_js_1 = require("./IsolatedWorld.js"); const NetworkManager_js_1 = require("./NetworkManager.js"); const PDFOptions_js_1 = require("./PDFOptions.js"); const TimeoutSettings_js_1 = require("./TimeoutSettings.js"); const Tracing_js_1 = require("./Tracing.js"); const util_js_1 = require("./util.js"); const WebWorker_js_1 = require("./WebWorker.js"); const Page_js_1 = require("../api/Page.js"); /** * @internal */ class CDPPage extends Page_js_1.Page { /** * @internal */ constructor(client, target, ignoreHTTPSErrors, screenshotTaskQueue) { super(); _CDPPage_instances.add(this); _CDPPage_closed.set(this, false); _CDPPage_client.set(this, void 0); _CDPPage_target.set(this, void 0); _CDPPage_keyboard.set(this, void 0); _CDPPage_mouse.set(this, void 0); _CDPPage_timeoutSettings.set(this, new TimeoutSettings_js_1.TimeoutSettings()); _CDPPage_touchscreen.set(this, void 0); _CDPPage_accessibility.set(this, void 0); _CDPPage_frameManager.set(this, void 0); _CDPPage_emulationManager.set(this, void 0); _CDPPage_tracing.set(this, void 0); _CDPPage_pageBindings.set(this, new Map()); _CDPPage_coverage.set(this, void 0); _CDPPage_javascriptEnabled.set(this, true); _CDPPage_viewport.set(this, void 0); _CDPPage_screenshotTaskQueue.set(this, void 0); _CDPPage_workers.set(this, new Map()); _CDPPage_fileChooserPromises.set(this, new Set()); _CDPPage_disconnectPromise.set(this, void 0); _CDPPage_userDragInterceptionEnabled.set(this, false); _CDPPage_onDetachedFromTarget.set(this, (target) => { var _a; const sessionId = (_a = target._session()) === null || _a === void 0 ? void 0 : _a.id(); __classPrivateFieldGet(this, _CDPPage_frameManager, "f").onDetachedFromTarget(target); const worker = __classPrivateFieldGet(this, _CDPPage_workers, "f").get(sessionId); if (!worker) { return; } __classPrivateFieldGet(this, _CDPPage_workers, "f").delete(sessionId); this.emit("workerdestroyed" /* PageEmittedEvents.WorkerDestroyed */, worker); }); _CDPPage_onAttachedToTarget.set(this, async (createdTarget) => { __classPrivateFieldGet(this, _CDPPage_frameManager, "f").onAttachedToTarget(createdTarget); if (createdTarget._getTargetInfo().type === 'worker') { const session = createdTarget._session(); (0, assert_js_1.assert)(session); const worker = new WebWorker_js_1.WebWorker(session, createdTarget.url(), __classPrivateFieldGet(this, _CDPPage_instances, "m", _CDPPage_addConsoleMessage).bind(this), __classPrivateFieldGet(this, _CDPPage_instances, "m", _CDPPage_handleException).bind(this)); __classPrivateFieldGet(this, _CDPPage_workers, "f").set(session.id(), worker); this.emit("workercreated" /* PageEmittedEvents.WorkerCreated */, worker); } if (createdTarget._session()) { __classPrivateFieldGet(this, _CDPPage_target, "f") ._targetManager() .addTargetInterceptor(createdTarget._session(), __classPrivateFieldGet(this, _CDPPage_onAttachedToTarget, "f")); } }); __classPrivateFieldSet(this, _CDPPage_client, client, "f"); __classPrivateFieldSet(this, _CDPPage_target, target, "f"); __classPrivateFieldSet(this, _CDPPage_keyboard, new Input_js_1.Keyboard(client), "f"); __classPrivateFieldSet(this, _CDPPage_mouse, new Input_js_1.Mouse(client, __classPrivateFieldGet(this, _CDPPage_keyboard, "f")), "f"); __classPrivateFieldSet(this, _CDPPage_touchscreen, new Input_js_1.Touchscreen(client, __classPrivateFieldGet(this, _CDPPage_keyboard, "f")), "f"); __classPrivateFieldSet(this, _CDPPage_accessibility, new Accessibility_js_1.Accessibility(client), "f"); __classPrivateFieldSet(this, _CDPPage_frameManager, new FrameManager_js_1.FrameManager(client, this, ignoreHTTPSErrors, __classPrivateFieldGet(this, _CDPPage_timeoutSettings, "f")), "f"); __classPrivateFieldSet(this, _CDPPage_emulationManager, new EmulationManager_js_1.EmulationManager(client), "f"); __classPrivateFieldSet(this, _CDPPage_tracing, new Tracing_js_1.Tracing(client), "f"); __classPrivateFieldSet(this, _CDPPage_coverage, new Coverage_js_1.Coverage(client), "f"); __classPrivateFieldSet(this, _CDPPage_screenshotTaskQueue, screenshotTaskQueue, "f"); __classPrivateFieldSet(this, _CDPPage_viewport, null, "f"); __classPrivateFieldGet(this, _CDPPage_target, "f") ._targetManager() .addTargetInterceptor(__classPrivateFieldGet(this, _CDPPage_client, "f"), __classPrivateFieldGet(this, _CDPPage_onAttachedToTarget, "f")); __classPrivateFieldGet(this, _CDPPage_target, "f") ._targetManager() .on("targetGone" /* TargetManagerEmittedEvents.TargetGone */, __classPrivateFieldGet(this, _CDPPage_onDetachedFromTarget, "f")); __classPrivateFieldGet(this, _CDPPage_frameManager, "f").on(FrameManager_js_1.FrameManagerEmittedEvents.FrameAttached, event => { return this.emit("frameattached" /* PageEmittedEvents.FrameAttached */, event); }); __classPrivateFieldGet(this, _CDPPage_frameManager, "f").on(FrameManager_js_1.FrameManagerEmittedEvents.FrameDetached, event => { return this.emit("framedetached" /* PageEmittedEvents.FrameDetached */, event); }); __classPrivateFieldGet(this, _CDPPage_frameManager, "f").on(FrameManager_js_1.FrameManagerEmittedEvents.FrameNavigated, event => { return this.emit("framenavigated" /* PageEmittedEvents.FrameNavigated */, event); }); const networkManager = __classPrivateFieldGet(this, _CDPPage_frameManager, "f").networkManager; networkManager.on(NetworkManager_js_1.NetworkManagerEmittedEvents.Request, event => { return this.emit("request" /* PageEmittedEvents.Request */, event); }); networkManager.on(NetworkManager_js_1.NetworkManagerEmittedEvents.RequestServedFromCache, event => { return this.emit("requestservedfromcache" /* PageEmittedEvents.RequestServedFromCache */, event); }); networkManager.on(NetworkManager_js_1.NetworkManagerEmittedEvents.Response, event => { return this.emit("response" /* PageEmittedEvents.Response */, event); }); networkManager.on(NetworkManager_js_1.NetworkManagerEmittedEvents.RequestFailed, event => { return this.emit("requestfailed" /* PageEmittedEvents.RequestFailed */, event); }); networkManager.on(NetworkManager_js_1.NetworkManagerEmittedEvents.RequestFinished, event => { return this.emit("requestfinished" /* PageEmittedEvents.RequestFinished */, event); }); client.on('Page.domContentEventFired', () => { return this.emit("domcontentloaded" /* PageEmittedEvents.DOMContentLoaded */); }); client.on('Page.loadEventFired', () => { return this.emit("load" /* PageEmittedEvents.Load */); }); client.on('Runtime.consoleAPICalled', event => { return __classPrivateFieldGet(this, _CDPPage_instances, "m", _CDPPage_onConsoleAPI).call(this, event); }); client.on('Runtime.bindingCalled', event => { return __classPrivateFieldGet(this, _CDPPage_instances, "m", _CDPPage_onBindingCalled).call(this, event); }); client.on('Page.javascriptDialogOpening', event => { return __classPrivateFieldGet(this, _CDPPage_instances, "m", _CDPPage_onDialog).call(this, event); }); client.on('Runtime.exceptionThrown', exception => { return __classPrivateFieldGet(this, _CDPPage_instances, "m", _CDPPage_handleException).call(this, exception.exceptionDetails); }); client.on('Inspector.targetCrashed', () => { return __classPrivateFieldGet(this, _CDPPage_instances, "m", _CDPPage_onTargetCrashed).call(this); }); client.on('Performance.metrics', event => { return __classPrivateFieldGet(this, _CDPPage_instances, "m", _CDPPage_emitMetrics).call(this, event); }); client.on('Log.entryAdded', event => { return __classPrivateFieldGet(this, _CDPPage_instances, "m", _CDPPage_onLogEntryAdded).call(this, event); }); client.on('Page.fileChooserOpened', event => { return __classPrivateFieldGet(this, _CDPPage_instances, "m", _CDPPage_onFileChooser).call(this, event); }); __classPrivateFieldGet(this, _CDPPage_target, "f")._isClosedPromise.then(() => { __classPrivateFieldGet(this, _CDPPage_target, "f") ._targetManager() .removeTargetInterceptor(__classPrivateFieldGet(this, _CDPPage_client, "f"), __classPrivateFieldGet(this, _CDPPage_onAttachedToTarget, "f")); __classPrivateFieldGet(this, _CDPPage_target, "f") ._targetManager() .off("targetGone" /* TargetManagerEmittedEvents.TargetGone */, __classPrivateFieldGet(this, _CDPPage_onDetachedFromTarget, "f")); this.emit("close" /* PageEmittedEvents.Close */); __classPrivateFieldSet(this, _CDPPage_closed, true, "f"); }); } /** * @internal */ static async _create(client, target, ignoreHTTPSErrors, defaultViewport, screenshotTaskQueue) { const page = new CDPPage(client, target, ignoreHTTPSErrors, screenshotTaskQueue); await __classPrivateFieldGet(page, _CDPPage_instances, "m", _CDPPage_initialize).call(page); if (defaultViewport) { try { await page.setViewport(defaultViewport); } catch (err) { if ((0, ErrorLike_js_1.isErrorLike)(err) && (0, Connection_js_1.isTargetClosedError)(err)) { (0, util_js_1.debugError)(err); } else { throw err; } } } return page; } /** * @returns `true` if drag events are being intercepted, `false` otherwise. */ isDragInterceptionEnabled() { return __classPrivateFieldGet(this, _CDPPage_userDragInterceptionEnabled, "f"); } /** * @returns `true` if the page has JavaScript enabled, `false` otherwise. */ isJavaScriptEnabled() { return __classPrivateFieldGet(this, _CDPPage_javascriptEnabled, "f"); } /** * 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']); * ``` */ waitForFileChooser(options = {}) { const needsEnable = __classPrivateFieldGet(this, _CDPPage_fileChooserPromises, "f").size === 0; const { timeout = __classPrivateFieldGet(this, _CDPPage_timeoutSettings, "f").timeout() } = options; const promise = (0, DeferredPromise_js_1.createDeferredPromise)({ message: `Waiting for \`FileChooser\` failed: ${timeout}ms exceeded`, timeout, }); __classPrivateFieldGet(this, _CDPPage_fileChooserPromises, "f").add(promise); let enablePromise; if (needsEnable) { enablePromise = __classPrivateFieldGet(this, _CDPPage_client, "f").send('Page.setInterceptFileChooserDialog', { enabled: true, }); } return Promise.all([promise, enablePromise]) .then(([result]) => { return result; }) .catch(error => { __classPrivateFieldGet(this, _CDPPage_fileChooserPromises, "f").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}); * ``` */ async setGeolocation(options) { 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 __classPrivateFieldGet(this, _CDPPage_client, "f").send('Emulation.setGeolocationOverride', { longitude, latitude, accuracy, }); } /** * @returns A target this page was created from. */ target() { return __classPrivateFieldGet(this, _CDPPage_target, "f"); } /** * @internal */ _client() { return __classPrivateFieldGet(this, _CDPPage_client, "f"); } /** * Get the browser the page belongs to. */ browser() { return __classPrivateFieldGet(this, _CDPPage_target, "f").browser(); } /** * Get the browser context that the page belongs to. */ browserContext() { return __classPrivateFieldGet(this, _CDPPage_target, "f").browserContext(); } /** * @returns The page's main frame. * * @remarks * Page is guaranteed to have a main frame which persists during navigations. */ mainFrame() { return __classPrivateFieldGet(this, _CDPPage_frameManager, "f").mainFrame(); } get keyboard() { return __classPrivateFieldGet(this, _CDPPage_keyboard, "f"); } get touchscreen() { return __classPrivateFieldGet(this, _CDPPage_touchscreen, "f"); } get coverage() { return __classPrivateFieldGet(this, _CDPPage_coverage, "f"); } get tracing() { return __classPrivateFieldGet(this, _CDPPage_tracing, "f"); } get accessibility() { return __classPrivateFieldGet(this, _CDPPage_accessibility, "f"); } /** * @returns An array of all frames attached to the page. */ frames() { return __classPrivateFieldGet(this, _CDPPage_frameManager, "f").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 */ workers() { return Array.from(__classPrivateFieldGet(this, _CDPPage_workers, "f").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. */ async setRequestInterception(value) { return __classPrivateFieldGet(this, _CDPPage_frameManager, "f").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. */ async setDragInterception(enabled) { __classPrivateFieldSet(this, _CDPPage_userDragInterceptionEnabled, enabled, "f"); return __classPrivateFieldGet(this, _CDPPage_client, "f").send('Input.setInterceptDrags', { enabled }); } /** * @param enabled - When `true`, enables offline mode for the page. * @remarks * NOTE: while this method sets the network connection to offline, it does * not change the parameters used in [page.emulateNetworkConditions(networkConditions)] * (#pageemulatenetworkconditionsnetworkconditions) */ setOfflineMode(enabled) { return __classPrivateFieldGet(this, _CDPPage_frameManager, "f").networkManager.setOfflineMode(enabled); } /** * @param networkConditions - Passing `null` disables network condition emulation. * @example * * ```ts * const puppeteer = require('puppeteer'); * const slow3G = puppeteer.networkConditions['Slow 3G']; * * (async () => { * const browser = await puppeteer.launch(); * const page = await browser.newPage(); * await page.emulateNetworkConditions(slow3G); * await page.goto('https://www.google.com'); * // other actions... * await browser.close(); * })(); * ``` * * @remarks * NOTE: This does not affect WebSockets and WebRTC PeerConnections (see * https://crbug.com/563644). To set the page offline, you can use * [page.setOfflineMode(enabled)](#pagesetofflinemodeenabled). */ emulateNetworkConditions(networkConditions) { return __classPrivateFieldGet(this, _CDPPage_frameManager, "f").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. */ setDefaultNavigationTimeout(timeout) { __classPrivateFieldGet(this, _CDPPage_timeoutSettings, "f").setDefaultNavigationTimeout(timeout); } /** * @param timeout - Maximum time in milliseconds. */ setDefaultTimeout(timeout) { __classPrivateFieldGet(this, _CDPPage_timeoutSettings, "f").setDefaultTimeout(timeout); } /** * @returns Maximum time in milliseconds. */ getDefaultTimeout() { return __classPrivateFieldGet(this, _CDPPage_timeoutSettings, "f").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. */ async $(selector) { 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 */ async $$(selector) { 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 */ async evaluateHandle(pageFunction, ...args) { 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. */ async queryObjects(prototypeHandle) { const context = await this.mainFrame().executionContext(); (0, assert_js_1.assert)(!prototypeHandle.disposed, 'Prototype JSHandle is disposed!'); const remoteObject = prototypeHandle.remoteObject(); (0, assert_js_1.assert)(remoteObject.objectId, 'Prototype JSHandle must not be referencing primitive value'); const response = await context._client.send('Runtime.queryObjects', { prototypeObjectId: remoteObject.objectId, }); return (0, util_js_1.createJSHandle)(context, response.objects); } /** * 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. */ async $eval(selector, pageFunction, ...args) { 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. */ async $$eval(selector, pageFunction, ...args) { 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 */ async $x(expression) { 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. */ async cookies(...urls) { const originalCookies = (await __classPrivateFieldGet(this, _CDPPage_client, "f").send('Network.getCookies', { urls: urls.length ? urls : [this.url()], })).cookies; const unsupportedCookieAttributes = ['priority']; const filterUnsupportedAttributes = (cookie) => { for (const attr of unsupportedCookieAttributes) { delete cookie[attr]; } return cookie; }; return originalCookies.map(filterUnsupportedAttributes); } async deleteCookie(...cookies) { const pageURL = this.url(); for (const cookie of cookies) { const item = Object.assign({}, cookie); if (!cookie.url && pageURL.startsWith('http')) { item.url = pageURL; } await __classPrivateFieldGet(this, _CDPPage_client, "f").send('Network.deleteCookies', item); } } /** * @example * * ```ts * await page.setCookie(cookieObject1, cookieObject2); * ``` */ async setCookie(...cookies) { 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; } (0, assert_js_1.assert)(item.url !== 'about:blank', `Blank page can not have cookie "${item.name}"`); (0, assert_js_1.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 __classPrivateFieldGet(this, _CDPPage_client, "f").send('Network.setCookies', { cookies: items }); } } /** * Adds a `