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-02-06 19:02:55 -08:00
|
|
|
import { debugError, 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';
|
2019-12-19 16:53:24 -08:00
|
|
|
import { EVALUATION_SCRIPT_URL, CRExecutionContext } from './crExecutionContext';
|
|
|
|
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';
|
|
|
|
|
|
|
|
const UTILITY_WORLD_NAME = '__playwright_utility_world__';
|
|
|
|
|
2019-12-23 11:39:57 -08:00
|
|
|
export class CRPage implements PageDelegate {
|
2020-03-17 22:07:20 -07:00
|
|
|
readonly _client: CRSession;
|
2020-03-23 21:48:32 -07:00
|
|
|
readonly _page: Page;
|
2019-12-19 16:53:24 -08:00
|
|
|
readonly _networkManager: CRNetworkManager;
|
2020-03-17 22:07:20 -07:00
|
|
|
private readonly _contextIdToContext = new Map<number, dom.FrameExecutionContext>();
|
2020-03-03 17:15:43 -08:00
|
|
|
private _eventListeners: RegisteredListener[] = [];
|
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;
|
|
|
|
private 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;
|
2020-03-18 17:14:18 -07:00
|
|
|
private _firstNonInitialNavigationCommittedPromise: Promise<void>;
|
|
|
|
private _firstNonInitialNavigationCommittedCallback = () => {};
|
2020-03-23 21:48:32 -07:00
|
|
|
private readonly _pagePromise: Promise<Page | Error>;
|
|
|
|
_initializedPage: Page | null = null;
|
2019-12-19 16:53:24 -08:00
|
|
|
|
2020-03-23 21:48:32 -07:00
|
|
|
constructor(client: CRSession, targetId: string, browserContext: CRBrowserContext, opener: CRPage | null) {
|
2019-12-19 16:53:24 -08:00
|
|
|
this._client = client;
|
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);
|
|
|
|
this._coverage = new CRCoverage(client);
|
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-01-07 12:59:01 -08:00
|
|
|
this._networkManager = new CRNetworkManager(client, this._page);
|
2020-03-18 17:14:18 -07:00
|
|
|
this._firstNonInitialNavigationCommittedPromise = new Promise(f => this._firstNonInitialNavigationCommittedCallback = f);
|
2020-03-23 21:48:32 -07:00
|
|
|
client.once(CRSessionEvents.Disconnected, () => this._page._didDisconnect());
|
|
|
|
this._pagePromise = this._initialize().then(() => this._initializedPage = this._page).catch(e => e);
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
2020-03-23 21:48:32 -07:00
|
|
|
async pageOrError(): Promise<Page | Error> {
|
|
|
|
return this._pagePromise;
|
|
|
|
}
|
|
|
|
|
|
|
|
private async _initialize() {
|
2020-03-23 13:50:04 -07:00
|
|
|
let lifecycleEventsEnabled: Promise<any>;
|
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}) => {
|
|
|
|
this._handleFrameTree(frameTree);
|
|
|
|
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)),
|
2020-04-02 17:56:14 -07:00
|
|
|
helper.addEventListener(this._client, 'Page.downloadWillBegin', event => this._onDownloadWillBegin(event)),
|
|
|
|
helper.addEventListener(this._client, 'Page.downloadProgress', event => this._onDownloadProgress(event)),
|
2020-03-05 10:45:32 -08:00
|
|
|
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-03-10 16:19:01 -07:00
|
|
|
for (const frame of this._page.frames()) {
|
|
|
|
// Note: frames might be removed before we send these.
|
|
|
|
this._client.send('Page.createIsolatedWorld', {
|
|
|
|
frameId: frame._id,
|
|
|
|
grantUniveralAccess: true,
|
|
|
|
worldName: UTILITY_WORLD_NAME,
|
|
|
|
}).catch(debugError);
|
|
|
|
for (const binding of this._browserContext._pageBindings.values())
|
|
|
|
frame.evaluate(binding.source).catch(debugError);
|
|
|
|
}
|
2020-03-23 13:50:04 -07:00
|
|
|
const isInitialEmptyPage = this._page.mainFrame().url() === ':';
|
|
|
|
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 {
|
|
|
|
this._firstNonInitialNavigationCommittedCallback();
|
|
|
|
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', {
|
|
|
|
source: `//# sourceURL=${EVALUATION_SCRIPT_URL}`,
|
|
|
|
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-03-05 17:22:57 -08:00
|
|
|
const options = this._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 }));
|
|
|
|
if (options.viewport)
|
2020-02-06 19:02:55 -08:00
|
|
|
promises.push(this._updateViewport(true /* updateTouch */));
|
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-01-03 10:14:50 -08:00
|
|
|
if (options.geolocation)
|
|
|
|
promises.push(this._client.send('Emulation.setGeolocationOverride', options.geolocation));
|
2020-02-26 12:42:20 -08:00
|
|
|
promises.push(this.updateExtraHTTPHeaders());
|
2020-03-09 21:02:54 -07:00
|
|
|
promises.push(this.updateRequestInterception());
|
2020-03-04 17:58:12 -08:00
|
|
|
if (options.offline)
|
|
|
|
promises.push(this._networkManager.setOffline(options.offline));
|
2020-03-06 13:50:42 -08:00
|
|
|
if (options.httpCredentials)
|
|
|
|
promises.push(this._networkManager.authenticate(options.httpCredentials));
|
2020-03-03 16:46:06 -08:00
|
|
|
for (const binding of this._browserContext._pageBindings.values())
|
|
|
|
promises.push(this._initBinding(binding));
|
2020-02-27 16:18:33 -08:00
|
|
|
for (const source of this._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
|
|
|
}
|
|
|
|
didClose() {
|
|
|
|
helper.removeEventListeners(this._eventListeners);
|
|
|
|
this._networkManager.dispose();
|
|
|
|
this._page._didClose();
|
|
|
|
}
|
|
|
|
|
|
|
|
async navigateFrame(frame: frames.Frame, url: string, referrer: string | undefined): Promise<frames.GotoResult> {
|
|
|
|
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) {
|
|
|
|
this._page._frameManager.frameAttached(frameId, parentFrameId);
|
|
|
|
}
|
|
|
|
|
|
|
|
_onFrameNavigated(framePayload: Protocol.Page.Frame, initial: boolean) {
|
|
|
|
this._page._frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url, framePayload.name || '', framePayload.loaderId, initial);
|
2020-03-18 17:14:18 -07:00
|
|
|
if (!initial)
|
|
|
|
this._firstNonInitialNavigationCommittedCallback();
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
2020-03-04 19:15:01 -08:00
|
|
|
_onFrameRequestedNavigation(payload: Protocol.Page.frameRequestedNavigationPayload) {
|
|
|
|
this._page._frameManager.frameRequestedNavigation(payload.frameId);
|
|
|
|
}
|
|
|
|
|
2019-12-19 16:53:24 -08:00
|
|
|
_onFrameNavigatedWithinDocument(frameId: string, url: string) {
|
|
|
|
this._page._frameManager.frameCommittedSameDocumentNavigation(frameId, url);
|
|
|
|
}
|
|
|
|
|
|
|
|
_onFrameDetached(frameId: string) {
|
|
|
|
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)!;
|
|
|
|
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.
|
|
|
|
session.send('Runtime.runIfWaitingForDebugger').catch(debugError).then(() => {
|
|
|
|
this._client.send('Target.detachFromTarget', { sessionId: event.sessionId }).catch(debugError);
|
|
|
|
});
|
2020-01-21 10:41:04 -08:00
|
|
|
return;
|
2020-02-04 19:36:46 -08:00
|
|
|
}
|
2020-01-21 10:41:04 -08:00
|
|
|
const url = event.targetInfo.url;
|
|
|
|
const worker = new Worker(url);
|
|
|
|
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-01-21 10:41:04 -08:00
|
|
|
]).catch(debugError); // This might fail if the target is closed before we initialize.
|
|
|
|
session.on('Runtime.consoleAPICalled', event => {
|
|
|
|
const args = event.args.map(o => worker._existingExecutionContext!._createHandle(o));
|
|
|
|
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.
|
|
|
|
this._networkManager.instrumentNetworkEvents(session, this._page.mainFrame());
|
2020-01-21 10:41:04 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
_onDetachedFromTarget(event: Protocol.Target.detachedFromTargetPayload) {
|
|
|
|
this._page._removeWorker(event.sessionId);
|
|
|
|
}
|
|
|
|
|
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)!;
|
2019-12-19 16:53:24 -08:00
|
|
|
const values = event.args.map(arg => context._createHandle(arg));
|
|
|
|
this._page._addConsoleMessage(event.type, values, toConsoleMessageLocation(event.stackTrace));
|
|
|
|
}
|
|
|
|
|
2020-03-03 16:46:06 -08:00
|
|
|
async exposeBinding(binding: PageBinding) {
|
|
|
|
await this._initBinding(binding);
|
|
|
|
await Promise.all(this._page.frames().map(frame => frame.evaluate(binding.source).catch(debugError)));
|
|
|
|
}
|
|
|
|
|
|
|
|
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));
|
|
|
|
}
|
|
|
|
|
|
|
|
_onTargetCrashed() {
|
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();
|
|
|
|
const handle = await this.adoptBackendNodeId(event.backendNodeId, utilityContext);
|
|
|
|
this._page._onFileChooserOpened(handle);
|
|
|
|
}
|
|
|
|
|
2020-04-02 17:56:14 -07:00
|
|
|
_onDownloadWillBegin(payload: Protocol.Page.downloadWillBeginPayload) {
|
|
|
|
this._browserContext._browser._downloadCreated(this._page, payload.guid, payload.url);
|
|
|
|
}
|
|
|
|
|
|
|
|
_onDownloadProgress(payload: Protocol.Page.downloadProgressPayload) {
|
|
|
|
if (payload.state === 'completed')
|
|
|
|
this._browserContext._browser._downloadFinished(payload.guid, '');
|
|
|
|
if (payload.state === 'canceled')
|
|
|
|
this._browserContext._browser._downloadFinished(payload.guid, 'canceled');
|
|
|
|
}
|
|
|
|
|
2020-02-26 12:42:20 -08:00
|
|
|
async updateExtraHTTPHeaders(): Promise<void> {
|
|
|
|
const headers = network.mergeHeaders([
|
2020-03-05 17:22:57 -08:00
|
|
|
this._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-02-06 19:02:55 -08:00
|
|
|
async setViewportSize(viewportSize: types.Size): Promise<void> {
|
|
|
|
assert(this._page._state.viewportSize === viewportSize);
|
|
|
|
await this._updateViewport(false /* updateTouch */);
|
|
|
|
}
|
|
|
|
|
|
|
|
async _updateViewport(updateTouch: boolean): Promise<void> {
|
2020-03-17 18:21:02 -07:00
|
|
|
const options = this._browserContext._options;
|
|
|
|
let viewport = options.viewport || { width: 0, height: 0 };
|
2020-02-06 19:02:55 -08:00
|
|
|
const viewportSize = this._page._state.viewportSize;
|
|
|
|
if (viewportSize)
|
|
|
|
viewport = { ...viewport, ...viewportSize };
|
|
|
|
const isLandscape = viewport.width > viewport.height;
|
|
|
|
const promises = [
|
|
|
|
this._client.send('Emulation.setDeviceMetricsOverride', {
|
2020-03-17 18:21:02 -07:00
|
|
|
mobile: !!options.isMobile,
|
2020-02-06 19:02:55 -08:00
|
|
|
width: viewport.width,
|
|
|
|
height: viewport.height,
|
2020-03-09 15:53:31 -07:00
|
|
|
screenWidth: viewport.width,
|
|
|
|
screenHeight: viewport.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' },
|
|
|
|
}),
|
|
|
|
];
|
|
|
|
if (updateTouch)
|
2020-03-17 18:21:02 -07:00
|
|
|
promises.push(this._client.send('Emulation.setTouchEmulationEnabled', { enabled: !!options.hasTouch }));
|
2020-02-06 19:02:55 -08:00
|
|
|
await Promise.all(promises);
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
2020-01-03 12:59:06 -08:00
|
|
|
async setEmulateMedia(mediaType: types.MediaType | null, colorScheme: types.ColorScheme | null): Promise<void> {
|
|
|
|
const features = colorScheme ? [{ name: 'prefers-color-scheme', value: colorScheme }] : [];
|
2019-12-19 16:53:24 -08:00
|
|
|
await this._client.send('Emulation.setEmulatedMedia', { media: mediaType || '', features });
|
|
|
|
}
|
|
|
|
|
2020-03-09 21:02:54 -07:00
|
|
|
async updateRequestInterception(): Promise<void> {
|
|
|
|
await this._networkManager.setRequestInterception(this._page._needsRequestInterception());
|
2019-12-30 14:05:28 -08:00
|
|
|
}
|
|
|
|
|
2020-01-30 17:43:06 -08:00
|
|
|
async setFileChooserIntercepted(enabled: boolean) {
|
|
|
|
await this._client.send('Page.setInterceptFileChooserDialog', { enabled }).catch(e => {}); // target can be closed.
|
|
|
|
}
|
|
|
|
|
2020-02-07 13:36:49 -08:00
|
|
|
async opener(): Promise<Page | null> {
|
2020-03-23 21:48:32 -07:00
|
|
|
if (!this._opener)
|
2020-01-31 18:38:45 -08:00
|
|
|
return null;
|
2020-03-23 21:48:32 -07:00
|
|
|
const openerPage = await this._opener.pageOrError();
|
2020-03-05 15:18:27 -08:00
|
|
|
if (openerPage instanceof Page && !openerPage.isClosed())
|
|
|
|
return openerPage;
|
|
|
|
return null;
|
2020-01-31 18:38:45 -08:00
|
|
|
}
|
|
|
|
|
2019-12-19 16:53:24 -08:00
|
|
|
async reload(): Promise<void> {
|
|
|
|
await this._client.send('Page.reload');
|
|
|
|
}
|
|
|
|
|
|
|
|
private async _go(delta: number): Promise<boolean> {
|
|
|
|
const history = await this._client.send('Page.getNavigationHistory');
|
|
|
|
const entry = history.entries[history.currentIndex + delta];
|
|
|
|
if (!entry)
|
|
|
|
return false;
|
|
|
|
await this._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._client.send('Page.addScriptToEvaluateOnNewDocument', { source });
|
|
|
|
}
|
|
|
|
|
|
|
|
async closePage(runBeforeUnload: boolean): Promise<void> {
|
|
|
|
if (runBeforeUnload)
|
|
|
|
await this._client.send('Page.close');
|
|
|
|
else
|
2020-03-23 21:48:32 -07:00
|
|
|
await this._browserContext._browser._closePage(this);
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
canScreenshotOutsideViewport(): boolean {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
async setBackgroundColor(color?: { r: number; g: number; b: number; a: number; }): Promise<void> {
|
|
|
|
await this._client.send('Emulation.setDefaultBackgroundColorOverride', { color });
|
|
|
|
}
|
|
|
|
|
2020-04-01 14:42:47 -07:00
|
|
|
async takeScreenshot(format: 'png' | 'jpeg', documentRect: types.Rect | undefined, viewportRect: types.Rect | undefined, quality: number | undefined): Promise<Buffer> {
|
2020-03-03 16:09:32 -08:00
|
|
|
const { visualViewport } = await this._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,
|
|
|
|
})
|
|
|
|
};
|
|
|
|
}
|
2019-12-19 16:53:24 -08:00
|
|
|
await this._client.send('Page.bringToFront', {});
|
2020-03-03 16:09:32 -08:00
|
|
|
// 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._client.send('Page.captureScreenshot', { format, quality, clip });
|
2020-04-01 14:42:47 -07:00
|
|
|
return Buffer.from(result.data, 'base64');
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
async resetViewport(): Promise<void> {
|
|
|
|
await this._client.send('Emulation.setDeviceMetricsOverride', { mobile: false, width: 0, height: 0, deviceScaleFactor: 0 });
|
|
|
|
}
|
|
|
|
|
|
|
|
async getContentFrame(handle: dom.ElementHandle): Promise<frames.Frame | null> {
|
|
|
|
const nodeInfo = await this._client.send('DOM.describeNode', {
|
|
|
|
objectId: toRemoteObject(handle).objectId
|
|
|
|
});
|
|
|
|
if (!nodeInfo || typeof nodeInfo.node.frameId !== 'string')
|
|
|
|
return null;
|
|
|
|
return this._page._frameManager.frame(nodeInfo.node.frameId);
|
|
|
|
}
|
|
|
|
|
2020-01-27 11:43:43 -08: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;
|
|
|
|
const remoteObject = toRemoteObject(documentElement);
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
isElementHandle(remoteObject: any): boolean {
|
|
|
|
return (remoteObject as Protocol.Runtime.RemoteObject).subtype === 'node';
|
|
|
|
}
|
|
|
|
|
|
|
|
async getBoundingBox(handle: dom.ElementHandle): Promise<types.Rect | null> {
|
|
|
|
const result = await this._client.send('DOM.getBoxModel', {
|
|
|
|
objectId: toRemoteObject(handle).objectId
|
|
|
|
}).catch(debugError);
|
|
|
|
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-02-11 10:30:09 -08:00
|
|
|
async scrollRectIntoViewIfNeeded(handle: dom.ElementHandle, rect?: types.Rect): Promise<void> {
|
|
|
|
await this._client.send('DOM.scrollIntoViewIfNeeded', {
|
|
|
|
objectId: toRemoteObject(handle).objectId,
|
|
|
|
rect,
|
|
|
|
}).catch(e => {
|
|
|
|
if (e instanceof Error && e.message.includes('Node does not have a layout object'))
|
|
|
|
e.message = 'Node is either not visible or not an HTMLElement';
|
|
|
|
throw e;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-12-19 16:53:24 -08:00
|
|
|
async getContentQuads(handle: dom.ElementHandle): Promise<types.Quad[] | null> {
|
|
|
|
const result = await this._client.send('DOM.getContentQuads', {
|
|
|
|
objectId: toRemoteObject(handle).objectId
|
|
|
|
}).catch(debugError);
|
|
|
|
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] }
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
|
|
|
async layoutViewport(): Promise<{ width: number, height: number }> {
|
|
|
|
const layoutMetrics = await this._client.send('Page.getLayoutMetrics');
|
|
|
|
return { width: layoutMetrics.layoutViewport.clientWidth, height: layoutMetrics.layoutViewport.clientHeight };
|
|
|
|
}
|
|
|
|
|
2020-01-13 13:33:25 -08:00
|
|
|
async setInputFiles(handle: dom.ElementHandle<HTMLInputElement>, files: types.FilePayload[]): Promise<void> {
|
2020-01-03 12:59:06 -08:00
|
|
|
await handle.evaluate(dom.setFileInputFunction, files);
|
2019-12-19 16:53:24 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
async adoptElementHandle<T extends Node>(handle: dom.ElementHandle<T>, to: dom.FrameExecutionContext): Promise<dom.ElementHandle<T>> {
|
|
|
|
const nodeInfo = await this._client.send('DOM.describeNode', {
|
|
|
|
objectId: toRemoteObject(handle).objectId,
|
|
|
|
});
|
|
|
|
return this.adoptBackendNodeId(nodeInfo.node.backendNodeId, to) as Promise<dom.ElementHandle<T>>;
|
|
|
|
}
|
|
|
|
|
|
|
|
async adoptBackendNodeId(backendNodeId: Protocol.DOM.BackendNodeId, to: dom.FrameExecutionContext): Promise<dom.ElementHandle> {
|
|
|
|
const result = await this._client.send('DOM.resolveNode', {
|
|
|
|
backendNodeId,
|
|
|
|
executionContextId: (to._delegate as CRExecutionContext)._contextId,
|
|
|
|
}).catch(debugError);
|
|
|
|
if (!result || result.object.subtype === 'null')
|
|
|
|
throw new Error('Unable to adopt element handle from a different document');
|
|
|
|
return to._createHandle(result.object).asElement()!;
|
|
|
|
}
|
2020-01-03 11:15:43 -08:00
|
|
|
|
2020-01-14 16:54:50 -08:00
|
|
|
async getAccessibilityTree(needle?: dom.ElementHandle) {
|
|
|
|
return getAccessibilityTree(this._client, needle);
|
2020-01-03 11:15:43 -08:00
|
|
|
}
|
2019-12-21 09:03:52 -08:00
|
|
|
|
2020-03-07 08:19:31 -08:00
|
|
|
async inputActionEpilogue(): Promise<void> {
|
|
|
|
await this._client.send('Page.enable').catch(e => {});
|
|
|
|
}
|
|
|
|
|
2020-04-01 14:42:47 -07:00
|
|
|
async pdf(options?: types.PDFOptions): Promise<Buffer> {
|
2020-01-07 13:57:37 -08:00
|
|
|
return this._pdf.generate(options);
|
2019-12-21 09:03:52 -08:00
|
|
|
}
|
|
|
|
|
2020-02-13 17:39:14 -08:00
|
|
|
coverage(): CRCoverage {
|
2020-01-07 13:57:37 -08:00
|
|
|
return this._coverage;
|
2019-12-21 09:03:52 -08:00
|
|
|
}
|
2020-02-05 17:20:23 -08:00
|
|
|
|
|
|
|
async getFrameElement(frame: frames.Frame): Promise<dom.ElementHandle> {
|
|
|
|
const { backendNodeId } = await this._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;
|
|
|
|
});
|
|
|
|
const parent = frame.parentFrame();
|
|
|
|
if (!parent)
|
|
|
|
throw new Error('Frame has been detached.');
|
|
|
|
return this.adoptBackendNodeId(backendNodeId, await parent._mainContext());
|
|
|
|
}
|
2019-12-21 09:03:52 -08:00
|
|
|
}
|
|
|
|
|
2020-01-13 13:33:25 -08:00
|
|
|
function toRemoteObject(handle: js.JSHandle): Protocol.Runtime.RemoteObject {
|
2019-12-19 16:53:24 -08:00
|
|
|
return handle._remoteObject as Protocol.Runtime.RemoteObject;
|
|
|
|
}
|
2020-01-02 15:06:28 -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;
|
|
|
|
}
|
|
|
|
}
|