2020-01-06 18:22:35 -08:00
|
|
|
/**
|
|
|
|
* 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.
|
|
|
|
*/
|
2019-11-27 16:02:31 -08:00
|
|
|
|
|
|
|
import * as frames from './frames';
|
2019-11-27 16:03:51 -08:00
|
|
|
import * as input from './input';
|
|
|
|
import * as js from './javascript';
|
|
|
|
import * as types from './types';
|
2019-11-28 12:50:52 -08:00
|
|
|
import * as injectedSource from './generated/injectedSource';
|
2019-12-05 09:54:50 -08:00
|
|
|
import { assert, helper, debugError } from './helper';
|
2019-12-02 13:12:28 -08:00
|
|
|
import Injected from './injected/injected';
|
2019-12-12 21:11:52 -08:00
|
|
|
import { Page } from './page';
|
2020-01-07 11:55:24 -08:00
|
|
|
import * as platform from './platform';
|
2020-01-28 11:20:34 -08:00
|
|
|
import { Selectors } from './selectors';
|
2019-11-27 16:02:31 -08:00
|
|
|
|
2019-12-12 21:11:52 -08:00
|
|
|
export class FrameExecutionContext extends js.ExecutionContext {
|
2019-12-19 15:19:22 -08:00
|
|
|
readonly frame: frames.Frame;
|
2019-11-28 12:50:52 -08:00
|
|
|
|
|
|
|
private _injectedPromise?: Promise<js.JSHandle>;
|
2020-01-28 11:20:34 -08:00
|
|
|
private _injectedGeneration = -1;
|
2019-11-28 12:50:52 -08:00
|
|
|
|
2019-12-12 21:11:52 -08:00
|
|
|
constructor(delegate: js.ExecutionContextDelegate, frame: frames.Frame) {
|
|
|
|
super(delegate);
|
2019-12-19 15:19:22 -08:00
|
|
|
this.frame = frame;
|
2019-12-02 13:12:28 -08:00
|
|
|
}
|
|
|
|
|
2019-12-19 11:44:07 -08:00
|
|
|
async _evaluate(returnByValue: boolean, pageFunction: string | Function, ...args: any[]): Promise<any> {
|
|
|
|
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<ElementHandle>[] = [];
|
|
|
|
const adopted = await Promise.all(args.map(async arg => {
|
|
|
|
if (!needsAdoption(arg))
|
|
|
|
return arg;
|
2019-12-19 15:19:22 -08:00
|
|
|
const adopted = this.frame._page._delegate.adoptElementHandle(arg, this);
|
2019-12-19 11:44:07 -08:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2020-01-13 13:33:25 -08:00
|
|
|
_createHandle(remoteObject: any): js.JSHandle {
|
2019-12-19 15:19:22 -08:00
|
|
|
if (this.frame._page._delegate.isElementHandle(remoteObject))
|
2019-12-12 21:11:52 -08:00
|
|
|
return new ElementHandle(this, remoteObject);
|
|
|
|
return super._createHandle(remoteObject);
|
|
|
|
}
|
|
|
|
|
|
|
|
_injected(): Promise<js.JSHandle> {
|
2020-01-28 11:20:34 -08:00
|
|
|
const selectors = Selectors._instance();
|
|
|
|
if (this._injectedPromise && selectors._generation !== this._injectedGeneration) {
|
|
|
|
this._injectedPromise.then(handle => handle.dispose());
|
|
|
|
this._injectedPromise = undefined;
|
|
|
|
}
|
2019-11-28 12:50:52 -08:00
|
|
|
if (!this._injectedPromise) {
|
|
|
|
const source = `
|
|
|
|
new (${injectedSource.source})([
|
2020-02-03 16:14:37 -08:00
|
|
|
${selectors._sources.join(',\n')}
|
2019-11-28 12:50:52 -08:00
|
|
|
])
|
|
|
|
`;
|
2019-12-12 21:11:52 -08:00
|
|
|
this._injectedPromise = this.evaluateHandle(source);
|
2020-01-28 11:20:34 -08:00
|
|
|
this._injectedGeneration = selectors._generation;
|
2019-11-28 12:50:52 -08:00
|
|
|
}
|
|
|
|
return this._injectedPromise;
|
|
|
|
}
|
|
|
|
|
2019-12-17 14:30:02 -08:00
|
|
|
async _$(selector: string, scope?: ElementHandle): Promise<ElementHandle<Element> | null> {
|
2019-12-12 21:11:52 -08:00
|
|
|
const handle = await this.evaluateHandle(
|
2019-12-17 14:30:02 -08:00
|
|
|
(injected: Injected, selector: string, scope?: Node) => injected.querySelector(selector, scope || document),
|
|
|
|
await this._injected(), normalizeSelector(selector), scope
|
2019-12-02 17:33:44 -08:00
|
|
|
);
|
|
|
|
if (!handle.asElement())
|
2019-11-28 12:50:52 -08:00
|
|
|
await handle.dispose();
|
2020-01-13 13:33:25 -08:00
|
|
|
return handle.asElement() as ElementHandle<Element>;
|
2019-11-28 12:50:52 -08:00
|
|
|
}
|
2019-11-27 16:02:31 -08:00
|
|
|
|
2019-12-17 14:30:02 -08:00
|
|
|
async _$array(selector: string, scope?: ElementHandle): Promise<js.JSHandle<Element[]>> {
|
2019-12-12 21:11:52 -08:00
|
|
|
const arrayHandle = await this.evaluateHandle(
|
2019-12-17 14:30:02 -08:00
|
|
|
(injected: Injected, selector: string, scope?: Node) => injected.querySelectorAll(selector, scope || document),
|
|
|
|
await this._injected(), normalizeSelector(selector), scope
|
2019-12-02 17:33:44 -08:00
|
|
|
);
|
2019-12-17 14:30:02 -08:00
|
|
|
return arrayHandle;
|
|
|
|
}
|
|
|
|
|
|
|
|
async _$$(selector: string, scope?: ElementHandle): Promise<ElementHandle<Element>[]> {
|
|
|
|
const arrayHandle = await this._$array(selector, scope);
|
2019-12-02 17:33:44 -08:00
|
|
|
const properties = await arrayHandle.getProperties();
|
|
|
|
await arrayHandle.dispose();
|
2020-01-13 13:33:25 -08:00
|
|
|
const result: ElementHandle<Element>[] = [];
|
2019-12-02 17:33:44 -08:00
|
|
|
for (const property of properties.values()) {
|
2020-01-13 13:33:25 -08:00
|
|
|
const elementHandle = property.asElement() as ElementHandle<Element>;
|
2019-12-02 17:33:44 -08:00
|
|
|
if (elementHandle)
|
|
|
|
result.push(elementHandle);
|
|
|
|
else
|
|
|
|
await property.dispose();
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
}
|
2019-12-02 13:12:28 -08:00
|
|
|
|
2019-12-05 16:26:09 -08:00
|
|
|
export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
|
2019-12-12 21:11:52 -08:00
|
|
|
readonly _context: FrameExecutionContext;
|
|
|
|
readonly _page: Page;
|
2019-11-27 16:02:31 -08:00
|
|
|
|
2019-12-12 21:11:52 -08:00
|
|
|
constructor(context: FrameExecutionContext, remoteObject: any) {
|
2019-12-02 13:12:28 -08:00
|
|
|
super(context, remoteObject);
|
2020-01-13 13:33:25 -08:00
|
|
|
this._context = context;
|
2019-12-19 15:19:22 -08:00
|
|
|
this._page = context.frame._page;
|
2019-12-18 13:51:45 -08:00
|
|
|
}
|
|
|
|
|
2019-12-05 16:26:09 -08:00
|
|
|
asElement(): ElementHandle<T> | null {
|
2019-11-27 16:02:31 -08:00
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
2019-12-19 15:19:22 -08:00
|
|
|
_evaluateInUtility: types.EvaluateOn<T> = async (pageFunction, ...args) => {
|
|
|
|
const utility = await this._context.frame._utilityContext();
|
2020-01-13 13:33:25 -08:00
|
|
|
return utility.evaluate(pageFunction as any, this, ...args);
|
2019-12-19 15:19:22 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
async ownerFrame(): Promise<frames.Frame | null> {
|
2020-01-27 11:43:43 -08:00
|
|
|
const frameId = await this._page._delegate.getOwnerFrame(this);
|
|
|
|
if (!frameId)
|
|
|
|
return null;
|
2020-02-10 10:41:45 -08:00
|
|
|
const pages = this._page.context()._existingPages();
|
2020-01-27 11:43:43 -08:00
|
|
|
for (const page of pages) {
|
|
|
|
const frame = page._frameManager.frame(frameId);
|
|
|
|
if (frame)
|
|
|
|
return frame;
|
|
|
|
}
|
|
|
|
return null;
|
2019-12-19 15:19:22 -08:00
|
|
|
}
|
|
|
|
|
2019-11-27 16:02:31 -08:00
|
|
|
async contentFrame(): Promise<frames.Frame | null> {
|
2020-01-30 11:04:09 -08:00
|
|
|
const isFrameElement = await this._evaluateInUtility(node => node && (node.nodeName === 'IFRAME' || node.nodeName === 'FRAME'));
|
2019-12-19 15:19:22 -08:00
|
|
|
if (!isFrameElement)
|
|
|
|
return null;
|
2019-12-12 21:11:52 -08:00
|
|
|
return this._page._delegate.getContentFrame(this);
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
|
|
|
|
2020-01-06 13:16:56 -08:00
|
|
|
async scrollIntoViewIfNeeded() {
|
2019-12-19 15:19:22 -08:00
|
|
|
const error = await this._evaluateInUtility(async (node: Node, pageJavascriptEnabled: boolean) => {
|
2019-12-05 16:26:09 -08:00
|
|
|
if (!node.isConnected)
|
2019-11-27 16:02:31 -08:00
|
|
|
return 'Node is detached from document';
|
2019-12-05 16:26:09 -08:00
|
|
|
if (node.nodeType !== Node.ELEMENT_NODE)
|
2019-11-27 16:02:31 -08:00
|
|
|
return 'Node is not of type HTMLElement';
|
2019-12-05 16:26:09 -08:00
|
|
|
const element = node as Element;
|
2019-11-27 16:02:31 -08:00
|
|
|
// force-scroll if page's javascript is disabled.
|
|
|
|
if (!pageJavascriptEnabled) {
|
2019-12-06 11:52:32 -08:00
|
|
|
// @ts-ignore because only Chromium still supports 'instant'
|
2019-11-27 16:02:31 -08:00
|
|
|
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(() => {});
|
|
|
|
});
|
2019-12-05 16:26:09 -08:00
|
|
|
if (visibleRatio !== 1.0) {
|
2019-12-06 11:52:32 -08:00
|
|
|
// @ts-ignore because only Chromium still supports 'instant'
|
2019-11-27 16:02:31 -08:00
|
|
|
element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'});
|
2019-12-05 16:26:09 -08:00
|
|
|
}
|
2019-11-27 16:02:31 -08:00
|
|
|
return false;
|
2020-02-10 10:41:45 -08:00
|
|
|
}, !!this._page.context()._options.javaScriptEnabled);
|
2019-11-27 16:02:31 -08:00
|
|
|
if (error)
|
|
|
|
throw new Error(error);
|
|
|
|
}
|
|
|
|
|
2019-12-05 09:54:50 -08:00
|
|
|
private async _ensurePointerActionPoint(relativePoint?: types.Point): Promise<types.Point> {
|
2020-01-06 13:16:56 -08:00
|
|
|
await this.scrollIntoViewIfNeeded();
|
2019-12-05 09:54:50 -08:00
|
|
|
if (!relativePoint)
|
|
|
|
return this._clickablePoint();
|
|
|
|
let r = await this._viewportPointAndScroll(relativePoint);
|
|
|
|
if (r.scrollX || r.scrollY) {
|
2019-12-19 15:19:22 -08:00
|
|
|
const error = await this._evaluateInUtility((element, scrollX, scrollY) => {
|
2019-12-05 09:54:50 -08:00
|
|
|
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<types.Point> {
|
|
|
|
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([
|
2019-12-12 21:11:52 -08:00
|
|
|
this._page._delegate.getContentQuads(this),
|
|
|
|
this._page._delegate.layoutViewport(),
|
2020-02-05 16:53:36 -08:00
|
|
|
] as const);
|
2019-12-05 09:54:50 -08:00
|
|
|
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(),
|
2019-12-19 15:19:22 -08:00
|
|
|
this._evaluateInUtility((node: Node) => {
|
2020-01-13 13:33:25 -08:00
|
|
|
if (node.nodeType !== Node.ELEMENT_NODE || !node.ownerDocument || !node.ownerDocument.defaultView)
|
2019-12-06 11:33:24 -08:00
|
|
|
return { x: 0, y: 0 };
|
|
|
|
const style = node.ownerDocument.defaultView.getComputedStyle(node as Element);
|
2020-01-13 13:33:25 -08:00
|
|
|
return { x: parseInt(style.borderLeftWidth || '', 10), y: parseInt(style.borderTopWidth || '', 10) };
|
2019-12-05 09:54:50 -08:00
|
|
|
}).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;
|
|
|
|
}
|
2019-12-12 21:11:52 -08:00
|
|
|
const metrics = await this._page._delegate.layoutViewport();
|
2019-12-08 17:17:49 -08:00
|
|
|
// Give 20 extra pixels to avoid any issues on viewport edge.
|
2019-12-05 09:54:50 -08:00
|
|
|
let scrollX = 0;
|
2019-12-08 17:17:49 -08:00
|
|
|
if (point.x < 20)
|
|
|
|
scrollX = point.x - 20;
|
|
|
|
if (point.x > metrics.width - 20)
|
|
|
|
scrollX = point.x - metrics.width + 20;
|
2019-12-05 09:54:50 -08:00
|
|
|
let scrollY = 0;
|
2019-12-08 17:17:49 -08:00
|
|
|
if (point.y < 20)
|
|
|
|
scrollY = point.y - 20;
|
|
|
|
if (point.y > metrics.height - 20)
|
|
|
|
scrollY = point.y - metrics.height + 20;
|
2019-12-05 09:54:50 -08:00
|
|
|
return { point, scrollX, scrollY };
|
|
|
|
}
|
|
|
|
|
2019-11-27 16:03:51 -08:00
|
|
|
async _performPointerAction(action: (point: types.Point) => Promise<void>, options?: input.PointerActionOptions): Promise<void> {
|
2019-12-05 09:54:50 -08:00
|
|
|
const point = await this._ensurePointerActionPoint(options ? options.relativePoint : undefined);
|
2019-11-27 16:02:31 -08:00
|
|
|
let restoreModifiers: input.Modifier[] | undefined;
|
|
|
|
if (options && options.modifiers)
|
2019-12-12 21:11:52 -08:00
|
|
|
restoreModifiers = await this._page.keyboard._ensureModifiers(options.modifiers);
|
2019-11-27 16:02:31 -08:00
|
|
|
await action(point);
|
|
|
|
if (restoreModifiers)
|
2019-12-12 21:11:52 -08:00
|
|
|
await this._page.keyboard._ensureModifiers(restoreModifiers);
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
hover(options?: input.PointerActionOptions): Promise<void> {
|
2019-12-12 21:11:52 -08:00
|
|
|
return this._performPointerAction(point => this._page.mouse.move(point.x, point.y), options);
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
click(options?: input.ClickOptions): Promise<void> {
|
2019-12-12 21:11:52 -08:00
|
|
|
return this._performPointerAction(point => this._page.mouse.click(point.x, point.y, options), options);
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
dblclick(options?: input.MultiClickOptions): Promise<void> {
|
2019-12-12 21:11:52 -08:00
|
|
|
return this._performPointerAction(point => this._page.mouse.dblclick(point.x, point.y, options), options);
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
tripleclick(options?: input.MultiClickOptions): Promise<void> {
|
2019-12-12 21:11:52 -08:00
|
|
|
return this._performPointerAction(point => this._page.mouse.tripleclick(point.x, point.y, options), options);
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
|
|
|
|
2020-01-03 12:59:06 -08:00
|
|
|
async select(...values: (string | ElementHandle | types.SelectOption)[]): Promise<string[]> {
|
2019-11-27 16:02:31 -08:00
|
|
|
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) + '"');
|
|
|
|
}
|
2020-01-03 12:59:06 -08:00
|
|
|
return this._evaluateInUtility((node: Node, ...optionsToSelect: (Node | types.SelectOption)[]) => {
|
|
|
|
if (node.nodeName.toLowerCase() !== 'select')
|
|
|
|
throw new Error('Element is not a <select> element.');
|
|
|
|
const element = node as HTMLSelectElement;
|
|
|
|
|
|
|
|
const options = Array.from(element.options);
|
2020-01-13 13:33:25 -08:00
|
|
|
element.value = undefined as any;
|
2020-01-03 12:59:06 -08:00
|
|
|
for (let index = 0; index < options.length; index++) {
|
|
|
|
const option = options[index];
|
|
|
|
option.selected = optionsToSelect.some(optionToSelect => {
|
|
|
|
if (optionToSelect instanceof Node)
|
|
|
|
return option === optionToSelect;
|
|
|
|
let matches = true;
|
|
|
|
if (optionToSelect.value !== undefined)
|
|
|
|
matches = matches && optionToSelect.value === option.value;
|
|
|
|
if (optionToSelect.label !== undefined)
|
|
|
|
matches = matches && optionToSelect.label === option.label;
|
|
|
|
if (optionToSelect.index !== undefined)
|
|
|
|
matches = matches && optionToSelect.index === index;
|
|
|
|
return matches;
|
|
|
|
});
|
|
|
|
if (option.selected && !element.multiple)
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
element.dispatchEvent(new Event('input', { 'bubbles': true }));
|
|
|
|
element.dispatchEvent(new Event('change', { 'bubbles': true }));
|
|
|
|
return options.filter(option => option.selected).map(option => option.value);
|
|
|
|
}, ...options);
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
async fill(value: string): Promise<void> {
|
|
|
|
assert(helper.isString(value), 'Value must be string. Found value "' + value + '" of type "' + (typeof value) + '"');
|
2020-02-03 15:50:45 -08:00
|
|
|
const error = await this._evaluateInUtility((node: Node, value: string) => {
|
2020-01-03 12:59:06 -08:00
|
|
|
if (node.nodeType !== Node.ELEMENT_NODE)
|
|
|
|
return 'Node is not of type HTMLElement';
|
|
|
|
const element = node as HTMLElement;
|
|
|
|
if (!element.isConnected)
|
|
|
|
return 'Element is not attached to the DOM';
|
|
|
|
if (!element.ownerDocument || !element.ownerDocument.defaultView)
|
|
|
|
return 'Element does not belong to a window';
|
|
|
|
|
|
|
|
const style = element.ownerDocument.defaultView.getComputedStyle(element);
|
|
|
|
if (!style || style.visibility === 'hidden')
|
|
|
|
return 'Element is hidden';
|
|
|
|
if (!element.offsetParent && element.tagName !== 'BODY')
|
|
|
|
return 'Element is not visible';
|
|
|
|
if (element.nodeName.toLowerCase() === 'input') {
|
|
|
|
const input = element as HTMLInputElement;
|
|
|
|
const type = input.getAttribute('type') || '';
|
2020-02-03 15:50:45 -08:00
|
|
|
const kTextInputTypes = new Set(['', 'email', 'number', 'password', 'search', 'tel', 'text', 'url']);
|
2020-01-03 12:59:06 -08:00
|
|
|
if (!kTextInputTypes.has(type.toLowerCase()))
|
|
|
|
return 'Cannot fill input of type "' + type + '".';
|
2020-02-03 15:50:45 -08:00
|
|
|
if (type.toLowerCase() === 'number') {
|
|
|
|
value = value.trim();
|
|
|
|
if (!value || isNaN(Number(value)))
|
|
|
|
return 'Cannot type text into input[type=number].';
|
|
|
|
}
|
2020-01-03 12:59:06 -08:00
|
|
|
if (input.disabled)
|
|
|
|
return 'Cannot fill a disabled input.';
|
|
|
|
if (input.readOnly)
|
|
|
|
return 'Cannot fill a readonly input.';
|
2020-01-07 13:57:17 -08:00
|
|
|
input.select();
|
2020-01-03 12:59:06 -08:00
|
|
|
input.focus();
|
|
|
|
} else if (element.nodeName.toLowerCase() === 'textarea') {
|
|
|
|
const textarea = element as HTMLTextAreaElement;
|
|
|
|
if (textarea.disabled)
|
|
|
|
return 'Cannot fill a disabled textarea.';
|
|
|
|
if (textarea.readOnly)
|
|
|
|
return 'Cannot fill a readonly textarea.';
|
|
|
|
textarea.selectionStart = 0;
|
|
|
|
textarea.selectionEnd = textarea.value.length;
|
|
|
|
textarea.focus();
|
|
|
|
} else if (element.isContentEditable) {
|
|
|
|
const range = element.ownerDocument.createRange();
|
|
|
|
range.selectNodeContents(element);
|
|
|
|
const selection = element.ownerDocument.defaultView.getSelection();
|
2020-01-13 13:33:25 -08:00
|
|
|
if (!selection)
|
|
|
|
return 'Element belongs to invisible iframe.';
|
2020-01-03 12:59:06 -08:00
|
|
|
selection.removeAllRanges();
|
|
|
|
selection.addRange(range);
|
|
|
|
element.focus();
|
|
|
|
} else {
|
|
|
|
return 'Element is not an <input>, <textarea> or [contenteditable] element.';
|
|
|
|
}
|
|
|
|
return false;
|
2020-02-03 15:50:45 -08:00
|
|
|
}, value);
|
2019-11-27 16:02:31 -08:00
|
|
|
if (error)
|
|
|
|
throw new Error(error);
|
2020-02-05 18:11:33 -08:00
|
|
|
if (value)
|
|
|
|
await this._page.keyboard.sendCharacters(value);
|
|
|
|
else
|
|
|
|
await this._page.keyboard.press('Delete');
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
|
|
|
|
2020-01-03 12:59:06 -08:00
|
|
|
async setInputFiles(...files: (string | types.FilePayload)[]) {
|
2019-12-19 15:19:22 -08:00
|
|
|
const multiple = await this._evaluateInUtility((node: Node) => {
|
2019-12-05 16:26:09 -08:00
|
|
|
if (node.nodeType !== Node.ELEMENT_NODE || (node as Element).tagName !== 'INPUT')
|
|
|
|
throw new Error('Node is not an HTMLInputElement');
|
|
|
|
const input = node as HTMLInputElement;
|
|
|
|
return input.multiple;
|
|
|
|
});
|
2019-11-27 16:02:31 -08:00
|
|
|
assert(multiple || files.length <= 1, 'Non-multiple file input can only accept single file!');
|
2020-01-03 12:59:06 -08:00
|
|
|
const filePayloads = await Promise.all(files.map(async item => {
|
|
|
|
if (typeof item === 'string') {
|
|
|
|
const file: types.FilePayload = {
|
2020-01-07 11:55:24 -08:00
|
|
|
name: platform.basename(item),
|
2020-02-10 10:08:51 -08:00
|
|
|
type: platform.getMimeType(item),
|
2020-01-07 11:55:24 -08:00
|
|
|
data: await platform.readFileAsync(item, 'base64')
|
2020-01-03 12:59:06 -08:00
|
|
|
};
|
|
|
|
return file;
|
|
|
|
}
|
|
|
|
return item;
|
|
|
|
}));
|
2020-01-13 13:33:25 -08:00
|
|
|
await this._page._delegate.setInputFiles(this as any as ElementHandle<HTMLInputElement>, filePayloads);
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
async focus() {
|
2019-12-19 15:19:22 -08:00
|
|
|
const errorMessage = await this._evaluateInUtility((element: Node) => {
|
2020-01-13 13:33:25 -08:00
|
|
|
if (!(element as any)['focus'])
|
2019-12-05 16:26:09 -08:00
|
|
|
return 'Node is not an HTML or SVG element.';
|
|
|
|
(element as HTMLElement|SVGElement).focus();
|
|
|
|
return false;
|
|
|
|
});
|
|
|
|
if (errorMessage)
|
|
|
|
throw new Error(errorMessage);
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
|
|
|
|
2019-12-17 14:30:02 -08:00
|
|
|
async type(text: string, options?: { delay?: number }) {
|
2019-11-27 16:02:31 -08:00
|
|
|
await this.focus();
|
2019-12-12 21:11:52 -08:00
|
|
|
await this._page.keyboard.type(text, options);
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
async press(key: string, options: { delay?: number; text?: string; } | undefined) {
|
|
|
|
await this.focus();
|
2019-12-12 21:11:52 -08:00
|
|
|
await this._page.keyboard.press(key, options);
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
2020-02-04 14:39:11 -08:00
|
|
|
async check() {
|
|
|
|
await this._setChecked(true);
|
|
|
|
}
|
|
|
|
|
|
|
|
async uncheck() {
|
|
|
|
await this._setChecked(false);
|
|
|
|
}
|
|
|
|
|
|
|
|
private async _setChecked(state: boolean) {
|
|
|
|
const isCheckboxChecked = async (): Promise<boolean> => {
|
|
|
|
return this._evaluateInUtility((node: Node) => {
|
|
|
|
if (node.nodeType !== Node.ELEMENT_NODE)
|
|
|
|
throw new Error('Not a checkbox or radio button');
|
|
|
|
|
|
|
|
let element: Element | undefined = node as Element;
|
|
|
|
if (element.getAttribute('role') === 'checkbox')
|
|
|
|
return element.getAttribute('aria-checked') === 'true';
|
|
|
|
|
|
|
|
if (element.nodeName === 'LABEL') {
|
|
|
|
const forId = element.getAttribute('for');
|
|
|
|
if (forId && element.ownerDocument)
|
|
|
|
element = element.ownerDocument.querySelector(`input[id="${forId}"]`) || undefined;
|
|
|
|
else
|
|
|
|
element = element.querySelector('input[type=checkbox],input[type=radio]') || undefined;
|
|
|
|
}
|
|
|
|
if (element && element.nodeName === 'INPUT') {
|
|
|
|
const type = element.getAttribute('type');
|
|
|
|
if (type && (type.toLowerCase() === 'checkbox' || type.toLowerCase() === 'radio'))
|
|
|
|
return (element as HTMLInputElement).checked;
|
|
|
|
}
|
|
|
|
throw new Error('Not a checkbox');
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
if (await isCheckboxChecked() === state)
|
|
|
|
return;
|
|
|
|
await this.click();
|
|
|
|
if (await isCheckboxChecked() !== state)
|
|
|
|
throw new Error('Unable to click checkbox');
|
|
|
|
}
|
2019-11-27 16:02:31 -08:00
|
|
|
|
2019-11-27 16:03:51 -08:00
|
|
|
async boundingBox(): Promise<types.Rect | null> {
|
2019-12-12 21:11:52 -08:00
|
|
|
return this._page._delegate.getBoundingBox(this);
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
|
|
|
|
2020-01-07 11:55:24 -08:00
|
|
|
async screenshot(options?: types.ElementScreenshotOptions): Promise<string | platform.BufferType> {
|
2019-12-12 21:11:52 -08:00
|
|
|
return this._page._screenshotter.screenshotElement(this, options);
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
|
|
|
|
2019-12-17 14:30:02 -08:00
|
|
|
$(selector: string): Promise<ElementHandle | null> {
|
|
|
|
return this._context._$(selector, this);
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
|
|
|
|
2019-12-17 14:30:02 -08:00
|
|
|
$$(selector: string): Promise<ElementHandle<Element>[]> {
|
|
|
|
return this._context._$$(selector, this);
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
|
|
|
|
2019-12-17 14:30:02 -08:00
|
|
|
$eval: types.$Eval = async (selector, pageFunction, ...args) => {
|
|
|
|
const elementHandle = await this._context._$(selector, this);
|
|
|
|
if (!elementHandle)
|
|
|
|
throw new Error(`Error: failed to find element matching selector "${selector}"`);
|
|
|
|
const result = await elementHandle.evaluate(pageFunction, ...args as any);
|
|
|
|
await elementHandle.dispose();
|
|
|
|
return result;
|
2019-12-04 13:11:10 -08:00
|
|
|
}
|
|
|
|
|
2019-12-17 14:30:02 -08:00
|
|
|
$$eval: types.$$Eval = async (selector, pageFunction, ...args) => {
|
|
|
|
const arrayHandle = await this._context._$array(selector, this);
|
|
|
|
const result = await arrayHandle.evaluate(pageFunction, ...args as any);
|
|
|
|
await arrayHandle.dispose();
|
|
|
|
return result;
|
2019-11-27 16:02:31 -08:00
|
|
|
}
|
|
|
|
|
2020-01-06 13:16:56 -08:00
|
|
|
visibleRatio(): Promise<number> {
|
2019-12-19 15:19:22 -08:00
|
|
|
return this._evaluateInUtility(async (node: Node) => {
|
2019-12-05 16:26:09 -08:00
|
|
|
if (node.nodeType !== Node.ELEMENT_NODE)
|
|
|
|
throw new Error('Node is not of type HTMLElement');
|
|
|
|
const element = node as Element;
|
2020-01-06 13:16:56 -08:00
|
|
|
const visibleRatio = await new Promise<number>(resolve => {
|
2019-11-27 16:02:31 -08:00
|
|
|
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(() => {});
|
|
|
|
});
|
2020-01-06 13:16:56 -08:00
|
|
|
return visibleRatio;
|
2019-11-27 16:02:31 -08:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2019-12-03 10:43:13 -08:00
|
|
|
|
|
|
|
function normalizeSelector(selector: string): string {
|
|
|
|
const eqIndex = selector.indexOf('=');
|
2019-12-16 20:49:18 -08:00
|
|
|
if (eqIndex !== -1 && selector.substring(0, eqIndex).trim().match(/^[a-zA-Z_0-9-]+$/))
|
2019-12-03 10:43:13 -08:00
|
|
|
return selector;
|
2020-02-03 14:52:18 -08:00
|
|
|
// If selector starts with '//' or '//' prefixed with multiple opening
|
|
|
|
// parenthesis, consider xpath. @see https://github.com/microsoft/playwright/issues/817
|
|
|
|
if (/^\(*\/\//.test(selector))
|
2019-12-03 10:43:13 -08:00
|
|
|
return 'xpath=' + selector;
|
2019-12-12 09:02:37 -08:00
|
|
|
if (selector.startsWith('"'))
|
2020-01-13 17:39:43 -08:00
|
|
|
return 'text=' + selector;
|
2019-12-03 10:43:13 -08:00
|
|
|
return 'css=' + selector;
|
|
|
|
}
|
|
|
|
|
2019-12-12 21:11:52 -08:00
|
|
|
export type Task = (context: FrameExecutionContext) => Promise<js.JSHandle>;
|
2019-12-03 10:51:41 -08:00
|
|
|
|
2019-12-18 18:11:02 -08:00
|
|
|
export function waitForFunctionTask(selector: string | undefined, pageFunction: Function | string, options: types.WaitForFunctionOptions, ...args: any[]) {
|
2019-12-03 10:51:41 -08:00
|
|
|
const { polling = 'raf' } = options;
|
|
|
|
if (helper.isString(polling))
|
|
|
|
assert(polling === 'raf' || polling === 'mutation', 'Unknown polling option: ' + polling);
|
|
|
|
else if (helper.isNumber(polling))
|
|
|
|
assert(polling > 0, 'Cannot poll with non-positive interval: ' + polling);
|
|
|
|
else
|
|
|
|
throw new Error('Unknown polling options: ' + polling);
|
|
|
|
const predicateBody = helper.isString(pageFunction) ? 'return (' + pageFunction + ')' : 'return (' + pageFunction + ')(...args)';
|
2019-12-18 18:11:02 -08:00
|
|
|
if (selector !== undefined)
|
|
|
|
selector = normalizeSelector(selector);
|
2019-12-03 10:51:41 -08:00
|
|
|
|
2019-12-18 18:11:02 -08:00
|
|
|
return async (context: FrameExecutionContext) => context.evaluateHandle((injected: Injected, selector: string | undefined, predicateBody: string, polling: types.Polling, timeout: number, ...args) => {
|
|
|
|
const innerPredicate = new Function('...args', predicateBody);
|
2019-12-03 10:51:41 -08:00
|
|
|
if (polling === 'raf')
|
2019-12-18 18:11:02 -08:00
|
|
|
return injected.pollRaf(selector, predicate, timeout);
|
2019-12-03 10:51:41 -08:00
|
|
|
if (polling === 'mutation')
|
2019-12-18 18:11:02 -08:00
|
|
|
return injected.pollMutation(selector, predicate, timeout);
|
|
|
|
return injected.pollInterval(selector, polling, predicate, timeout);
|
|
|
|
|
|
|
|
function predicate(element: Element | undefined): any {
|
|
|
|
if (selector === undefined)
|
|
|
|
return innerPredicate(...args);
|
|
|
|
return innerPredicate(element, ...args);
|
|
|
|
}
|
2020-01-13 13:33:25 -08:00
|
|
|
}, await context._injected(), selector, predicateBody, polling, options.timeout || 0, ...args);
|
2019-12-03 10:51:41 -08:00
|
|
|
}
|
|
|
|
|
2020-01-13 13:33:25 -08:00
|
|
|
export function waitForSelectorTask(selector: string, visibility: types.Visibility, timeout: number): Task {
|
2019-12-12 21:11:52 -08:00
|
|
|
return async (context: FrameExecutionContext) => {
|
2019-12-17 14:30:02 -08:00
|
|
|
selector = normalizeSelector(selector);
|
2019-12-18 18:11:02 -08:00
|
|
|
return context.evaluateHandle((injected: Injected, selector: string, visibility: types.Visibility, timeout: number) => {
|
2019-12-14 19:13:22 -08:00
|
|
|
if (visibility !== 'any')
|
2019-12-18 18:11:02 -08:00
|
|
|
return injected.pollRaf(selector, predicate, timeout);
|
|
|
|
return injected.pollMutation(selector, predicate, timeout);
|
2019-12-04 13:11:10 -08:00
|
|
|
|
2019-12-18 18:11:02 -08:00
|
|
|
function predicate(element: Element | undefined): Element | boolean {
|
2019-12-04 13:11:10 -08:00
|
|
|
if (!element)
|
2019-12-14 19:13:22 -08:00
|
|
|
return visibility === 'hidden';
|
|
|
|
if (visibility === 'any')
|
2019-12-04 13:11:10 -08:00
|
|
|
return element;
|
2019-12-14 19:13:22 -08:00
|
|
|
return injected.isVisible(element) === (visibility === 'visible') ? element : false;
|
2019-12-03 10:51:41 -08:00
|
|
|
}
|
2019-12-18 18:11:02 -08:00
|
|
|
}, await context._injected(), selector, visibility, timeout);
|
2019-12-04 13:11:10 -08:00
|
|
|
};
|
2019-12-03 10:43:13 -08:00
|
|
|
}
|
2020-01-03 12:59:06 -08:00
|
|
|
|
|
|
|
export const setFileInputFunction = async (element: HTMLInputElement, payloads: types.FilePayload[]) => {
|
|
|
|
const files = await Promise.all(payloads.map(async (file: types.FilePayload) => {
|
|
|
|
const result = await fetch(`data:${file.type};base64,${file.data}`);
|
2020-02-10 10:08:51 -08:00
|
|
|
return new File([await result.blob()], file.name, {type: file.type});
|
2020-01-03 12:59:06 -08:00
|
|
|
}));
|
|
|
|
const dt = new DataTransfer();
|
|
|
|
for (const file of files)
|
|
|
|
dt.items.add(file);
|
|
|
|
element.files = dt.files;
|
|
|
|
element.dispatchEvent(new Event('input', { 'bubbles': true }));
|
|
|
|
};
|