/** * Copyright (c) Microsoft Corporation. * * 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 * as frames from './frames'; import * as input from './input'; import * as js from './javascript'; import * as types from './types'; import * as injectedSource from './generated/injectedSource'; import { assert, helper, debugError } from './helper'; import Injected from './injected/injected'; import { Page } from './page'; import * as platform from './platform'; import { Selectors } from './selectors'; export class FrameExecutionContext extends js.ExecutionContext { readonly frame: frames.Frame; private _injectedPromise?: Promise; private _injectedGeneration = -1; constructor(delegate: js.ExecutionContextDelegate, frame: frames.Frame) { super(delegate); this.frame = frame; } async _evaluate(returnByValue: boolean, pageFunction: string | Function, ...args: any[]): Promise { const needsAdoption = (value: any): boolean => { return typeof value === 'object' && value instanceof ElementHandle && value._context !== this; }; if (!args.some(needsAdoption)) { // Only go through asynchronous calls if required. return this._delegate.evaluate(this, returnByValue, pageFunction, ...args); } const toDispose: Promise[] = []; const adopted = await Promise.all(args.map(async arg => { if (!needsAdoption(arg)) return arg; const adopted = this.frame._page._delegate.adoptElementHandle(arg, this); toDispose.push(adopted); return adopted; })); let result; try { result = await this._delegate.evaluate(this, returnByValue, pageFunction, ...adopted); } finally { await Promise.all(toDispose.map(handlePromise => handlePromise.then(handle => handle.dispose()))); } return result; } _createHandle(remoteObject: any): js.JSHandle { if (this.frame._page._delegate.isElementHandle(remoteObject)) return new ElementHandle(this, remoteObject); return super._createHandle(remoteObject); } _injected(): Promise { const selectors = Selectors._instance(); if (this._injectedPromise && selectors._generation !== this._injectedGeneration) { this._injectedPromise.then(handle => handle.dispose()); this._injectedPromise = undefined; } if (!this._injectedPromise) { const source = ` new (${injectedSource.source})([ ${selectors._sources.join(',\n')}, ]) `; this._injectedPromise = this.evaluateHandle(source); this._injectedGeneration = selectors._generation; } return this._injectedPromise; } async _$(selector: string, scope?: ElementHandle): Promise | null> { const handle = await this.evaluateHandle( (injected: Injected, selector: string, scope?: Node) => injected.querySelector(selector, scope || document), await this._injected(), normalizeSelector(selector), scope ); if (!handle.asElement()) await handle.dispose(); return handle.asElement() as ElementHandle; } async _$array(selector: string, scope?: ElementHandle): Promise> { const arrayHandle = await this.evaluateHandle( (injected: Injected, selector: string, scope?: Node) => injected.querySelectorAll(selector, scope || document), await this._injected(), normalizeSelector(selector), scope ); return arrayHandle; } async _$$(selector: string, scope?: ElementHandle): Promise[]> { const arrayHandle = await this._$array(selector, scope); const properties = await arrayHandle.getProperties(); await arrayHandle.dispose(); const result: ElementHandle[] = []; for (const property of properties.values()) { const elementHandle = property.asElement() as ElementHandle; if (elementHandle) result.push(elementHandle); else await property.dispose(); } return result; } } export class ElementHandle extends js.JSHandle { readonly _context: FrameExecutionContext; readonly _page: Page; constructor(context: FrameExecutionContext, remoteObject: any) { super(context, remoteObject); this._context = context; this._page = context.frame._page; } asElement(): ElementHandle | null { return this; } _evaluateInUtility: types.EvaluateOn = async (pageFunction, ...args) => { const utility = await this._context.frame._utilityContext(); return utility.evaluate(pageFunction as any, this, ...args); } async ownerFrame(): Promise { const frameId = await this._page._delegate.getOwnerFrame(this); if (!frameId) return null; const pages = this._page.browserContext()._existingPages(); for (const page of pages) { const frame = page._frameManager.frame(frameId); if (frame) return frame; } return null; } async contentFrame(): Promise { const isFrameElement = await this._evaluateInUtility(node => node && (node.nodeName === 'IFRAME' || node.nodeName === 'FRAME')); if (!isFrameElement) return null; return this._page._delegate.getContentFrame(this); } async scrollIntoViewIfNeeded() { const error = await this._evaluateInUtility(async (node: Node, pageJavascriptEnabled: boolean) => { if (!node.isConnected) return 'Node is detached from document'; if (node.nodeType !== Node.ELEMENT_NODE) return 'Node is not of type HTMLElement'; const element = node as Element; // force-scroll if page's javascript is disabled. if (!pageJavascriptEnabled) { // @ts-ignore because only Chromium still supports 'instant' element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'}); return false; } const visibleRatio = await new Promise(resolve => { const observer = new IntersectionObserver(entries => { resolve(entries[0].intersectionRatio); observer.disconnect(); }); observer.observe(element); // Firefox doesn't call IntersectionObserver callback unless // there are rafs. requestAnimationFrame(() => {}); }); if (visibleRatio !== 1.0) { // @ts-ignore because only Chromium still supports 'instant' element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'}); } return false; }, !!this._page.browserContext()._options.javaScriptEnabled); if (error) throw new Error(error); } private async _ensurePointerActionPoint(relativePoint?: types.Point): Promise { await this.scrollIntoViewIfNeeded(); if (!relativePoint) return this._clickablePoint(); let r = await this._viewportPointAndScroll(relativePoint); if (r.scrollX || r.scrollY) { const error = await this._evaluateInUtility((element, scrollX, scrollY) => { if (!element.ownerDocument || !element.ownerDocument.defaultView) return 'Node does not have a containing window'; element.ownerDocument.defaultView.scrollBy(scrollX, scrollY); return false; }, r.scrollX, r.scrollY); if (error) throw new Error(error); r = await this._viewportPointAndScroll(relativePoint); if (r.scrollX || r.scrollY) throw new Error('Failed to scroll relative point into viewport'); } return r.point; } private async _clickablePoint(): Promise { const intersectQuadWithViewport = (quad: types.Quad): types.Quad => { return quad.map(point => ({ x: Math.min(Math.max(point.x, 0), metrics.width), y: Math.min(Math.max(point.y, 0), metrics.height), })) as types.Quad; }; const computeQuadArea = (quad: types.Quad) => { // Compute sum of all directed areas of adjacent triangles // https://en.wikipedia.org/wiki/Polygon#Simple_polygons let area = 0; for (let i = 0; i < quad.length; ++i) { const p1 = quad[i]; const p2 = quad[(i + 1) % quad.length]; area += (p1.x * p2.y - p2.x * p1.y) / 2; } return Math.abs(area); }; const [quads, metrics] = await Promise.all([ this._page._delegate.getContentQuads(this), this._page._delegate.layoutViewport(), ]); if (!quads || !quads.length) throw new Error('Node is either not visible or not an HTMLElement'); const filtered = quads.map(quad => intersectQuadWithViewport(quad)).filter(quad => computeQuadArea(quad) > 1); if (!filtered.length) throw new Error('Node is either not visible or not an HTMLElement'); // Return the middle point of the first quad. const result = { x: 0, y: 0 }; for (const point of filtered[0]) { result.x += point.x / 4; result.y += point.y / 4; } return result; } private async _viewportPointAndScroll(relativePoint: types.Point): Promise<{point: types.Point, scrollX: number, scrollY: number}> { const [box, border] = await Promise.all([ this.boundingBox(), this._evaluateInUtility((node: Node) => { if (node.nodeType !== Node.ELEMENT_NODE || !node.ownerDocument || !node.ownerDocument.defaultView) return { x: 0, y: 0 }; const style = node.ownerDocument.defaultView.getComputedStyle(node as Element); return { x: parseInt(style.borderLeftWidth || '', 10), y: parseInt(style.borderTopWidth || '', 10) }; }).catch(debugError), ]); const point = { x: relativePoint.x, y: relativePoint.y }; if (box) { point.x += box.x; point.y += box.y; } if (border) { // Make point relative to the padding box to align with offsetX/offsetY. point.x += border.x; point.y += border.y; } const metrics = await this._page._delegate.layoutViewport(); // Give 20 extra pixels to avoid any issues on viewport edge. let scrollX = 0; if (point.x < 20) scrollX = point.x - 20; if (point.x > metrics.width - 20) scrollX = point.x - metrics.width + 20; let scrollY = 0; if (point.y < 20) scrollY = point.y - 20; if (point.y > metrics.height - 20) scrollY = point.y - metrics.height + 20; return { point, scrollX, scrollY }; } async _performPointerAction(action: (point: types.Point) => Promise, options?: input.PointerActionOptions): Promise { const point = await this._ensurePointerActionPoint(options ? options.relativePoint : undefined); let restoreModifiers: input.Modifier[] | undefined; if (options && options.modifiers) restoreModifiers = await this._page.keyboard._ensureModifiers(options.modifiers); await action(point); if (restoreModifiers) await this._page.keyboard._ensureModifiers(restoreModifiers); } hover(options?: input.PointerActionOptions): Promise { return this._performPointerAction(point => this._page.mouse.move(point.x, point.y), options); } click(options?: input.ClickOptions): Promise { return this._performPointerAction(point => this._page.mouse.click(point.x, point.y, options), options); } dblclick(options?: input.MultiClickOptions): Promise { return this._performPointerAction(point => this._page.mouse.dblclick(point.x, point.y, options), options); } tripleclick(options?: input.MultiClickOptions): Promise { return this._performPointerAction(point => this._page.mouse.tripleclick(point.x, point.y, options), options); } async select(...values: (string | ElementHandle | types.SelectOption)[]): Promise { const options = values.map(value => typeof value === 'object' ? value : { value }); for (const option of options) { if (option instanceof ElementHandle) continue; if (option.value !== undefined) assert(helper.isString(option.value), 'Values must be strings. Found value "' + option.value + '" of type "' + (typeof option.value) + '"'); if (option.label !== undefined) assert(helper.isString(option.label), 'Labels must be strings. Found label "' + option.label + '" of type "' + (typeof option.label) + '"'); if (option.index !== undefined) assert(helper.isNumber(option.index), 'Indices must be numbers. Found index "' + option.index + '" of type "' + (typeof option.index) + '"'); } return this._evaluateInUtility((node: Node, ...optionsToSelect: (Node | types.SelectOption)[]) => { if (node.nodeName.toLowerCase() !== 'select') throw new Error('Element is not a ,