2019-12-19 16:53:24 -08:00
|
|
|
/**
|
|
|
|
* Copyright 2017 Google Inc. All rights reserved.
|
|
|
|
* Modifications 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 dom from '../dom';
|
2020-01-13 13:33:25 -08:00
|
|
|
import * as js from '../javascript';
|
2019-12-19 16:53:24 -08:00
|
|
|
import * as frames from '../frames';
|
2020-04-20 07:52:26 -07:00
|
|
|
import { helper, RegisteredListener, assert } from '../helper';
|
2019-12-19 16:53:24 -08:00
|
|
|
import * as network from '../network';
|
2020-03-23 21:48:32 -07:00
|
|
|
import { CRSession, CRConnection, CRSessionEvents } from './crConnection';
|
2020-05-19 08:40:45 -07:00
|
|
|
import { CRExecutionContext } from './crExecutionContext';
|
2019-12-19 16:53:24 -08:00
|
|
|
import { CRNetworkManager } from './crNetworkManager';
|
2020-03-03 16:46:06 -08:00
|
|
|
import { Page, Worker, PageBinding } from '../page';
|
2019-12-19 16:53:24 -08:00
|
|
|
import { Protocol } from './protocol';
|
|
|
|
import { Events } from '../events';
|
2019-12-19 17:03:27 -08:00
|
|
|
import { toConsoleMessageLocation, exceptionToError, releaseObject } from './crProtocolHelper';
|
2019-12-19 16:53:24 -08:00
|
|
|
import * as dialog from '../dialog';
|
|
|
|
import { PageDelegate } from '../page';
|
|
|
|
import { RawMouseImpl, RawKeyboardImpl } from './crInput';
|
2020-01-03 11:15:43 -08:00
|
|
|
import { getAccessibilityTree } from './crAccessibility';
|
2020-01-07 12:59:01 -08:00
|
|
|
import { CRCoverage } from './crCoverage';
|
2020-01-07 13:57:37 -08:00
|
|
|
import { CRPDF } from './crPdf';
|
2020-03-23 21:48:32 -07:00
|
|
|
import { CRBrowserContext } from './crBrowser';
|
2019-12-19 16:53:24 -08:00
|
|
|
import * as types from '../types';
|
|
|
|
import { ConsoleMessage } from '../console';
|
2020-04-18 18:29:31 -07:00
|
|
|
import { NotConnectedError } from '../errors';
|
2020-04-20 07:52:26 -07:00
|
|
|
import { logError } from '../logger';
|
2019-12-19 16:53:24 -08:00
|
|
|
|
2020-04-23 10:38:58 -07:00
|
|
|
|
2019-12-19 16:53:24 -08:00
|
|
|
const UTILITY_WORLD_NAME = '__playwright_utility_world__';
|
|
|
|
|
2019-12-23 11:39:57 -08:00
|
|
|
export class CRPage implements PageDelegate {
|
2020-04-06 15:09:43 -07:00
|
|
|
readonly _mainFrameSession: FrameSession;
|
|
|
|
readonly _sessions = new Map<Protocol.Target.TargetID, FrameSession>();
|
2020-03-23 21:48:32 -07:00
|
|
|
readonly _page: Page;
|
2020-03-17 22:07:20 -07:00
|
|
|
readonly rawMouse: RawMouseImpl;
|
|
|
|
readonly rawKeyboard: RawKeyboardImpl;
|
2020-03-23 21:48:32 -07:00
|
|
|
readonly _targetId: string;
|
2020-04-29 18:36:24 -07:00
|
|
|
readonly _opener: CRPage | null;
|
2020-03-17 22:07:20 -07:00
|
|
|
private readonly _pdf: CRPDF;
|
|
|
|
private readonly _coverage: CRCoverage;
|
2020-03-23 21:48:32 -07:00
|
|
|
readonly _browserContext: CRBrowserContext;
|
|
|
|
private readonly _pagePromise: Promise<Page | Error>;
|
|
|
|
_initializedPage: Page | null = null;
|
2019-12-19 16:53:24 -08:00
|
|
|
|
2020-05-22 15:56:37 -07:00
|
|
|
// Holds window features for the next popup being opened via window.open,
|
|
|
|
// until the popup target arrives. This could be racy if two oopifs
|
|
|
|
// simultaneously call window.open with window features: the order
|
|
|
|
// of their Page.windowOpen events is not guaranteed to match the order
|
|
|
|
// of new popup targets.
|
|
|
|
readonly _nextWindowOpenPopupFeatures: string[][] = [];
|
|
|
|
|
2020-04-23 10:38:58 -07:00
|
|
|
constructor(client: CRSession, targetId: string, browserContext: CRBrowserContext, opener: CRPage | null, hasUIWindow: boolean) {
|
2020-03-23 21:48:32 -07:00
|
|
|
this._targetId = targetId;
|
|
|
|
this._opener = opener;
|
2019-12-19 16:53:24 -08:00
|
|
|
this.rawKeyboard = new RawKeyboardImpl(client);
|
|
|
|
this.rawMouse = new RawMouseImpl(client);
|
2020-01-07 13:57:37 -08:00
|
|
|
this._pdf = new CRPDF(client);
|
2020-04-20 07:52:26 -07:00
|
|
|
this._coverage = new CRCoverage(client, browserContext);
|
2020-02-27 16:18:33 -08:00
|
|
|
this._browserContext = browserContext;
|
2020-01-07 13:57:37 -08:00
|
|
|
this._page = new Page(this, browserContext);
|
2020-05-18 17:13:51 -07:00
|
|
|
this._mainFrameSession = new FrameSession(this, client, targetId, null);
|
2020-04-06 15:09:43 -07:00
|
|
|
this._sessions.set(targetId, this._mainFrameSession);
|
2020-03-23 21:48:32 -07:00
|
|
|
client.once(CRSessionEvents.Disconnected, () => this._page._didDisconnect());
|
2020-05-22 15:56:37 -07:00
|
|
|
if (opener && browserContext._options.viewport !== null) {
|
|
|
|
const features = opener._nextWindowOpenPopupFeatures.shift() || [];
|
|
|
|
const viewportSize = helper.getViewportSizeFromWindowFeatures(features);
|
|
|
|
if (viewportSize)
|
|
|
|
this._page._state.viewportSize = viewportSize;
|
|
|
|
}
|
2020-04-23 10:38:58 -07:00
|
|
|
this._pagePromise = this._mainFrameSession._initialize(hasUIWindow).then(() => this._initializedPage = this._page).catch(e => e);
|
2020-04-06 15:09:43 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
private async _forAllFrameSessions(cb: (frame: FrameSession) => Promise<any>) {
|
|
|
|
await Promise.all(Array.from(this._sessions.values()).map(frame => cb(frame)));
|
|
|
|
}
|
|
|
|
|
2020-05-18 17:13:51 -07:00
|
|
|
_sessionForFrame(frame: frames.Frame): FrameSession {
|
2020-04-06 15:09:43 -07:00
|
|
|
// Frame id equals target id.
|
|
|
|
while (!this._sessions.has(frame._id)) {
|
|
|
|
const parent = frame.parentFrame();
|
|
|
|
if (!parent)
|
|
|
|
throw new Error(`Frame has been detached.`);
|
|
|
|
frame = parent;
|
|
|
|
}
|
|
|
|
return this._sessions.get(frame._id)!;
|
|
|
|
}
|
|
|
|
|
|
|
|
private _sessionForHandle(handle: dom.ElementHandle): FrameSession {
|
|
|
|
const frame = handle._context.frame;
|
|
|
|
return this._sessionForFrame(frame);
|
|
|
|
}
|
|
|
|
|
|
|
|
addFrameSession(targetId: Protocol.Target.TargetID, session: CRSession) {
|
|
|
|
// Frame id equals target id.
|
|
|
|
const frame = this._page._frameManager.frame(targetId);
|
|
|
|
assert(frame);
|
2020-05-18 17:13:51 -07:00
|
|
|
const parentSession = this._sessionForFrame(frame);
|
2020-04-06 15:09:43 -07:00
|
|
|
this._page._frameManager.removeChildFramesRecursively(frame);
|
2020-05-18 17:13:51 -07:00
|
|
|
const frameSession = new FrameSession(this, session, targetId, parentSession);
|
2020-04-06 15:09:43 -07:00
|
|
|
this._sessions.set(targetId, frameSession);
|
2020-04-23 10:38:58 -07:00
|
|
|
frameSession._initialize(false).catch(e => e);
|
2020-04-06 15:09:43 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
removeFrameSession(targetId: Protocol.Target.TargetID) {
|
|
|
|
const frameSession = this._sessions.get(targetId);
|
|
|
|
if (!frameSession)
|
|
|
|
return;
|
|
|
|
// Frame id equals target id.
|
|
|
|
const frame = this._page._frameManager.frame(targetId);
|
2020-04-14 19:01:01 -07:00
|
|
|
if (frame)
|
|
|
|
this._page._frameManager.removeChildFramesRecursively(frame);
|
2020-04-06 15:09:43 -07:00
|
|
|
frameSession.dispose();
|
|
|
|
this._sessions.delete(targetId);
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
2020-03-23 21:48:32 -07:00
|
|
|
async pageOrError(): Promise<Page | Error> {
|
|
|
|
return this._pagePromise;
|
|
|
|
}
|
|
|
|
|
2020-04-06 15:09:43 -07:00
|
|
|
didClose() {
|
|
|
|
for (const session of this._sessions.values())
|
|
|
|
session.dispose();
|
|
|
|
this._page._didClose();
|
|
|
|
}
|
|
|
|
|
|
|
|
async navigateFrame(frame: frames.Frame, url: string, referrer: string | undefined): Promise<frames.GotoResult> {
|
|
|
|
return this._sessionForFrame(frame)._navigate(frame, url, referrer);
|
|
|
|
}
|
|
|
|
|
|
|
|
async exposeBinding(binding: PageBinding) {
|
|
|
|
await this._forAllFrameSessions(frame => frame._initBinding(binding));
|
2020-04-20 07:52:26 -07:00
|
|
|
await Promise.all(this._page.frames().map(frame => frame.evaluate(binding.source).catch(logError(this._page))));
|
2020-04-06 15:09:43 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
async updateExtraHTTPHeaders(): Promise<void> {
|
|
|
|
await this._forAllFrameSessions(frame => frame._updateExtraHTTPHeaders());
|
|
|
|
}
|
|
|
|
|
|
|
|
async updateGeolocation(): Promise<void> {
|
|
|
|
await this._forAllFrameSessions(frame => frame._updateGeolocation());
|
|
|
|
}
|
|
|
|
|
|
|
|
async updateOffline(): Promise<void> {
|
|
|
|
await this._forAllFrameSessions(frame => frame._updateOffline());
|
|
|
|
}
|
|
|
|
|
|
|
|
async updateHttpCredentials(): Promise<void> {
|
|
|
|
await this._forAllFrameSessions(frame => frame._updateHttpCredentials());
|
|
|
|
}
|
|
|
|
|
|
|
|
async setViewportSize(viewportSize: types.Size): Promise<void> {
|
|
|
|
assert(this._page._state.viewportSize === viewportSize);
|
|
|
|
await this._mainFrameSession._updateViewport();
|
|
|
|
}
|
|
|
|
|
2020-04-06 19:49:33 -07:00
|
|
|
async updateEmulateMedia(): Promise<void> {
|
|
|
|
await this._forAllFrameSessions(frame => frame._updateEmulateMedia());
|
2020-04-06 15:09:43 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
async updateRequestInterception(): Promise<void> {
|
|
|
|
await this._forAllFrameSessions(frame => frame._updateRequestInterception());
|
|
|
|
}
|
|
|
|
|
|
|
|
async setFileChooserIntercepted(enabled: boolean) {
|
|
|
|
await this._forAllFrameSessions(frame => frame._setFileChooserIntercepted(enabled));
|
|
|
|
}
|
|
|
|
|
|
|
|
async opener(): Promise<Page | null> {
|
|
|
|
if (!this._opener)
|
|
|
|
return null;
|
|
|
|
const openerPage = await this._opener.pageOrError();
|
|
|
|
if (openerPage instanceof Page && !openerPage.isClosed())
|
|
|
|
return openerPage;
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
async reload(): Promise<void> {
|
|
|
|
await this._mainFrameSession._client.send('Page.reload');
|
|
|
|
}
|
|
|
|
|
|
|
|
private async _go(delta: number): Promise<boolean> {
|
|
|
|
const history = await this._mainFrameSession._client.send('Page.getNavigationHistory');
|
|
|
|
const entry = history.entries[history.currentIndex + delta];
|
|
|
|
if (!entry)
|
|
|
|
return false;
|
|
|
|
await this._mainFrameSession._client.send('Page.navigateToHistoryEntry', { entryId: entry.id });
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
goBack(): Promise<boolean> {
|
|
|
|
return this._go(-1);
|
|
|
|
}
|
|
|
|
|
|
|
|
goForward(): Promise<boolean> {
|
|
|
|
return this._go(+1);
|
|
|
|
}
|
|
|
|
|
|
|
|
async evaluateOnNewDocument(source: string): Promise<void> {
|
|
|
|
await this._forAllFrameSessions(frame => frame._evaluateOnNewDocument(source));
|
|
|
|
}
|
|
|
|
|
|
|
|
async closePage(runBeforeUnload: boolean): Promise<void> {
|
|
|
|
if (runBeforeUnload)
|
|
|
|
await this._mainFrameSession._client.send('Page.close');
|
|
|
|
else
|
|
|
|
await this._browserContext._browser._closePage(this);
|
|
|
|
}
|
|
|
|
|
|
|
|
canScreenshotOutsideViewport(): boolean {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
async setBackgroundColor(color?: { r: number; g: number; b: number; a: number; }): Promise<void> {
|
|
|
|
await this._mainFrameSession._client.send('Emulation.setDefaultBackgroundColorOverride', { color });
|
|
|
|
}
|
|
|
|
|
|
|
|
async takeScreenshot(format: 'png' | 'jpeg', documentRect: types.Rect | undefined, viewportRect: types.Rect | undefined, quality: number | undefined): Promise<Buffer> {
|
|
|
|
const { visualViewport } = await this._mainFrameSession._client.send('Page.getLayoutMetrics');
|
|
|
|
if (!documentRect) {
|
|
|
|
documentRect = {
|
|
|
|
x: visualViewport.pageX + viewportRect!.x,
|
|
|
|
y: visualViewport.pageY + viewportRect!.y,
|
|
|
|
...helper.enclosingIntSize({
|
|
|
|
width: viewportRect!.width / visualViewport.scale,
|
|
|
|
height: viewportRect!.height / visualViewport.scale,
|
|
|
|
})
|
|
|
|
};
|
|
|
|
}
|
|
|
|
await this._mainFrameSession._client.send('Page.bringToFront', {});
|
|
|
|
// When taking screenshots with documentRect (based on the page content, not viewport),
|
|
|
|
// ignore current page scale.
|
|
|
|
const clip = { ...documentRect, scale: viewportRect ? visualViewport.scale : 1 };
|
|
|
|
const result = await this._mainFrameSession._client.send('Page.captureScreenshot', { format, quality, clip });
|
|
|
|
return Buffer.from(result.data, 'base64');
|
|
|
|
}
|
|
|
|
|
|
|
|
async resetViewport(): Promise<void> {
|
|
|
|
await this._mainFrameSession._client.send('Emulation.setDeviceMetricsOverride', { mobile: false, width: 0, height: 0, deviceScaleFactor: 0 });
|
|
|
|
}
|
|
|
|
|
|
|
|
async getContentFrame(handle: dom.ElementHandle): Promise<frames.Frame | null> {
|
|
|
|
return this._sessionForHandle(handle)._getContentFrame(handle);
|
|
|
|
}
|
|
|
|
|
|
|
|
async getOwnerFrame(handle: dom.ElementHandle): Promise<string | null> {
|
|
|
|
return this._sessionForHandle(handle)._getOwnerFrame(handle);
|
|
|
|
}
|
|
|
|
|
|
|
|
isElementHandle(remoteObject: any): boolean {
|
|
|
|
return (remoteObject as Protocol.Runtime.RemoteObject).subtype === 'node';
|
|
|
|
}
|
|
|
|
|
|
|
|
async getBoundingBox(handle: dom.ElementHandle): Promise<types.Rect | null> {
|
|
|
|
return this._sessionForHandle(handle)._getBoundingBox(handle);
|
|
|
|
}
|
|
|
|
|
2020-05-22 11:15:57 -07:00
|
|
|
async scrollRectIntoViewIfNeeded(handle: dom.ElementHandle, rect?: types.Rect): Promise<'success' | 'invisible'> {
|
2020-04-06 15:09:43 -07:00
|
|
|
return this._sessionForHandle(handle)._scrollRectIntoViewIfNeeded(handle, rect);
|
|
|
|
}
|
|
|
|
|
2020-04-29 11:05:23 -07:00
|
|
|
async setActivityPaused(paused: boolean): Promise<void> {
|
|
|
|
await this._forAllFrameSessions(frame => frame._setActivityPaused(paused));
|
|
|
|
}
|
|
|
|
|
2020-05-04 16:30:19 -07:00
|
|
|
rafCountForStablePosition(): number {
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2020-04-06 15:09:43 -07:00
|
|
|
async getContentQuads(handle: dom.ElementHandle): Promise<types.Quad[] | null> {
|
|
|
|
return this._sessionForHandle(handle)._getContentQuads(handle);
|
|
|
|
}
|
|
|
|
|
|
|
|
async layoutViewport(): Promise<{ width: number, height: number }> {
|
|
|
|
const layoutMetrics = await this._mainFrameSession._client.send('Page.getLayoutMetrics');
|
|
|
|
return { width: layoutMetrics.layoutViewport.clientWidth, height: layoutMetrics.layoutViewport.clientHeight };
|
|
|
|
}
|
|
|
|
|
|
|
|
async setInputFiles(handle: dom.ElementHandle<HTMLInputElement>, files: types.FilePayload[]): Promise<void> {
|
2020-04-16 10:25:28 -07:00
|
|
|
await handle._evaluateInUtility(({ injected, node }, files) =>
|
|
|
|
injected.setInputFiles(node, files), dom.toFileTransferPayload(files));
|
2020-04-06 15:09:43 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
async adoptElementHandle<T extends Node>(handle: dom.ElementHandle<T>, to: dom.FrameExecutionContext): Promise<dom.ElementHandle<T>> {
|
|
|
|
return this._sessionForHandle(handle)._adoptElementHandle<T>(handle, to);
|
|
|
|
}
|
|
|
|
|
|
|
|
async getAccessibilityTree(needle?: dom.ElementHandle) {
|
|
|
|
return getAccessibilityTree(this._mainFrameSession._client, needle);
|
|
|
|
}
|
|
|
|
|
|
|
|
async inputActionEpilogue(): Promise<void> {
|
|
|
|
await this._mainFrameSession._client.send('Page.enable').catch(e => {});
|
|
|
|
}
|
|
|
|
|
|
|
|
async pdf(options?: types.PDFOptions): Promise<Buffer> {
|
|
|
|
return this._pdf.generate(options);
|
|
|
|
}
|
|
|
|
|
|
|
|
coverage(): CRCoverage {
|
|
|
|
return this._coverage;
|
|
|
|
}
|
|
|
|
|
|
|
|
async getFrameElement(frame: frames.Frame): Promise<dom.ElementHandle> {
|
|
|
|
let parent = frame.parentFrame();
|
|
|
|
if (!parent)
|
|
|
|
throw new Error('Frame has been detached.');
|
|
|
|
const parentSession = this._sessionForFrame(parent);
|
|
|
|
const { backendNodeId } = await parentSession._client.send('DOM.getFrameOwner', { frameId: frame._id }).catch(e => {
|
|
|
|
if (e instanceof Error && e.message.includes('Frame with the given id was not found.'))
|
|
|
|
e.message = 'Frame has been detached.';
|
|
|
|
throw e;
|
|
|
|
});
|
|
|
|
parent = frame.parentFrame();
|
|
|
|
if (!parent)
|
|
|
|
throw new Error('Frame has been detached.');
|
|
|
|
return parentSession._adoptBackendNodeId(backendNodeId, await parent._mainContext());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class FrameSession {
|
|
|
|
readonly _client: CRSession;
|
|
|
|
readonly _crPage: CRPage;
|
|
|
|
readonly _page: Page;
|
|
|
|
readonly _networkManager: CRNetworkManager;
|
|
|
|
private readonly _contextIdToContext = new Map<number, dom.FrameExecutionContext>();
|
|
|
|
private _eventListeners: RegisteredListener[] = [];
|
|
|
|
readonly _targetId: string;
|
|
|
|
private _firstNonInitialNavigationCommittedPromise: Promise<void>;
|
2020-04-16 13:09:24 -07:00
|
|
|
private _firstNonInitialNavigationCommittedFulfill = () => {};
|
|
|
|
private _firstNonInitialNavigationCommittedReject = (e: Error) => {};
|
2020-04-23 10:38:58 -07:00
|
|
|
private _windowId: number | undefined;
|
2020-04-06 15:09:43 -07:00
|
|
|
|
2020-05-18 17:13:51 -07:00
|
|
|
constructor(crPage: CRPage, client: CRSession, targetId: string, parentSession: FrameSession | null) {
|
2020-04-06 15:09:43 -07:00
|
|
|
this._client = client;
|
|
|
|
this._crPage = crPage;
|
|
|
|
this._page = crPage._page;
|
|
|
|
this._targetId = targetId;
|
2020-05-18 17:13:51 -07:00
|
|
|
this._networkManager = new CRNetworkManager(client, this._page, parentSession ? parentSession._networkManager : null);
|
2020-04-16 13:09:24 -07:00
|
|
|
this._firstNonInitialNavigationCommittedPromise = new Promise((f, r) => {
|
|
|
|
this._firstNonInitialNavigationCommittedFulfill = f;
|
|
|
|
this._firstNonInitialNavigationCommittedReject = r;
|
|
|
|
});
|
|
|
|
client.once(CRSessionEvents.Disconnected, () => {
|
|
|
|
this._firstNonInitialNavigationCommittedReject(new Error('Page closed'));
|
|
|
|
});
|
2020-04-06 15:09:43 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
private _isMainFrame(): boolean {
|
|
|
|
return this._targetId === this._crPage._targetId;
|
|
|
|
}
|
|
|
|
|
|
|
|
private _addSessionListeners() {
|
|
|
|
this._eventListeners = [
|
|
|
|
helper.addEventListener(this._client, 'Inspector.targetCrashed', event => this._onTargetCrashed()),
|
|
|
|
helper.addEventListener(this._client, 'Log.entryAdded', event => this._onLogEntryAdded(event)),
|
|
|
|
helper.addEventListener(this._client, 'Page.fileChooserOpened', event => this._onFileChooserOpened(event)),
|
|
|
|
helper.addEventListener(this._client, 'Page.frameAttached', event => this._onFrameAttached(event.frameId, event.parentFrameId)),
|
|
|
|
helper.addEventListener(this._client, 'Page.frameDetached', event => this._onFrameDetached(event.frameId)),
|
|
|
|
helper.addEventListener(this._client, 'Page.frameNavigated', event => this._onFrameNavigated(event.frame, false)),
|
|
|
|
helper.addEventListener(this._client, 'Page.frameRequestedNavigation', event => this._onFrameRequestedNavigation(event)),
|
|
|
|
helper.addEventListener(this._client, 'Page.frameStoppedLoading', event => this._onFrameStoppedLoading(event.frameId)),
|
|
|
|
helper.addEventListener(this._client, 'Page.javascriptDialogOpening', event => this._onDialog(event)),
|
|
|
|
helper.addEventListener(this._client, 'Page.navigatedWithinDocument', event => this._onFrameNavigatedWithinDocument(event.frameId, event.url)),
|
|
|
|
helper.addEventListener(this._client, 'Page.downloadWillBegin', event => this._onDownloadWillBegin(event)),
|
|
|
|
helper.addEventListener(this._client, 'Page.downloadProgress', event => this._onDownloadProgress(event)),
|
|
|
|
helper.addEventListener(this._client, 'Runtime.bindingCalled', event => this._onBindingCalled(event)),
|
|
|
|
helper.addEventListener(this._client, 'Runtime.consoleAPICalled', event => this._onConsoleAPI(event)),
|
|
|
|
helper.addEventListener(this._client, 'Runtime.exceptionThrown', exception => this._handleException(exception.exceptionDetails)),
|
|
|
|
helper.addEventListener(this._client, 'Runtime.executionContextCreated', event => this._onExecutionContextCreated(event.context)),
|
|
|
|
helper.addEventListener(this._client, 'Runtime.executionContextDestroyed', event => this._onExecutionContextDestroyed(event.executionContextId)),
|
|
|
|
helper.addEventListener(this._client, 'Runtime.executionContextsCleared', event => this._onExecutionContextsCleared()),
|
|
|
|
helper.addEventListener(this._client, 'Target.attachedToTarget', event => this._onAttachedToTarget(event)),
|
|
|
|
helper.addEventListener(this._client, 'Target.detachedFromTarget', event => this._onDetachedFromTarget(event)),
|
2020-05-22 15:56:37 -07:00
|
|
|
helper.addEventListener(this._client, 'Page.windowOpen', event => this._onWindowOpen(event)),
|
2020-04-06 15:09:43 -07:00
|
|
|
];
|
|
|
|
}
|
|
|
|
|
2020-04-23 10:38:58 -07:00
|
|
|
async _initialize(hasUIWindow: boolean) {
|
2020-05-11 14:42:13 -07:00
|
|
|
if (hasUIWindow && this._crPage._browserContext._options.viewport !== null) {
|
2020-04-23 10:38:58 -07:00
|
|
|
const { windowId } = await this._client.send('Browser.getWindowForTarget');
|
|
|
|
this._windowId = windowId;
|
|
|
|
}
|
2020-03-23 13:50:04 -07:00
|
|
|
let lifecycleEventsEnabled: Promise<any>;
|
2020-04-06 15:09:43 -07:00
|
|
|
if (!this._isMainFrame())
|
|
|
|
this._addSessionListeners();
|
2020-01-02 15:06:28 -08:00
|
|
|
const promises: Promise<any>[] = [
|
2020-03-05 10:45:32 -08:00
|
|
|
this._client.send('Page.enable'),
|
|
|
|
this._client.send('Page.getFrameTree').then(({frameTree}) => {
|
2020-04-06 15:09:43 -07:00
|
|
|
if (this._isMainFrame()) {
|
|
|
|
this._handleFrameTree(frameTree);
|
|
|
|
this._addSessionListeners();
|
|
|
|
}
|
|
|
|
const localFrames = this._isMainFrame() ? this._page.frames() : [ this._page._frameManager.frame(this._targetId)! ];
|
|
|
|
for (const frame of localFrames) {
|
2020-03-10 16:19:01 -07:00
|
|
|
// Note: frames might be removed before we send these.
|
|
|
|
this._client.send('Page.createIsolatedWorld', {
|
|
|
|
frameId: frame._id,
|
|
|
|
grantUniveralAccess: true,
|
|
|
|
worldName: UTILITY_WORLD_NAME,
|
2020-04-20 07:52:26 -07:00
|
|
|
}).catch(logError(this._page));
|
2020-04-06 15:09:43 -07:00
|
|
|
for (const binding of this._crPage._browserContext._pageBindings.values())
|
2020-04-20 07:52:26 -07:00
|
|
|
frame.evaluate(binding.source).catch(logError(this._page));
|
2020-03-10 16:19:01 -07:00
|
|
|
}
|
2020-04-06 15:09:43 -07:00
|
|
|
const isInitialEmptyPage = this._isMainFrame() && this._page.mainFrame().url() === ':';
|
2020-03-23 13:50:04 -07:00
|
|
|
if (isInitialEmptyPage) {
|
|
|
|
// Ignore lifecycle events for the initial empty page. It is never the final page
|
|
|
|
// hence we are going to get more lifecycle updates after the actual navigation has
|
|
|
|
// started (even if the target url is about:blank).
|
|
|
|
lifecycleEventsEnabled.then(() => {
|
|
|
|
this._eventListeners.push(helper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));
|
|
|
|
});
|
|
|
|
} else {
|
2020-04-16 13:09:24 -07:00
|
|
|
this._firstNonInitialNavigationCommittedFulfill();
|
2020-03-23 13:50:04 -07:00
|
|
|
this._eventListeners.push(helper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));
|
|
|
|
}
|
2020-03-05 10:45:32 -08:00
|
|
|
}),
|
2019-12-19 16:53:24 -08:00
|
|
|
this._client.send('Log.enable', {}),
|
2020-03-23 13:50:04 -07:00
|
|
|
lifecycleEventsEnabled = this._client.send('Page.setLifecycleEventsEnabled', { enabled: true }),
|
2020-03-10 10:06:17 -07:00
|
|
|
this._client.send('Runtime.enable', {}),
|
|
|
|
this._client.send('Page.addScriptToEvaluateOnNewDocument', {
|
2020-05-19 08:40:45 -07:00
|
|
|
source: js.generateSourceUrl(),
|
2020-03-10 10:06:17 -07:00
|
|
|
worldName: UTILITY_WORLD_NAME,
|
|
|
|
}),
|
2019-12-19 16:53:24 -08:00
|
|
|
this._networkManager.initialize(),
|
2020-02-04 19:36:46 -08:00
|
|
|
this._client.send('Target.setAutoAttach', { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }),
|
2020-02-13 11:29:13 -08:00
|
|
|
this._client.send('Emulation.setFocusEmulationEnabled', { enabled: true }),
|
2020-01-02 15:06:28 -08:00
|
|
|
];
|
2020-04-06 15:09:43 -07:00
|
|
|
const options = this._crPage._browserContext._options;
|
2020-01-02 15:06:28 -08:00
|
|
|
if (options.bypassCSP)
|
|
|
|
promises.push(this._client.send('Page.setBypassCSP', { enabled: true }));
|
|
|
|
if (options.ignoreHTTPSErrors)
|
|
|
|
promises.push(this._client.send('Security.setIgnoreCertificateErrors', { ignore: true }));
|
2020-05-12 18:31:17 -07:00
|
|
|
if (this._isMainFrame())
|
2020-04-03 15:34:36 -07:00
|
|
|
promises.push(this._updateViewport());
|
|
|
|
if (options.hasTouch)
|
|
|
|
promises.push(this._client.send('Emulation.setTouchEmulationEnabled', { enabled: true }));
|
2020-01-02 15:06:28 -08:00
|
|
|
if (options.javaScriptEnabled === false)
|
|
|
|
promises.push(this._client.send('Emulation.setScriptExecutionDisabled', { value: true }));
|
2020-02-13 13:37:59 -08:00
|
|
|
if (options.userAgent || options.locale)
|
|
|
|
promises.push(this._client.send('Emulation.setUserAgentOverride', { userAgent: options.userAgent || '', acceptLanguage: options.locale }));
|
2020-02-26 11:01:46 -08:00
|
|
|
if (options.locale)
|
2020-03-23 17:23:47 -07:00
|
|
|
promises.push(emulateLocale(this._client, options.locale));
|
2020-01-02 15:06:28 -08:00
|
|
|
if (options.timezoneId)
|
|
|
|
promises.push(emulateTimezone(this._client, options.timezoneId));
|
2020-04-06 15:09:43 -07:00
|
|
|
promises.push(this._updateGeolocation());
|
|
|
|
promises.push(this._updateExtraHTTPHeaders());
|
|
|
|
promises.push(this._updateRequestInterception());
|
|
|
|
promises.push(this._updateOffline());
|
|
|
|
promises.push(this._updateHttpCredentials());
|
2020-04-06 19:49:33 -07:00
|
|
|
promises.push(this._updateEmulateMedia());
|
2020-04-06 15:09:43 -07:00
|
|
|
for (const binding of this._crPage._browserContext._pageBindings.values())
|
2020-03-03 16:46:06 -08:00
|
|
|
promises.push(this._initBinding(binding));
|
2020-04-06 15:09:43 -07:00
|
|
|
for (const source of this._crPage._browserContext._evaluateOnNewDocumentSources)
|
|
|
|
promises.push(this._evaluateOnNewDocument(source));
|
2020-03-05 10:45:32 -08:00
|
|
|
promises.push(this._client.send('Runtime.runIfWaitingForDebugger'));
|
2020-03-23 13:50:04 -07:00
|
|
|
promises.push(this._firstNonInitialNavigationCommittedPromise);
|
2020-01-02 15:06:28 -08:00
|
|
|
await Promise.all(promises);
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
2020-04-06 15:09:43 -07:00
|
|
|
|
|
|
|
dispose() {
|
2019-12-19 16:53:24 -08:00
|
|
|
helper.removeEventListeners(this._eventListeners);
|
|
|
|
this._networkManager.dispose();
|
|
|
|
}
|
|
|
|
|
2020-04-06 15:09:43 -07:00
|
|
|
async _navigate(frame: frames.Frame, url: string, referrer: string | undefined): Promise<frames.GotoResult> {
|
2019-12-19 16:53:24 -08:00
|
|
|
const response = await this._client.send('Page.navigate', { url, referrer, frameId: frame._id });
|
|
|
|
if (response.errorText)
|
|
|
|
throw new Error(`${response.errorText} at ${url}`);
|
2020-02-10 18:35:47 -08:00
|
|
|
return { newDocumentId: response.loaderId };
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
_onLifecycleEvent(event: Protocol.Page.lifecycleEventPayload) {
|
2020-01-27 16:51:52 -08:00
|
|
|
if (event.name === 'load')
|
2019-12-19 16:53:24 -08:00
|
|
|
this._page._frameManager.frameLifecycleEvent(event.frameId, 'load');
|
|
|
|
else if (event.name === 'DOMContentLoaded')
|
|
|
|
this._page._frameManager.frameLifecycleEvent(event.frameId, 'domcontentloaded');
|
|
|
|
}
|
|
|
|
|
|
|
|
_onFrameStoppedLoading(frameId: string) {
|
|
|
|
this._page._frameManager.frameStoppedLoading(frameId);
|
|
|
|
}
|
|
|
|
|
|
|
|
_handleFrameTree(frameTree: Protocol.Page.FrameTree) {
|
2020-01-13 13:33:25 -08:00
|
|
|
this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null);
|
2019-12-19 16:53:24 -08:00
|
|
|
this._onFrameNavigated(frameTree.frame, true);
|
|
|
|
if (!frameTree.childFrames)
|
|
|
|
return;
|
|
|
|
|
|
|
|
for (const child of frameTree.childFrames)
|
|
|
|
this._handleFrameTree(child);
|
|
|
|
}
|
|
|
|
|
|
|
|
_onFrameAttached(frameId: string, parentFrameId: string | null) {
|
2020-04-06 15:09:43 -07:00
|
|
|
if (this._crPage._sessions.has(frameId) && frameId !== this._targetId) {
|
|
|
|
// This is a remote -> local frame transition.
|
|
|
|
const frame = this._page._frameManager.frame(frameId)!;
|
|
|
|
this._page._frameManager.removeChildFramesRecursively(frame);
|
|
|
|
return;
|
|
|
|
}
|
2019-12-19 16:53:24 -08:00
|
|
|
this._page._frameManager.frameAttached(frameId, parentFrameId);
|
|
|
|
}
|
|
|
|
|
|
|
|
_onFrameNavigated(framePayload: Protocol.Page.Frame, initial: boolean) {
|
2020-05-14 17:23:19 -07:00
|
|
|
this._page._frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url + (framePayload.urlFragment || ''), framePayload.name || '', framePayload.loaderId, initial);
|
2020-03-18 17:14:18 -07:00
|
|
|
if (!initial)
|
2020-04-16 13:09:24 -07:00
|
|
|
this._firstNonInitialNavigationCommittedFulfill();
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
2020-03-04 19:15:01 -08:00
|
|
|
_onFrameRequestedNavigation(payload: Protocol.Page.frameRequestedNavigationPayload) {
|
2020-04-30 21:24:03 -07:00
|
|
|
if (payload.disposition === 'currentTab')
|
|
|
|
this._page._frameManager.frameRequestedNavigation(payload.frameId, '');
|
2020-03-04 19:15:01 -08:00
|
|
|
}
|
|
|
|
|
2019-12-19 16:53:24 -08:00
|
|
|
_onFrameNavigatedWithinDocument(frameId: string, url: string) {
|
|
|
|
this._page._frameManager.frameCommittedSameDocumentNavigation(frameId, url);
|
|
|
|
}
|
|
|
|
|
|
|
|
_onFrameDetached(frameId: string) {
|
2020-04-06 15:09:43 -07:00
|
|
|
if (this._crPage._sessions.has(frameId)) {
|
|
|
|
// This is a local -> remote frame transtion.
|
|
|
|
// We already got a new target and handled frame reattach - nothing to do here.
|
|
|
|
return;
|
|
|
|
}
|
2019-12-19 16:53:24 -08:00
|
|
|
this._page._frameManager.frameDetached(frameId);
|
|
|
|
}
|
|
|
|
|
|
|
|
_onExecutionContextCreated(contextPayload: Protocol.Runtime.ExecutionContextDescription) {
|
2020-01-13 13:33:25 -08:00
|
|
|
const frame = contextPayload.auxData ? this._page._frameManager.frame(contextPayload.auxData.frameId) : null;
|
2019-12-19 16:53:24 -08:00
|
|
|
if (!frame)
|
|
|
|
return;
|
|
|
|
const delegate = new CRExecutionContext(this._client, contextPayload);
|
|
|
|
const context = new dom.FrameExecutionContext(delegate, frame);
|
|
|
|
if (contextPayload.auxData && !!contextPayload.auxData.isDefault)
|
|
|
|
frame._contextCreated('main', context);
|
|
|
|
else if (contextPayload.name === UTILITY_WORLD_NAME)
|
|
|
|
frame._contextCreated('utility', context);
|
|
|
|
this._contextIdToContext.set(contextPayload.id, context);
|
|
|
|
}
|
|
|
|
|
|
|
|
_onExecutionContextDestroyed(executionContextId: number) {
|
|
|
|
const context = this._contextIdToContext.get(executionContextId);
|
|
|
|
if (!context)
|
|
|
|
return;
|
|
|
|
this._contextIdToContext.delete(executionContextId);
|
|
|
|
context.frame._contextDestroyed(context);
|
|
|
|
}
|
|
|
|
|
|
|
|
_onExecutionContextsCleared() {
|
|
|
|
for (const contextId of Array.from(this._contextIdToContext.keys()))
|
|
|
|
this._onExecutionContextDestroyed(contextId);
|
|
|
|
}
|
|
|
|
|
2020-01-21 10:41:04 -08:00
|
|
|
_onAttachedToTarget(event: Protocol.Target.attachedToTargetPayload) {
|
2020-02-04 19:36:46 -08:00
|
|
|
const session = CRConnection.fromSession(this._client).session(event.sessionId)!;
|
2020-04-06 15:09:43 -07:00
|
|
|
|
|
|
|
if (event.targetInfo.type === 'iframe') {
|
|
|
|
this._crPage.addFrameSession(event.targetInfo.targetId, session);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-02-04 19:36:46 -08:00
|
|
|
if (event.targetInfo.type !== 'worker') {
|
2020-02-05 16:08:28 -08:00
|
|
|
// Ideally, detaching should resume any target, but there is a bug in the backend.
|
2020-04-20 07:52:26 -07:00
|
|
|
session.send('Runtime.runIfWaitingForDebugger').catch(logError(this._page)).then(() => {
|
|
|
|
this._client.send('Target.detachFromTarget', { sessionId: event.sessionId }).catch(logError(this._page));
|
2020-02-05 16:08:28 -08:00
|
|
|
});
|
2020-01-21 10:41:04 -08:00
|
|
|
return;
|
2020-02-04 19:36:46 -08:00
|
|
|
}
|
2020-04-06 15:09:43 -07:00
|
|
|
|
2020-01-21 10:41:04 -08:00
|
|
|
const url = event.targetInfo.url;
|
2020-04-20 07:52:26 -07:00
|
|
|
const worker = new Worker(this._page, url);
|
2020-01-21 10:41:04 -08:00
|
|
|
this._page._addWorker(event.sessionId, worker);
|
|
|
|
session.once('Runtime.executionContextCreated', async event => {
|
|
|
|
worker._createExecutionContext(new CRExecutionContext(session, event.context));
|
|
|
|
});
|
|
|
|
Promise.all([
|
|
|
|
session.send('Runtime.enable'),
|
|
|
|
session.send('Network.enable'),
|
2020-02-04 19:36:46 -08:00
|
|
|
session.send('Runtime.runIfWaitingForDebugger'),
|
2020-04-20 07:52:26 -07:00
|
|
|
]).catch(logError(this._page)); // This might fail if the target is closed before we initialize.
|
2020-01-21 10:41:04 -08:00
|
|
|
session.on('Runtime.consoleAPICalled', event => {
|
2020-05-15 15:21:49 -07:00
|
|
|
const args = event.args.map(o => worker._existingExecutionContext!.createHandle(o));
|
2020-01-21 10:41:04 -08:00
|
|
|
this._page._addConsoleMessage(event.type, args, toConsoleMessageLocation(event.stackTrace));
|
|
|
|
});
|
|
|
|
session.on('Runtime.exceptionThrown', exception => this._page.emit(Events.Page.PageError, exceptionToError(exception.exceptionDetails)));
|
2020-03-10 11:39:35 -07:00
|
|
|
// TODO: attribute workers to the right frame.
|
2020-04-06 15:09:43 -07:00
|
|
|
this._networkManager.instrumentNetworkEvents(session, this._page._frameManager.frame(this._targetId)!);
|
2020-01-21 10:41:04 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
_onDetachedFromTarget(event: Protocol.Target.detachedFromTargetPayload) {
|
2020-04-06 15:09:43 -07:00
|
|
|
this._crPage.removeFrameSession(event.targetId!);
|
2020-01-21 10:41:04 -08:00
|
|
|
this._page._removeWorker(event.sessionId);
|
|
|
|
}
|
|
|
|
|
2020-05-22 15:56:37 -07:00
|
|
|
_onWindowOpen(event: Protocol.Page.windowOpenPayload) {
|
|
|
|
this._crPage._nextWindowOpenPopupFeatures.push(event.windowFeatures);
|
|
|
|
}
|
|
|
|
|
2019-12-19 16:53:24 -08:00
|
|
|
async _onConsoleAPI(event: Protocol.Runtime.consoleAPICalledPayload) {
|
|
|
|
if (event.executionContextId === 0) {
|
|
|
|
// DevTools protocol stores the last 1000 console messages. These
|
|
|
|
// messages are always reported even for removed execution contexts. In
|
|
|
|
// this case, they are marked with executionContextId = 0 and are
|
|
|
|
// reported upon enabling Runtime agent.
|
|
|
|
//
|
|
|
|
// Ignore these messages since:
|
|
|
|
// - there's no execution context we can use to operate with message
|
|
|
|
// arguments
|
|
|
|
// - these messages are reported before Playwright clients can subscribe
|
|
|
|
// to the 'console'
|
|
|
|
// page event.
|
|
|
|
//
|
|
|
|
// @see https://github.com/GoogleChrome/puppeteer/issues/3865
|
|
|
|
return;
|
|
|
|
}
|
2020-01-13 13:33:25 -08:00
|
|
|
const context = this._contextIdToContext.get(event.executionContextId)!;
|
2020-05-15 15:21:49 -07:00
|
|
|
const values = event.args.map(arg => context.createHandle(arg));
|
2019-12-19 16:53:24 -08:00
|
|
|
this._page._addConsoleMessage(event.type, values, toConsoleMessageLocation(event.stackTrace));
|
|
|
|
}
|
|
|
|
|
2020-03-03 16:46:06 -08:00
|
|
|
async _initBinding(binding: PageBinding) {
|
|
|
|
await Promise.all([
|
|
|
|
this._client.send('Runtime.addBinding', { name: binding.name }),
|
|
|
|
this._client.send('Page.addScriptToEvaluateOnNewDocument', { source: binding.source })
|
|
|
|
]);
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
_onBindingCalled(event: Protocol.Runtime.bindingCalledPayload) {
|
2020-01-13 13:33:25 -08:00
|
|
|
const context = this._contextIdToContext.get(event.executionContextId)!;
|
2019-12-19 16:53:24 -08:00
|
|
|
this._page._onBindingCalled(event.payload, context);
|
|
|
|
}
|
|
|
|
|
2020-02-07 13:36:49 -08:00
|
|
|
_onDialog(event: Protocol.Page.javascriptDialogOpeningPayload) {
|
2019-12-19 16:53:24 -08:00
|
|
|
this._page.emit(Events.Page.Dialog, new dialog.Dialog(
|
2020-02-07 13:38:50 -08:00
|
|
|
event.type,
|
|
|
|
event.message,
|
|
|
|
async (accept: boolean, promptText?: string) => {
|
|
|
|
await this._client.send('Page.handleJavaScriptDialog', { accept, promptText });
|
|
|
|
},
|
|
|
|
event.defaultPrompt));
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
_handleException(exceptionDetails: Protocol.Runtime.ExceptionDetails) {
|
|
|
|
this._page.emit(Events.Page.PageError, exceptionToError(exceptionDetails));
|
|
|
|
}
|
|
|
|
|
2020-04-15 00:04:35 -07:00
|
|
|
async _onTargetCrashed() {
|
|
|
|
this._client._markAsCrashed();
|
2020-01-03 11:10:10 -08:00
|
|
|
this._page._didCrash();
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
_onLogEntryAdded(event: Protocol.Log.entryAddedPayload) {
|
|
|
|
const {level, text, args, source, url, lineNumber} = event.entry;
|
|
|
|
if (args)
|
|
|
|
args.map(arg => releaseObject(this._client, arg));
|
|
|
|
if (source !== 'worker')
|
|
|
|
this._page.emit(Events.Page.Console, new ConsoleMessage(level, text, [], {url, lineNumber}));
|
|
|
|
}
|
|
|
|
|
|
|
|
async _onFileChooserOpened(event: Protocol.Page.fileChooserOpenedPayload) {
|
2020-01-13 13:33:25 -08:00
|
|
|
const frame = this._page._frameManager.frame(event.frameId)!;
|
2019-12-19 16:53:24 -08:00
|
|
|
const utilityContext = await frame._utilityContext();
|
2020-04-06 15:09:43 -07:00
|
|
|
const handle = await this._adoptBackendNodeId(event.backendNodeId, utilityContext);
|
2019-12-19 16:53:24 -08:00
|
|
|
this._page._onFileChooserOpened(handle);
|
|
|
|
}
|
|
|
|
|
2020-04-02 17:56:14 -07:00
|
|
|
_onDownloadWillBegin(payload: Protocol.Page.downloadWillBeginPayload) {
|
2020-04-29 18:36:24 -07:00
|
|
|
let originPage = this._crPage._initializedPage;
|
|
|
|
// If it's a new window download, report it on the opener page.
|
|
|
|
if (!originPage) {
|
|
|
|
// Resume the page creation with an error. The page will automatically close right
|
|
|
|
// after the download begins.
|
|
|
|
this._firstNonInitialNavigationCommittedReject(new Error('Starting new page download'));
|
|
|
|
if (this._crPage._opener)
|
|
|
|
originPage = this._crPage._opener._initializedPage;
|
|
|
|
}
|
|
|
|
if (!originPage)
|
|
|
|
return;
|
2020-05-12 19:23:08 -07:00
|
|
|
this._crPage._browserContext._browser._downloadCreated(originPage, payload.guid, payload.url, payload.suggestedFilename);
|
2020-04-02 17:56:14 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
_onDownloadProgress(payload: Protocol.Page.downloadProgressPayload) {
|
|
|
|
if (payload.state === 'completed')
|
2020-04-06 15:09:43 -07:00
|
|
|
this._crPage._browserContext._browser._downloadFinished(payload.guid, '');
|
2020-04-02 17:56:14 -07:00
|
|
|
if (payload.state === 'canceled')
|
2020-04-06 15:09:43 -07:00
|
|
|
this._crPage._browserContext._browser._downloadFinished(payload.guid, 'canceled');
|
2020-04-02 17:56:14 -07:00
|
|
|
}
|
|
|
|
|
2020-04-06 15:09:43 -07:00
|
|
|
async _updateExtraHTTPHeaders(): Promise<void> {
|
2020-02-26 12:42:20 -08:00
|
|
|
const headers = network.mergeHeaders([
|
2020-04-06 15:09:43 -07:00
|
|
|
this._crPage._browserContext._options.extraHTTPHeaders,
|
2020-02-26 12:42:20 -08:00
|
|
|
this._page._state.extraHTTPHeaders
|
|
|
|
]);
|
2019-12-19 16:53:24 -08:00
|
|
|
await this._client.send('Network.setExtraHTTPHeaders', { headers });
|
|
|
|
}
|
|
|
|
|
2020-04-06 15:09:43 -07:00
|
|
|
async _updateGeolocation(): Promise<void> {
|
|
|
|
const geolocation = this._crPage._browserContext._options.geolocation;
|
|
|
|
await this._client.send('Emulation.setGeolocationOverride', geolocation || {});
|
|
|
|
}
|
|
|
|
|
|
|
|
async _updateOffline(): Promise<void> {
|
|
|
|
const offline = !!this._crPage._browserContext._options.offline;
|
|
|
|
await this._networkManager.setOffline(offline);
|
|
|
|
}
|
|
|
|
|
|
|
|
async _updateHttpCredentials(): Promise<void> {
|
|
|
|
const credentials = this._crPage._browserContext._options.httpCredentials || null;
|
|
|
|
await this._networkManager.authenticate(credentials);
|
2020-02-06 19:02:55 -08:00
|
|
|
}
|
|
|
|
|
2020-04-03 15:34:36 -07:00
|
|
|
async _updateViewport(): Promise<void> {
|
2020-04-06 15:09:43 -07:00
|
|
|
assert(this._isMainFrame());
|
|
|
|
const options = this._crPage._browserContext._options;
|
2020-02-06 19:02:55 -08:00
|
|
|
const viewportSize = this._page._state.viewportSize;
|
2020-05-12 18:31:17 -07:00
|
|
|
if (viewportSize === null)
|
|
|
|
return;
|
|
|
|
const isLandscape = viewportSize.width > viewportSize.height;
|
2020-02-06 19:02:55 -08:00
|
|
|
const promises = [
|
|
|
|
this._client.send('Emulation.setDeviceMetricsOverride', {
|
2020-03-17 18:21:02 -07:00
|
|
|
mobile: !!options.isMobile,
|
2020-05-12 18:31:17 -07:00
|
|
|
width: viewportSize.width,
|
|
|
|
height: viewportSize.height,
|
|
|
|
screenWidth: viewportSize.width,
|
|
|
|
screenHeight: viewportSize.height,
|
2020-03-17 18:21:02 -07:00
|
|
|
deviceScaleFactor: options.deviceScaleFactor || 1,
|
2020-02-06 19:02:55 -08:00
|
|
|
screenOrientation: isLandscape ? { angle: 90, type: 'landscapePrimary' } : { angle: 0, type: 'portraitPrimary' },
|
|
|
|
}),
|
|
|
|
];
|
2020-04-23 10:38:58 -07:00
|
|
|
if (this._windowId) {
|
2020-05-12 18:31:17 -07:00
|
|
|
// TODO: popup windows have their own insets.
|
2020-04-23 10:38:58 -07:00
|
|
|
let insets = { width: 24, height: 88 };
|
|
|
|
if (process.platform === 'win32')
|
|
|
|
insets = { width: 16, height: 88 };
|
|
|
|
else if (process.platform === 'linux')
|
|
|
|
insets = { width: 8, height: 85 };
|
|
|
|
else if (process.platform === 'darwin')
|
|
|
|
insets = { width: 2, height: 80 };
|
|
|
|
|
|
|
|
promises.push(this._client.send('Browser.setWindowBounds', {
|
|
|
|
windowId: this._windowId,
|
2020-05-12 18:31:17 -07:00
|
|
|
bounds: { width: viewportSize.width + insets.width, height: viewportSize.height + insets.height }
|
2020-04-23 10:38:58 -07:00
|
|
|
}));
|
|
|
|
}
|
2020-02-06 19:02:55 -08:00
|
|
|
await Promise.all(promises);
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
2020-04-06 19:49:33 -07:00
|
|
|
async _updateEmulateMedia(): Promise<void> {
|
|
|
|
const colorScheme = this._page._state.colorScheme || this._crPage._browserContext._options.colorScheme || 'light';
|
2020-01-03 12:59:06 -08:00
|
|
|
const features = colorScheme ? [{ name: 'prefers-color-scheme', value: colorScheme }] : [];
|
2020-04-06 19:49:33 -07:00
|
|
|
await this._client.send('Emulation.setEmulatedMedia', { media: this._page._state.mediaType || '', features });
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
2020-04-06 15:09:43 -07:00
|
|
|
async _updateRequestInterception(): Promise<void> {
|
2020-03-09 21:02:54 -07:00
|
|
|
await this._networkManager.setRequestInterception(this._page._needsRequestInterception());
|
2019-12-30 14:05:28 -08:00
|
|
|
}
|
|
|
|
|
2020-04-06 15:09:43 -07:00
|
|
|
async _setFileChooserIntercepted(enabled: boolean) {
|
2020-01-30 17:43:06 -08:00
|
|
|
await this._client.send('Page.setInterceptFileChooserDialog', { enabled }).catch(e => {}); // target can be closed.
|
|
|
|
}
|
|
|
|
|
2020-04-06 15:09:43 -07:00
|
|
|
async _evaluateOnNewDocument(source: string): Promise<void> {
|
2019-12-19 16:53:24 -08:00
|
|
|
await this._client.send('Page.addScriptToEvaluateOnNewDocument', { source });
|
|
|
|
}
|
|
|
|
|
2020-04-06 15:09:43 -07:00
|
|
|
async _getContentFrame(handle: dom.ElementHandle): Promise<frames.Frame | null> {
|
2019-12-19 16:53:24 -08:00
|
|
|
const nodeInfo = await this._client.send('DOM.describeNode', {
|
2020-05-20 15:55:33 -07:00
|
|
|
objectId: handle._remoteObject.objectId
|
2019-12-19 16:53:24 -08:00
|
|
|
});
|
|
|
|
if (!nodeInfo || typeof nodeInfo.node.frameId !== 'string')
|
|
|
|
return null;
|
|
|
|
return this._page._frameManager.frame(nodeInfo.node.frameId);
|
|
|
|
}
|
|
|
|
|
2020-04-06 15:09:43 -07:00
|
|
|
async _getOwnerFrame(handle: dom.ElementHandle): Promise<string | null> {
|
2019-12-19 16:53:24 -08:00
|
|
|
// document.documentElement has frameId of the owner frame.
|
|
|
|
const documentElement = await handle.evaluateHandle(node => {
|
|
|
|
const doc = node as Document;
|
|
|
|
if (doc.documentElement && doc.documentElement.ownerDocument === doc)
|
|
|
|
return doc.documentElement;
|
|
|
|
return node.ownerDocument ? node.ownerDocument.documentElement : null;
|
|
|
|
});
|
|
|
|
if (!documentElement)
|
|
|
|
return null;
|
2020-05-20 15:55:33 -07:00
|
|
|
const remoteObject = documentElement._remoteObject;
|
2019-12-19 16:53:24 -08:00
|
|
|
if (!remoteObject.objectId)
|
|
|
|
return null;
|
|
|
|
const nodeInfo = await this._client.send('DOM.describeNode', {
|
|
|
|
objectId: remoteObject.objectId
|
|
|
|
});
|
2020-01-27 11:43:43 -08:00
|
|
|
const frameId = nodeInfo && typeof nodeInfo.node.frameId === 'string' ?
|
|
|
|
nodeInfo.node.frameId : null;
|
2020-03-04 17:57:35 -08:00
|
|
|
documentElement.dispose();
|
2020-01-27 11:43:43 -08:00
|
|
|
return frameId;
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
2020-04-06 15:09:43 -07:00
|
|
|
async _getBoundingBox(handle: dom.ElementHandle): Promise<types.Rect | null> {
|
2019-12-19 16:53:24 -08:00
|
|
|
const result = await this._client.send('DOM.getBoxModel', {
|
2020-05-20 15:55:33 -07:00
|
|
|
objectId: handle._remoteObject.objectId
|
2020-04-20 07:52:26 -07:00
|
|
|
}).catch(logError(this._page));
|
2019-12-19 16:53:24 -08:00
|
|
|
if (!result)
|
|
|
|
return null;
|
|
|
|
const quad = result.model.border;
|
|
|
|
const x = Math.min(quad[0], quad[2], quad[4], quad[6]);
|
|
|
|
const y = Math.min(quad[1], quad[3], quad[5], quad[7]);
|
|
|
|
const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x;
|
|
|
|
const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y;
|
|
|
|
return {x, y, width, height};
|
|
|
|
}
|
|
|
|
|
2020-05-22 11:15:57 -07:00
|
|
|
async _scrollRectIntoViewIfNeeded(handle: dom.ElementHandle, rect?: types.Rect): Promise<'success' | 'invisible'> {
|
|
|
|
return await this._client.send('DOM.scrollIntoViewIfNeeded', {
|
2020-05-20 15:55:33 -07:00
|
|
|
objectId: handle._remoteObject.objectId,
|
2020-02-11 10:30:09 -08:00
|
|
|
rect,
|
2020-05-22 11:15:57 -07:00
|
|
|
}).then(() => 'success' as const).catch(e => {
|
|
|
|
if (e instanceof Error && e.message.includes('Node does not have a layout object'))
|
|
|
|
return 'invisible';
|
2020-04-18 18:29:31 -07:00
|
|
|
if (e instanceof Error && e.message.includes('Node is detached from document'))
|
|
|
|
throw new NotConnectedError();
|
2020-02-11 10:30:09 -08:00
|
|
|
throw e;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-04-29 11:05:23 -07:00
|
|
|
async _setActivityPaused(paused: boolean): Promise<void> {
|
|
|
|
}
|
|
|
|
|
2020-04-06 15:09:43 -07:00
|
|
|
async _getContentQuads(handle: dom.ElementHandle): Promise<types.Quad[] | null> {
|
2019-12-19 16:53:24 -08:00
|
|
|
const result = await this._client.send('DOM.getContentQuads', {
|
2020-05-20 15:55:33 -07:00
|
|
|
objectId: handle._remoteObject.objectId
|
2020-04-20 07:52:26 -07:00
|
|
|
}).catch(logError(this._page));
|
2019-12-19 16:53:24 -08:00
|
|
|
if (!result)
|
|
|
|
return null;
|
|
|
|
return result.quads.map(quad => [
|
|
|
|
{ x: quad[0], y: quad[1] },
|
|
|
|
{ x: quad[2], y: quad[3] },
|
|
|
|
{ x: quad[4], y: quad[5] },
|
|
|
|
{ x: quad[6], y: quad[7] }
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
2020-04-06 15:09:43 -07:00
|
|
|
async _adoptElementHandle<T extends Node>(handle: dom.ElementHandle<T>, to: dom.FrameExecutionContext): Promise<dom.ElementHandle<T>> {
|
2019-12-19 16:53:24 -08:00
|
|
|
const nodeInfo = await this._client.send('DOM.describeNode', {
|
2020-05-20 15:55:33 -07:00
|
|
|
objectId: handle._remoteObject.objectId,
|
2019-12-19 16:53:24 -08:00
|
|
|
});
|
2020-04-06 15:09:43 -07:00
|
|
|
return this._adoptBackendNodeId(nodeInfo.node.backendNodeId, to) as Promise<dom.ElementHandle<T>>;
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
2020-04-06 15:09:43 -07:00
|
|
|
async _adoptBackendNodeId(backendNodeId: Protocol.DOM.BackendNodeId, to: dom.FrameExecutionContext): Promise<dom.ElementHandle> {
|
2019-12-19 16:53:24 -08:00
|
|
|
const result = await this._client.send('DOM.resolveNode', {
|
|
|
|
backendNodeId,
|
|
|
|
executionContextId: (to._delegate as CRExecutionContext)._contextId,
|
2020-04-20 07:52:26 -07:00
|
|
|
}).catch(logError(this._page));
|
2019-12-19 16:53:24 -08:00
|
|
|
if (!result || result.object.subtype === 'null')
|
|
|
|
throw new Error('Unable to adopt element handle from a different document');
|
2020-05-15 15:21:49 -07:00
|
|
|
return to.createHandle(result.object).asElement()!;
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
2019-12-21 09:03:52 -08:00
|
|
|
}
|
|
|
|
|
2020-03-23 17:23:47 -07:00
|
|
|
async function emulateLocale(session: CRSession, locale: string) {
|
|
|
|
try {
|
|
|
|
await session.send('Emulation.setLocaleOverride', { locale });
|
|
|
|
} catch (exception) {
|
|
|
|
// All pages in the same renderer share locale. All such pages belong to the same
|
|
|
|
// context and if locale is overridden for one of them its value is the same as
|
|
|
|
// we are trying to set so it's not a problem.
|
|
|
|
if (exception.message.includes('Another locale override is already in effect'))
|
|
|
|
return;
|
|
|
|
throw exception;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-02 15:06:28 -08:00
|
|
|
async function emulateTimezone(session: CRSession, timezoneId: string) {
|
|
|
|
try {
|
|
|
|
await session.send('Emulation.setTimezoneOverride', { timezoneId: timezoneId });
|
|
|
|
} catch (exception) {
|
2020-03-23 17:23:47 -07:00
|
|
|
if (exception.message.includes('Timezone override is already in effect'))
|
|
|
|
return;
|
2020-01-02 15:06:28 -08:00
|
|
|
if (exception.message.includes('Invalid timezone'))
|
|
|
|
throw new Error(`Invalid timezone ID: ${timezoneId}`);
|
|
|
|
throw exception;
|
|
|
|
}
|
|
|
|
}
|