2019-11-18 18:18:28 -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.
|
|
|
|
*/
|
|
|
|
|
2022-09-20 18:41:51 -07:00
|
|
|
import type * as channels from '@protocol/channels';
|
2022-04-06 13:57:14 -08:00
|
|
|
import type { ConsoleMessage } from './console';
|
2019-11-27 16:02:31 -08:00
|
|
|
import * as dom from './dom';
|
2021-07-07 21:14:16 +02:00
|
|
|
import { helper } from './helper';
|
2022-04-07 19:18:22 -08:00
|
|
|
import type { RegisteredListener } from '../utils/eventsHelper';
|
|
|
|
import { eventsHelper } from '../utils/eventsHelper';
|
2020-04-01 14:42:47 -07:00
|
|
|
import * as js from './javascript';
|
|
|
|
import * as network from './network';
|
2022-04-06 13:57:14 -08:00
|
|
|
import type { Dialog } from './dialog';
|
2019-12-11 12:36:42 -08:00
|
|
|
import { Page } from './page';
|
2020-04-01 14:42:47 -07:00
|
|
|
import * as types from './types';
|
2020-05-18 14:28:06 -07:00
|
|
|
import { BrowserContext } from './browserContext';
|
2022-04-06 13:57:14 -08:00
|
|
|
import type { Progress } from './progress';
|
|
|
|
import { ProgressController } from './progress';
|
2022-11-17 19:43:10 -08:00
|
|
|
import { assert, constructURLBasedOnBaseURL, makeWaitForNextTask, monotonicTime } from '../utils';
|
2022-04-07 19:18:22 -08:00
|
|
|
import { ManualPromise } from '../utils/manualPromise';
|
2022-04-07 13:36:13 -08:00
|
|
|
import { debugLogger } from '../common/debugLogger';
|
2022-04-06 13:57:14 -08:00
|
|
|
import type { CallMetadata } from './instrumentation';
|
|
|
|
import { serverSideCallMetadata, SdkObject } from './instrumentation';
|
2022-12-27 13:39:35 -08:00
|
|
|
import type { InjectedScript, ElementStateWithoutStable, FrameExpectParams, InjectedScriptPoll, InjectedScriptProgress } from './injected/injectedScript';
|
2022-01-18 19:13:51 -08:00
|
|
|
import { isSessionClosedError } from './protocolError';
|
2023-03-06 18:49:14 -08:00
|
|
|
import { type ParsedSelector, isInvalidSelectorError } from '../utils/isomorphic/selectorParser';
|
2022-04-06 13:57:14 -08:00
|
|
|
import type { ScreenshotOptions } from './screenshotter';
|
|
|
|
import type { InputFilesItems } from './dom';
|
2023-03-06 18:49:14 -08:00
|
|
|
import { asLocator } from '../utils/isomorphic/locatorGenerators';
|
2023-02-21 14:08:51 -08:00
|
|
|
import { FrameSelectors } from './frameSelectors';
|
2023-04-03 15:06:13 -07:00
|
|
|
import { TimeoutError } from '../common/errors';
|
2019-11-18 18:18:28 -08:00
|
|
|
|
2019-12-12 21:11:52 -08:00
|
|
|
type ContextData = {
|
2021-11-03 10:44:50 -07:00
|
|
|
contextPromise: ManualPromise<dom.FrameExecutionContext | Error>;
|
2019-12-12 21:11:52 -08:00
|
|
|
context: dom.FrameExecutionContext | null;
|
2019-11-26 15:37:25 -08:00
|
|
|
};
|
|
|
|
|
2020-07-06 15:58:27 -07:00
|
|
|
type DocumentInfo = {
|
|
|
|
// Unfortunately, we don't have documentId when we find out about
|
|
|
|
// a pending navigation from things like frameScheduledNavigaiton.
|
|
|
|
documentId: string | undefined,
|
|
|
|
request: network.Request | undefined,
|
|
|
|
};
|
|
|
|
|
2019-12-16 22:02:33 -08:00
|
|
|
export type GotoResult = {
|
|
|
|
newDocumentId?: string,
|
|
|
|
};
|
2019-11-26 16:19:43 -08:00
|
|
|
|
2020-01-27 16:51:52 -08:00
|
|
|
type ConsoleTagHandler = () => void;
|
2019-12-14 19:13:22 -08:00
|
|
|
|
2022-08-26 13:48:05 -07:00
|
|
|
type RegularLifecycleEvent = Exclude<types.LifecycleEvent, 'networkidle'>;
|
|
|
|
|
2020-05-18 14:28:06 -07:00
|
|
|
export type FunctionWithSource = (source: { context: BrowserContext, page: Page, frame: Frame}, ...args: any) => any;
|
|
|
|
|
2020-07-15 18:48:19 -07:00
|
|
|
export type NavigationEvent = {
|
|
|
|
// New frame url after navigation.
|
|
|
|
url: string,
|
|
|
|
// New frame name after navigation.
|
|
|
|
name: string,
|
|
|
|
// Information about the new document for cross-document navigations.
|
|
|
|
// Undefined for same-document navigations.
|
|
|
|
newDocument?: DocumentInfo,
|
|
|
|
// Error for cross-document navigations if any. When error is present,
|
|
|
|
// the navigation did not commit.
|
2020-07-07 15:22:05 -07:00
|
|
|
error?: Error,
|
2022-06-17 21:17:30 -07:00
|
|
|
// Wether this event should be visible to the clients via the public APIs.
|
|
|
|
isPublic?: boolean;
|
2020-07-07 15:22:05 -07:00
|
|
|
};
|
|
|
|
|
2021-09-22 17:17:49 -07:00
|
|
|
export type SchedulableTask<T> = (injectedScript: js.JSHandle<InjectedScript>) => Promise<js.JSHandle<InjectedScriptPoll<T>>>;
|
2021-11-01 13:57:13 -07:00
|
|
|
export type DomTaskBody<T, R, E> = (progress: InjectedScriptProgress, element: E, data: T, elements: Element[]) => R | symbol;
|
2022-12-27 09:22:22 -08:00
|
|
|
type ElementCallback<T, R> = (injected: InjectedScript, element: Element, data: T) => R;
|
2021-09-22 17:17:49 -07:00
|
|
|
|
2022-06-17 21:17:30 -07:00
|
|
|
export class NavigationAbortedError extends Error {
|
|
|
|
readonly documentId?: string;
|
|
|
|
constructor(documentId: string | undefined, message: string) {
|
|
|
|
super(message);
|
|
|
|
this.documentId = documentId;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-04 20:52:50 +01:00
|
|
|
const kDummyFrameId = '<dummy>';
|
|
|
|
|
2019-12-16 15:56:11 -08:00
|
|
|
export class FrameManager {
|
|
|
|
private _page: Page;
|
|
|
|
private _frames = new Map<string, Frame>();
|
|
|
|
private _mainFrame: Frame;
|
2020-01-27 16:51:52 -08:00
|
|
|
readonly _consoleMessageTags = new Map<string, ConsoleTagHandler>();
|
2020-04-16 13:09:24 -07:00
|
|
|
readonly _signalBarriers = new Set<SignalBarrier>();
|
2020-10-26 22:20:43 -07:00
|
|
|
private _webSockets = new Map<string, network.WebSocket>();
|
2022-01-25 14:52:18 -07:00
|
|
|
_openedDialogs: Set<Dialog> = new Set();
|
2022-10-26 15:17:40 -07:00
|
|
|
private _closeAllOpeningDialogs = false;
|
2019-12-16 15:56:11 -08:00
|
|
|
|
|
|
|
constructor(page: Page) {
|
|
|
|
this._page = page;
|
2020-01-13 13:33:25 -08:00
|
|
|
this._mainFrame = undefined as any as Frame;
|
2019-12-16 15:56:11 -08:00
|
|
|
}
|
|
|
|
|
2022-05-04 20:52:50 +01:00
|
|
|
createDummyMainFrameIfNeeded() {
|
|
|
|
if (!this._mainFrame)
|
|
|
|
this.frameAttached(kDummyFrameId, null);
|
|
|
|
}
|
|
|
|
|
2020-07-10 16:38:01 -07:00
|
|
|
dispose() {
|
2022-05-24 14:02:32 -07:00
|
|
|
for (const frame of this._frames.values()) {
|
2020-07-10 16:38:01 -07:00
|
|
|
frame._stopNetworkIdleTimer();
|
2022-05-24 14:02:32 -07:00
|
|
|
frame._invalidateNonStallingEvaluations('Target crashed');
|
|
|
|
}
|
2020-07-10 16:38:01 -07:00
|
|
|
}
|
|
|
|
|
2019-12-16 15:56:11 -08:00
|
|
|
mainFrame(): Frame {
|
|
|
|
return this._mainFrame;
|
|
|
|
}
|
|
|
|
|
|
|
|
frames() {
|
|
|
|
const frames: Frame[] = [];
|
|
|
|
collect(this._mainFrame);
|
|
|
|
return frames;
|
|
|
|
|
|
|
|
function collect(frame: Frame) {
|
|
|
|
frames.push(frame);
|
|
|
|
for (const subframe of frame.childFrames())
|
|
|
|
collect(subframe);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
frame(frameId: string): Frame | null {
|
|
|
|
return this._frames.get(frameId) || null;
|
|
|
|
}
|
|
|
|
|
|
|
|
frameAttached(frameId: string, parentFrameId: string | null | undefined): Frame {
|
2020-01-13 13:33:25 -08:00
|
|
|
const parentFrame = parentFrameId ? this._frames.get(parentFrameId)! : null;
|
2019-12-16 15:56:11 -08:00
|
|
|
if (!parentFrame) {
|
|
|
|
if (this._mainFrame) {
|
|
|
|
// Update frame id to retain frame identity on cross-process navigation.
|
|
|
|
this._frames.delete(this._mainFrame._id);
|
|
|
|
this._mainFrame._id = frameId;
|
|
|
|
} else {
|
|
|
|
assert(!this._frames.has(frameId));
|
|
|
|
this._mainFrame = new Frame(this._page, frameId, parentFrame);
|
|
|
|
}
|
|
|
|
this._frames.set(frameId, this._mainFrame);
|
|
|
|
return this._mainFrame;
|
|
|
|
} else {
|
|
|
|
assert(!this._frames.has(frameId));
|
|
|
|
const frame = new Frame(this._page, frameId, parentFrame);
|
|
|
|
this._frames.set(frameId, frame);
|
2020-08-21 16:26:33 -07:00
|
|
|
this._page.emit(Page.Events.FrameAttached, frame);
|
2019-12-16 15:56:11 -08:00
|
|
|
return frame;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-03 11:23:24 -07:00
|
|
|
async waitForSignalsCreatedBy<T>(progress: Progress | null, noWaitAfter: boolean | undefined, action: () => Promise<T>, source?: 'input'): Promise<T> {
|
|
|
|
if (noWaitAfter)
|
2020-03-06 14:32:15 -08:00
|
|
|
return action();
|
2020-06-03 11:23:24 -07:00
|
|
|
const barrier = new SignalBarrier(progress);
|
2020-04-16 13:09:24 -07:00
|
|
|
this._signalBarriers.add(barrier);
|
2020-06-03 11:23:24 -07:00
|
|
|
if (progress)
|
2020-06-04 16:43:48 -07:00
|
|
|
progress.cleanupWhenAborted(() => this._signalBarriers.delete(barrier));
|
2020-06-03 11:23:24 -07:00
|
|
|
const result = await action();
|
2021-04-23 09:28:18 -07:00
|
|
|
if (source === 'input')
|
2020-06-03 11:23:24 -07:00
|
|
|
await this._page._delegate.inputActionEpilogue();
|
|
|
|
await barrier.waitFor();
|
|
|
|
this._signalBarriers.delete(barrier);
|
|
|
|
// Resolve in the next task, after all waitForNavigations.
|
2021-02-03 13:49:25 -08:00
|
|
|
await new Promise<void>(makeWaitForNextTask());
|
2020-06-03 11:23:24 -07:00
|
|
|
return result;
|
2020-03-04 19:15:01 -08:00
|
|
|
}
|
|
|
|
|
2020-03-05 14:47:04 -08:00
|
|
|
frameWillPotentiallyRequestNavigation() {
|
2020-04-16 13:09:24 -07:00
|
|
|
for (const barrier of this._signalBarriers)
|
2020-03-05 14:47:04 -08:00
|
|
|
barrier.retain();
|
2020-03-04 19:15:01 -08:00
|
|
|
}
|
|
|
|
|
2020-03-05 14:47:04 -08:00
|
|
|
frameDidPotentiallyRequestNavigation() {
|
2020-04-16 13:09:24 -07:00
|
|
|
for (const barrier of this._signalBarriers)
|
2020-03-05 14:47:04 -08:00
|
|
|
barrier.release();
|
|
|
|
}
|
|
|
|
|
2020-07-06 15:58:27 -07:00
|
|
|
frameRequestedNavigation(frameId: string, documentId?: string) {
|
2020-03-05 14:47:04 -08:00
|
|
|
const frame = this._frames.get(frameId);
|
|
|
|
if (!frame)
|
|
|
|
return;
|
2020-04-16 13:09:24 -07:00
|
|
|
for (const barrier of this._signalBarriers)
|
|
|
|
barrier.addFrameNavigation(frame);
|
2021-04-29 09:28:19 -07:00
|
|
|
if (frame.pendingDocument() && frame.pendingDocument()!.documentId === documentId) {
|
2020-07-06 15:58:27 -07:00
|
|
|
// Do not override request with undefined.
|
2020-04-09 19:03:06 -07:00
|
|
|
return;
|
2020-07-06 15:58:27 -07:00
|
|
|
}
|
2021-04-29 09:28:19 -07:00
|
|
|
frame.setPendingDocument({ documentId, request: undefined });
|
2020-03-04 19:15:01 -08:00
|
|
|
}
|
|
|
|
|
2019-12-16 15:56:11 -08:00
|
|
|
frameCommittedNewDocumentNavigation(frameId: string, url: string, name: string, documentId: string, initial: boolean) {
|
2020-01-13 13:33:25 -08:00
|
|
|
const frame = this._frames.get(frameId)!;
|
2020-04-06 15:09:43 -07:00
|
|
|
this.removeChildFramesRecursively(frame);
|
2020-10-26 22:20:43 -07:00
|
|
|
this.clearWebSockets(frame);
|
2019-12-16 15:56:11 -08:00
|
|
|
frame._url = url;
|
|
|
|
frame._name = name;
|
2020-08-11 08:59:00 -07:00
|
|
|
|
|
|
|
let keepPending: DocumentInfo | undefined;
|
2021-04-29 09:28:19 -07:00
|
|
|
const pendingDocument = frame.pendingDocument();
|
|
|
|
if (pendingDocument) {
|
|
|
|
if (pendingDocument.documentId === undefined) {
|
2020-08-11 08:59:00 -07:00
|
|
|
// Pending with unknown documentId - assume it is the one being committed.
|
2021-04-29 09:28:19 -07:00
|
|
|
pendingDocument.documentId = documentId;
|
2020-08-11 08:59:00 -07:00
|
|
|
}
|
2021-04-29 09:28:19 -07:00
|
|
|
if (pendingDocument.documentId === documentId) {
|
2020-08-11 08:59:00 -07:00
|
|
|
// Committing a pending document.
|
2021-04-29 09:28:19 -07:00
|
|
|
frame._currentDocument = pendingDocument;
|
2020-08-11 08:59:00 -07:00
|
|
|
} else {
|
|
|
|
// Sometimes, we already have a new pending when the old one commits.
|
|
|
|
// An example would be Chromium error page followed by a new navigation request,
|
|
|
|
// where the error page commit arrives after Network.requestWillBeSent for the
|
|
|
|
// new navigation.
|
|
|
|
// We commit, but keep the pending request since it's not done yet.
|
2021-04-29 09:28:19 -07:00
|
|
|
keepPending = pendingDocument;
|
2020-08-11 08:59:00 -07:00
|
|
|
frame._currentDocument = { documentId, request: undefined };
|
|
|
|
}
|
2021-04-29 09:28:19 -07:00
|
|
|
frame.setPendingDocument(undefined);
|
2020-08-11 08:59:00 -07:00
|
|
|
} else {
|
|
|
|
// No pending - just commit a new document.
|
2020-07-06 15:58:27 -07:00
|
|
|
frame._currentDocument = { documentId, request: undefined };
|
2020-08-11 08:59:00 -07:00
|
|
|
}
|
|
|
|
|
2020-07-06 17:33:56 -07:00
|
|
|
frame._onClearLifecycle();
|
2022-06-17 21:17:30 -07:00
|
|
|
const navigationEvent: NavigationEvent = { url, name, newDocument: frame._currentDocument, isPublic: true };
|
2022-08-11 13:42:16 -07:00
|
|
|
this._fireInternalFrameNavigation(frame, navigationEvent);
|
2020-07-07 15:22:05 -07:00
|
|
|
if (!initial) {
|
2020-08-17 14:12:31 -07:00
|
|
|
debugLogger.log('api', ` navigated to "${url}"`);
|
2021-01-13 14:25:42 -08:00
|
|
|
this._page.frameNavigatedToNewDocument(frame);
|
2020-07-07 15:22:05 -07:00
|
|
|
}
|
2020-08-11 08:59:00 -07:00
|
|
|
// Restore pending if any - see comments above about keepPending.
|
2021-04-29 09:28:19 -07:00
|
|
|
frame.setPendingDocument(keepPending);
|
2019-12-16 15:56:11 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
frameCommittedSameDocumentNavigation(frameId: string, url: string) {
|
|
|
|
const frame = this._frames.get(frameId);
|
|
|
|
if (!frame)
|
|
|
|
return;
|
|
|
|
frame._url = url;
|
2022-06-17 21:17:30 -07:00
|
|
|
const navigationEvent: NavigationEvent = { url, name: frame._name, isPublic: true };
|
2022-08-11 13:42:16 -07:00
|
|
|
this._fireInternalFrameNavigation(frame, navigationEvent);
|
2020-08-17 14:12:31 -07:00
|
|
|
debugLogger.log('api', ` navigated to "${url}"`);
|
2019-12-16 15:56:11 -08:00
|
|
|
}
|
|
|
|
|
2020-07-06 15:58:27 -07:00
|
|
|
frameAbortedNavigation(frameId: string, errorText: string, documentId?: string) {
|
|
|
|
const frame = this._frames.get(frameId);
|
2021-04-29 09:28:19 -07:00
|
|
|
if (!frame || !frame.pendingDocument())
|
2020-07-06 15:58:27 -07:00
|
|
|
return;
|
2021-04-29 09:28:19 -07:00
|
|
|
if (documentId !== undefined && frame.pendingDocument()!.documentId !== documentId)
|
2020-07-06 15:58:27 -07:00
|
|
|
return;
|
2020-07-15 18:48:19 -07:00
|
|
|
const navigationEvent: NavigationEvent = {
|
|
|
|
url: frame._url,
|
|
|
|
name: frame._name,
|
2021-04-29 09:28:19 -07:00
|
|
|
newDocument: frame.pendingDocument(),
|
2022-06-17 21:17:30 -07:00
|
|
|
error: new NavigationAbortedError(documentId, errorText),
|
2022-06-21 11:01:01 -07:00
|
|
|
isPublic: !(documentId && frame._redirectedNavigations.has(documentId)),
|
2020-07-15 18:48:19 -07:00
|
|
|
};
|
2021-04-29 09:28:19 -07:00
|
|
|
frame.setPendingDocument(undefined);
|
2022-08-11 13:42:16 -07:00
|
|
|
this._fireInternalFrameNavigation(frame, navigationEvent);
|
2020-07-06 15:58:27 -07:00
|
|
|
}
|
|
|
|
|
2019-12-16 15:56:11 -08:00
|
|
|
frameDetached(frameId: string) {
|
|
|
|
const frame = this._frames.get(frameId);
|
2022-07-22 19:44:02 -07:00
|
|
|
if (frame) {
|
2019-12-16 15:56:11 -08:00
|
|
|
this._removeFramesRecursively(frame);
|
2022-08-26 13:48:05 -07:00
|
|
|
this._page.mainFrame()._recalculateNetworkIdle();
|
2022-07-22 19:44:02 -07:00
|
|
|
}
|
2019-12-16 15:56:11 -08:00
|
|
|
}
|
|
|
|
|
2022-08-26 13:48:05 -07:00
|
|
|
frameLifecycleEvent(frameId: string, event: RegularLifecycleEvent) {
|
2019-12-16 15:56:11 -08:00
|
|
|
const frame = this._frames.get(frameId);
|
2020-07-06 17:33:56 -07:00
|
|
|
if (frame)
|
|
|
|
frame._onLifecycleEvent(event);
|
2020-01-03 12:59:27 -08:00
|
|
|
}
|
|
|
|
|
2021-08-05 08:49:02 -07:00
|
|
|
requestStarted(request: network.Request, route?: network.RouteDelegate) {
|
2022-07-01 12:49:43 -07:00
|
|
|
const frame = request.frame()!;
|
2020-01-03 12:59:27 -08:00
|
|
|
this._inflightRequestStarted(request);
|
2020-07-06 15:58:27 -07:00
|
|
|
if (request._documentId)
|
2021-04-29 09:28:19 -07:00
|
|
|
frame.setPendingDocument({ documentId: request._documentId, request });
|
2020-05-15 15:22:29 -07:00
|
|
|
if (request._isFavicon) {
|
|
|
|
if (route)
|
2023-06-14 09:37:19 -07:00
|
|
|
route.continue(request, { isFallback: true });
|
2020-05-15 15:22:29 -07:00
|
|
|
return;
|
|
|
|
}
|
2022-03-17 17:27:33 -08:00
|
|
|
this._page.emitOnContext(BrowserContext.Events.Request, request);
|
2022-07-01 12:49:43 -07:00
|
|
|
if (route) {
|
|
|
|
const r = new network.Route(request, route);
|
2023-01-27 10:43:19 -08:00
|
|
|
if (this._page._serverRequestInterceptor?.(r, request))
|
2022-07-01 12:49:43 -07:00
|
|
|
return;
|
2023-01-27 10:43:19 -08:00
|
|
|
if (this._page._clientRequestInterceptor?.(r, request))
|
2022-07-01 12:49:43 -07:00
|
|
|
return;
|
2023-01-27 10:43:19 -08:00
|
|
|
if (this._page._browserContext._requestInterceptor?.(r, request))
|
2022-07-01 12:49:43 -07:00
|
|
|
return;
|
2023-06-14 09:37:19 -07:00
|
|
|
r.continue({ isFallback: true });
|
2022-07-01 12:49:43 -07:00
|
|
|
}
|
2019-12-16 16:32:04 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
requestReceivedResponse(response: network.Response) {
|
2021-04-27 11:07:07 -07:00
|
|
|
if (response.request()._isFavicon)
|
|
|
|
return;
|
2022-03-17 17:27:33 -08:00
|
|
|
this._page.emitOnContext(BrowserContext.Events.Response, response);
|
2019-12-16 16:32:04 -08:00
|
|
|
}
|
|
|
|
|
2021-08-30 20:43:40 -07:00
|
|
|
reportRequestFinished(request: network.Request, response: network.Response | null) {
|
2020-01-03 12:59:27 -08:00
|
|
|
this._inflightRequestFinished(request);
|
2021-05-13 10:29:14 -07:00
|
|
|
if (request._isFavicon)
|
|
|
|
return;
|
2022-03-17 17:27:33 -08:00
|
|
|
this._page.emitOnContext(BrowserContext.Events.RequestFinished, { request, response });
|
2019-12-16 16:32:04 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
requestFailed(request: network.Request, canceled: boolean) {
|
2022-07-01 12:49:43 -07:00
|
|
|
const frame = request.frame()!;
|
2020-01-03 12:59:27 -08:00
|
|
|
this._inflightRequestFinished(request);
|
2021-04-29 09:28:19 -07:00
|
|
|
if (frame.pendingDocument() && frame.pendingDocument()!.request === request) {
|
2020-07-06 15:58:27 -07:00
|
|
|
let errorText = request.failure()!.errorText;
|
|
|
|
if (canceled)
|
|
|
|
errorText += '; maybe frame was detached?';
|
2021-04-29 09:28:19 -07:00
|
|
|
this.frameAbortedNavigation(frame._id, errorText, frame.pendingDocument()!.documentId);
|
2019-12-16 16:32:04 -08:00
|
|
|
}
|
2021-05-13 10:29:14 -07:00
|
|
|
if (request._isFavicon)
|
|
|
|
return;
|
2022-03-17 17:27:33 -08:00
|
|
|
this._page.emitOnContext(BrowserContext.Events.RequestFailed, request);
|
2019-12-16 16:32:04 -08:00
|
|
|
}
|
|
|
|
|
2022-01-25 14:52:18 -07:00
|
|
|
dialogDidOpen(dialog: Dialog) {
|
2021-08-19 18:20:15 -07:00
|
|
|
// Any ongoing evaluations will be stalled until the dialog is closed.
|
|
|
|
for (const frame of this._frames.values())
|
|
|
|
frame._invalidateNonStallingEvaluations('JavaScript dialog interrupted evaluation');
|
2022-10-26 15:17:40 -07:00
|
|
|
if (this._closeAllOpeningDialogs)
|
|
|
|
dialog.close().then(() => {});
|
|
|
|
else
|
|
|
|
this._openedDialogs.add(dialog);
|
2021-08-19 18:20:15 -07:00
|
|
|
}
|
|
|
|
|
2022-01-25 14:52:18 -07:00
|
|
|
dialogWillClose(dialog: Dialog) {
|
|
|
|
this._openedDialogs.delete(dialog);
|
2021-08-19 18:20:15 -07:00
|
|
|
}
|
|
|
|
|
2022-07-11 12:10:08 -08:00
|
|
|
async closeOpenDialogs() {
|
2022-10-26 15:17:40 -07:00
|
|
|
await Promise.all([...this._openedDialogs].map(dialog => dialog.close())).catch(() => {});
|
2022-07-11 12:10:08 -08:00
|
|
|
this._openedDialogs.clear();
|
|
|
|
}
|
|
|
|
|
2022-10-26 15:17:40 -07:00
|
|
|
setCloseAllOpeningDialogs(closeDialogs: boolean) {
|
|
|
|
this._closeAllOpeningDialogs = closeDialogs;
|
|
|
|
}
|
|
|
|
|
2020-04-06 15:09:43 -07:00
|
|
|
removeChildFramesRecursively(frame: Frame) {
|
2019-12-16 15:56:11 -08:00
|
|
|
for (const child of frame.childFrames())
|
|
|
|
this._removeFramesRecursively(child);
|
2020-04-06 15:09:43 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
private _removeFramesRecursively(frame: Frame) {
|
|
|
|
this.removeChildFramesRecursively(frame);
|
2019-12-16 15:56:11 -08:00
|
|
|
frame._onDetached();
|
|
|
|
this._frames.delete(frame._id);
|
2020-11-02 13:06:54 -08:00
|
|
|
if (!this._page.isClosed())
|
|
|
|
this._page.emit(Page.Events.FrameDetached, frame);
|
2019-12-16 15:56:11 -08:00
|
|
|
}
|
2019-12-16 16:32:04 -08:00
|
|
|
|
2020-01-03 12:59:27 -08:00
|
|
|
private _inflightRequestFinished(request: network.Request) {
|
2022-07-01 12:49:43 -07:00
|
|
|
const frame = request.frame()!;
|
2020-03-10 11:39:35 -07:00
|
|
|
if (request._isFavicon)
|
2020-01-13 13:33:25 -08:00
|
|
|
return;
|
2020-01-03 12:59:27 -08:00
|
|
|
if (!frame._inflightRequests.has(request))
|
|
|
|
return;
|
|
|
|
frame._inflightRequests.delete(request);
|
|
|
|
if (frame._inflightRequests.size === 0)
|
2020-04-20 16:52:26 -07:00
|
|
|
frame._startNetworkIdleTimer();
|
2019-12-16 16:32:04 -08:00
|
|
|
}
|
|
|
|
|
2020-01-03 12:59:27 -08:00
|
|
|
private _inflightRequestStarted(request: network.Request) {
|
2022-07-01 12:49:43 -07:00
|
|
|
const frame = request.frame()!;
|
2020-03-10 11:39:35 -07:00
|
|
|
if (request._isFavicon)
|
2020-01-13 13:33:25 -08:00
|
|
|
return;
|
2020-01-03 12:59:27 -08:00
|
|
|
frame._inflightRequests.add(request);
|
|
|
|
if (frame._inflightRequests.size === 1)
|
2020-04-20 16:52:26 -07:00
|
|
|
frame._stopNetworkIdleTimer();
|
2019-12-16 16:32:04 -08:00
|
|
|
}
|
2020-01-27 16:51:52 -08:00
|
|
|
|
|
|
|
interceptConsoleMessage(message: ConsoleMessage): boolean {
|
|
|
|
if (message.type() !== 'debug')
|
|
|
|
return false;
|
|
|
|
const tag = message.text();
|
|
|
|
const handler = this._consoleMessageTags.get(tag);
|
|
|
|
if (!handler)
|
|
|
|
return false;
|
|
|
|
this._consoleMessageTags.delete(tag);
|
|
|
|
handler();
|
|
|
|
return true;
|
|
|
|
}
|
2020-10-26 22:20:43 -07:00
|
|
|
|
|
|
|
clearWebSockets(frame: Frame) {
|
|
|
|
// TODO: attribute sockets to frames.
|
|
|
|
if (frame.parentFrame())
|
|
|
|
return;
|
|
|
|
this._webSockets.clear();
|
|
|
|
}
|
|
|
|
|
|
|
|
onWebSocketCreated(requestId: string, url: string) {
|
2021-02-09 09:00:00 -08:00
|
|
|
const ws = new network.WebSocket(this._page, url);
|
2020-10-26 22:20:43 -07:00
|
|
|
this._webSockets.set(requestId, ws);
|
|
|
|
}
|
|
|
|
|
|
|
|
onWebSocketRequest(requestId: string) {
|
|
|
|
const ws = this._webSockets.get(requestId);
|
2021-11-24 10:46:32 -08:00
|
|
|
if (ws && ws.markAsNotified())
|
2020-10-26 22:20:43 -07:00
|
|
|
this._page.emit(Page.Events.WebSocket, ws);
|
|
|
|
}
|
|
|
|
|
|
|
|
onWebSocketResponse(requestId: string, status: number, statusText: string) {
|
|
|
|
const ws = this._webSockets.get(requestId);
|
2020-11-02 14:09:58 -08:00
|
|
|
if (status < 400)
|
2020-10-26 22:20:43 -07:00
|
|
|
return;
|
|
|
|
if (ws)
|
|
|
|
ws.error(`${statusText}: ${status}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
onWebSocketFrameSent(requestId: string, opcode: number, data: string) {
|
|
|
|
const ws = this._webSockets.get(requestId);
|
|
|
|
if (ws)
|
|
|
|
ws.frameSent(opcode, data);
|
|
|
|
}
|
|
|
|
|
|
|
|
webSocketFrameReceived(requestId: string, opcode: number, data: string) {
|
|
|
|
const ws = this._webSockets.get(requestId);
|
|
|
|
if (ws)
|
|
|
|
ws.frameReceived(opcode, data);
|
|
|
|
}
|
|
|
|
|
|
|
|
webSocketClosed(requestId: string) {
|
|
|
|
const ws = this._webSockets.get(requestId);
|
|
|
|
if (ws)
|
|
|
|
ws.closed();
|
|
|
|
this._webSockets.delete(requestId);
|
|
|
|
}
|
|
|
|
|
|
|
|
webSocketError(requestId: string, errorMessage: string): void {
|
|
|
|
const ws = this._webSockets.get(requestId);
|
|
|
|
if (ws)
|
|
|
|
ws.error(errorMessage);
|
|
|
|
}
|
2022-08-11 13:42:16 -07:00
|
|
|
|
|
|
|
private _fireInternalFrameNavigation(frame: Frame, event: NavigationEvent) {
|
|
|
|
frame.emit(Frame.Events.InternalNavigation, event);
|
|
|
|
}
|
2019-12-16 15:56:11 -08:00
|
|
|
}
|
|
|
|
|
2021-02-09 09:00:00 -08:00
|
|
|
export class Frame extends SdkObject {
|
2020-08-21 16:26:33 -07:00
|
|
|
static Events = {
|
2022-06-17 21:17:30 -07:00
|
|
|
InternalNavigation: 'internalnavigation',
|
2020-08-21 16:26:33 -07:00
|
|
|
AddLifecycle: 'addlifecycle',
|
|
|
|
RemoveLifecycle: 'removelifecycle',
|
|
|
|
};
|
|
|
|
|
2019-12-13 10:52:33 -08:00
|
|
|
_id: string;
|
2022-08-26 13:48:05 -07:00
|
|
|
_firedLifecycleEvents = new Set<types.LifecycleEvent>();
|
|
|
|
private _firedNetworkIdleSelf = false;
|
2020-07-06 15:58:27 -07:00
|
|
|
_currentDocument: DocumentInfo;
|
2021-04-29 09:28:19 -07:00
|
|
|
private _pendingDocument: DocumentInfo | undefined;
|
2019-12-11 07:17:32 -08:00
|
|
|
readonly _page: Page;
|
2020-01-13 13:33:25 -08:00
|
|
|
private _parentFrame: Frame | null;
|
2019-12-16 15:56:11 -08:00
|
|
|
_url = '';
|
2019-11-18 18:18:28 -08:00
|
|
|
private _detached = false;
|
2020-06-24 17:03:28 -07:00
|
|
|
private _contextData = new Map<types.World, ContextData>();
|
2019-11-27 16:02:31 -08:00
|
|
|
private _childFrames = new Set<Frame>();
|
2020-01-13 13:33:25 -08:00
|
|
|
_name = '';
|
2020-01-03 12:59:27 -08:00
|
|
|
_inflightRequests = new Set<network.Request>();
|
2020-04-20 16:52:26 -07:00
|
|
|
private _networkIdleTimer: NodeJS.Timer | undefined;
|
2020-01-27 16:51:52 -08:00
|
|
|
private _setContentCounter = 0;
|
2020-03-18 20:05:35 -07:00
|
|
|
readonly _detachedPromise: Promise<void>;
|
2020-02-10 18:35:47 -08:00
|
|
|
private _detachedCallback = () => {};
|
2022-03-15 14:13:45 -07:00
|
|
|
private _raceAgainstEvaluationStallingEventsPromises = new Set<ManualPromise<any>>();
|
2022-06-21 11:01:01 -07:00
|
|
|
readonly _redirectedNavigations = new Map<string, { url: string, gotoPromise: Promise<network.Response | null> }>(); // documentId -> data
|
2023-02-21 14:08:51 -08:00
|
|
|
readonly selectors: FrameSelectors;
|
2019-11-18 18:18:28 -08:00
|
|
|
|
2019-12-13 10:52:33 -08:00
|
|
|
constructor(page: Page, id: string, parentFrame: Frame | null) {
|
2021-04-20 23:03:56 -07:00
|
|
|
super(page, 'frame');
|
2021-02-09 09:00:00 -08:00
|
|
|
this.attribution.frame = this;
|
2019-12-13 10:52:33 -08:00
|
|
|
this._id = id;
|
2019-12-11 07:17:32 -08:00
|
|
|
this._page = page;
|
2019-11-18 18:18:28 -08:00
|
|
|
this._parentFrame = parentFrame;
|
2020-07-06 15:58:27 -07:00
|
|
|
this._currentDocument = { documentId: undefined, request: undefined };
|
2023-02-21 14:08:51 -08:00
|
|
|
this.selectors = new FrameSelectors(this);
|
2019-11-18 18:18:28 -08:00
|
|
|
|
2020-02-10 18:35:47 -08:00
|
|
|
this._detachedPromise = new Promise<void>(x => this._detachedCallback = x);
|
|
|
|
|
2022-12-27 17:22:44 -08:00
|
|
|
this._contextData.set('main', { contextPromise: new ManualPromise(), context: null });
|
|
|
|
this._contextData.set('utility', { contextPromise: new ManualPromise(), context: null });
|
2019-11-26 15:37:25 -08:00
|
|
|
this._setContext('main', null);
|
|
|
|
this._setContext('utility', null);
|
2019-11-18 18:18:28 -08:00
|
|
|
|
|
|
|
if (this._parentFrame)
|
|
|
|
this._parentFrame._childFrames.add(this);
|
2021-11-01 17:12:19 -07:00
|
|
|
|
|
|
|
this._firedLifecycleEvents.add('commit');
|
2022-05-04 20:52:50 +01:00
|
|
|
if (id !== kDummyFrameId)
|
|
|
|
this._startNetworkIdleTimer();
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
2021-11-05 10:06:04 -08:00
|
|
|
isDetached(): boolean {
|
|
|
|
return this._detached;
|
|
|
|
}
|
|
|
|
|
2022-08-26 13:48:05 -07:00
|
|
|
_onLifecycleEvent(event: RegularLifecycleEvent) {
|
2020-07-06 17:33:56 -07:00
|
|
|
if (this._firedLifecycleEvents.has(event))
|
|
|
|
return;
|
|
|
|
this._firedLifecycleEvents.add(event);
|
2022-08-26 13:48:05 -07:00
|
|
|
this.emit(Frame.Events.AddLifecycle, event);
|
|
|
|
if (this === this._page.mainFrame() && this._url !== 'about:blank')
|
|
|
|
debugLogger.log('api', ` "${event}" event fired`);
|
|
|
|
this._page.mainFrame()._recalculateNetworkIdle();
|
2020-07-06 17:33:56 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
_onClearLifecycle() {
|
2022-08-26 13:48:05 -07:00
|
|
|
for (const event of this._firedLifecycleEvents)
|
|
|
|
this.emit(Frame.Events.RemoveLifecycle, event);
|
2020-07-06 17:33:56 -07:00
|
|
|
this._firedLifecycleEvents.clear();
|
|
|
|
// Keep the current navigation request if any.
|
|
|
|
this._inflightRequests = new Set(Array.from(this._inflightRequests).filter(request => request === this._currentDocument.request));
|
|
|
|
this._stopNetworkIdleTimer();
|
|
|
|
if (this._inflightRequests.size === 0)
|
|
|
|
this._startNetworkIdleTimer();
|
2022-08-26 13:48:05 -07:00
|
|
|
this._page.mainFrame()._recalculateNetworkIdle(this);
|
2021-11-01 17:12:19 -07:00
|
|
|
this._onLifecycleEvent('commit');
|
2020-07-06 17:33:56 -07:00
|
|
|
}
|
|
|
|
|
2021-04-29 09:28:19 -07:00
|
|
|
setPendingDocument(documentInfo: DocumentInfo | undefined) {
|
|
|
|
this._pendingDocument = documentInfo;
|
|
|
|
if (documentInfo)
|
2021-08-19 18:20:15 -07:00
|
|
|
this._invalidateNonStallingEvaluations('Navigation interrupted the evaluation');
|
2021-04-29 09:28:19 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
pendingDocument(): DocumentInfo | undefined {
|
|
|
|
return this._pendingDocument;
|
|
|
|
}
|
|
|
|
|
2021-08-19 18:20:15 -07:00
|
|
|
_invalidateNonStallingEvaluations(message: string) {
|
2022-03-15 14:13:45 -07:00
|
|
|
if (!this._raceAgainstEvaluationStallingEventsPromises.size)
|
2021-04-29 09:28:19 -07:00
|
|
|
return;
|
2021-08-19 18:20:15 -07:00
|
|
|
const error = new Error(message);
|
2022-03-15 14:13:45 -07:00
|
|
|
for (const promise of this._raceAgainstEvaluationStallingEventsPromises)
|
|
|
|
promise.reject(error);
|
2021-04-29 09:28:19 -07:00
|
|
|
}
|
|
|
|
|
2022-03-15 14:13:45 -07:00
|
|
|
async raceAgainstEvaluationStallingEvents<T>(cb: () => Promise<T>): Promise<T> {
|
2021-04-29 09:28:19 -07:00
|
|
|
if (this._pendingDocument)
|
|
|
|
throw new Error('Frame is currently attempting a navigation');
|
2022-01-25 14:52:18 -07:00
|
|
|
if (this._page._frameManager._openedDialogs.size)
|
2021-08-19 18:20:15 -07:00
|
|
|
throw new Error('Open JavaScript dialog prevents evaluation');
|
2021-04-29 09:28:19 -07:00
|
|
|
|
2022-03-15 14:13:45 -07:00
|
|
|
const promise = new ManualPromise<T>();
|
|
|
|
this._raceAgainstEvaluationStallingEventsPromises.add(promise);
|
2021-04-29 09:28:19 -07:00
|
|
|
try {
|
|
|
|
return await Promise.race([
|
2022-03-15 14:13:45 -07:00
|
|
|
cb(),
|
|
|
|
promise
|
2021-04-29 09:28:19 -07:00
|
|
|
]);
|
|
|
|
} finally {
|
2022-03-15 14:13:45 -07:00
|
|
|
this._raceAgainstEvaluationStallingEventsPromises.delete(promise);
|
2021-04-29 09:28:19 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-15 14:13:45 -07:00
|
|
|
nonStallingRawEvaluateInExistingMainContext(expression: string): Promise<any> {
|
|
|
|
return this.raceAgainstEvaluationStallingEvents(() => {
|
|
|
|
const context = this._existingMainContext();
|
|
|
|
if (!context)
|
|
|
|
throw new Error('Frame does not yet have a main execution context');
|
|
|
|
return context.rawEvaluateJSON(expression);
|
|
|
|
});
|
|
|
|
}
|
2021-06-07 10:27:34 -07:00
|
|
|
|
2022-11-29 16:57:11 -08:00
|
|
|
nonStallingEvaluateInExistingContext(expression: string, isFunction: boolean | undefined, world: types.World): Promise<any> {
|
2022-03-15 14:13:45 -07:00
|
|
|
return this.raceAgainstEvaluationStallingEvents(() => {
|
|
|
|
const context = this._contextData.get(world)?.context;
|
|
|
|
if (!context)
|
|
|
|
throw new Error('Frame does not yet have the execution context');
|
2022-11-29 16:57:11 -08:00
|
|
|
return context.evaluateExpression(expression, { isFunction });
|
2022-03-15 14:13:45 -07:00
|
|
|
});
|
2021-06-07 10:27:34 -07:00
|
|
|
}
|
|
|
|
|
2022-08-26 13:48:05 -07:00
|
|
|
_recalculateNetworkIdle(frameThatAllowsRemovingNetworkIdle?: Frame) {
|
|
|
|
let isNetworkIdle = this._firedNetworkIdleSelf;
|
2020-07-06 17:33:56 -07:00
|
|
|
for (const child of this._childFrames) {
|
2022-08-26 13:48:05 -07:00
|
|
|
child._recalculateNetworkIdle(frameThatAllowsRemovingNetworkIdle);
|
|
|
|
// We require networkidle event to be fired in the whole frame subtree, and then consider it done.
|
|
|
|
if (!child._firedLifecycleEvents.has('networkidle'))
|
|
|
|
isNetworkIdle = false;
|
2020-07-06 17:33:56 -07:00
|
|
|
}
|
2022-08-26 13:48:05 -07:00
|
|
|
if (isNetworkIdle && !this._firedLifecycleEvents.has('networkidle')) {
|
|
|
|
this._firedLifecycleEvents.add('networkidle');
|
|
|
|
this.emit(Frame.Events.AddLifecycle, 'networkidle');
|
|
|
|
if (this === this._page.mainFrame() && this._url !== 'about:blank')
|
|
|
|
debugLogger.log('api', ` "networkidle" event fired`);
|
2020-07-06 17:33:56 -07:00
|
|
|
}
|
2022-08-26 13:48:05 -07:00
|
|
|
if (frameThatAllowsRemovingNetworkIdle !== this && this._firedLifecycleEvents.has('networkidle') && !isNetworkIdle) {
|
|
|
|
// Usually, networkidle is fired once and not removed after that.
|
|
|
|
// However, when we clear them right before a new commit, this is allowed for a particular frame.
|
|
|
|
this._firedLifecycleEvents.delete('networkidle');
|
|
|
|
this.emit(Frame.Events.RemoveLifecycle, 'networkidle');
|
2020-07-13 16:03:24 -07:00
|
|
|
}
|
2020-07-06 17:33:56 -07:00
|
|
|
}
|
|
|
|
|
2022-06-17 21:17:30 -07:00
|
|
|
async raceNavigationAction(progress: Progress, options: types.GotoOptions, action: () => Promise<network.Response | null>): Promise<network.Response | null> {
|
2021-02-25 10:00:54 -08:00
|
|
|
return Promise.race([
|
|
|
|
this._page._disconnectedPromise.then(() => { throw new Error('Navigation failed because page was closed!'); }),
|
|
|
|
this._page._crashedPromise.then(() => { throw new Error('Navigation failed because page crashed!'); }),
|
|
|
|
this._detachedPromise.then(() => { throw new Error('Navigating frame was detached!'); }),
|
2022-06-17 21:17:30 -07:00
|
|
|
action().catch(e => {
|
2022-06-21 11:01:01 -07:00
|
|
|
if (e instanceof NavigationAbortedError && e.documentId) {
|
|
|
|
const data = this._redirectedNavigations.get(e.documentId);
|
|
|
|
if (data) {
|
|
|
|
progress.log(`waiting for redirected navigation to "${data.url}"`);
|
|
|
|
return data.gotoPromise;
|
2022-06-17 21:17:30 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
throw e;
|
|
|
|
}),
|
2021-02-25 10:00:54 -08:00
|
|
|
]);
|
2020-09-14 16:43:17 -07:00
|
|
|
}
|
|
|
|
|
2022-06-21 11:01:01 -07:00
|
|
|
redirectNavigation(url: string, documentId: string, referer: string | undefined) {
|
|
|
|
const controller = new ProgressController(serverSideCallMetadata(), this);
|
|
|
|
const data = {
|
|
|
|
url,
|
|
|
|
gotoPromise: controller.run(progress => this._gotoAction(progress, url, { referer }), 0),
|
|
|
|
};
|
|
|
|
this._redirectedNavigations.set(documentId, data);
|
|
|
|
data.gotoPromise.finally(() => this._redirectedNavigations.delete(documentId));
|
2022-06-17 21:17:30 -07:00
|
|
|
}
|
|
|
|
|
2021-02-09 14:44:48 -08:00
|
|
|
async goto(metadata: CallMetadata, url: string, options: types.GotoOptions = {}): Promise<network.Response | null> {
|
2021-07-06 21:16:37 +02:00
|
|
|
const constructedNavigationURL = constructURLBasedOnBaseURL(this._page._browserContext._options.baseURL, url);
|
2021-02-25 10:00:54 -08:00
|
|
|
const controller = new ProgressController(metadata, this);
|
2021-07-06 21:16:37 +02:00
|
|
|
return controller.run(progress => this._goto(progress, constructedNavigationURL, options), this._page._timeoutSettings.navigationTimeout(options));
|
2021-02-25 10:00:54 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
private async _goto(progress: Progress, url: string, options: types.GotoOptions): Promise<network.Response | null> {
|
2022-06-17 21:17:30 -07:00
|
|
|
return this.raceNavigationAction(progress, options, async () => this._gotoAction(progress, url, options));
|
|
|
|
}
|
|
|
|
|
|
|
|
private async _gotoAction(progress: Progress, url: string, options: types.GotoOptions): Promise<network.Response | null> {
|
|
|
|
const waitUntil = verifyLifecycle('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);
|
|
|
|
progress.log(`navigating to "${url}", waiting until "${waitUntil}"`);
|
2022-07-07 15:28:20 -08:00
|
|
|
const headers = this._page.extraHTTPHeaders() || [];
|
2022-06-17 21:17:30 -07:00
|
|
|
const refererHeader = headers.find(h => h.name.toLowerCase() === 'referer');
|
|
|
|
let referer = refererHeader ? refererHeader.value : undefined;
|
|
|
|
if (options.referer !== undefined) {
|
|
|
|
if (referer !== undefined && referer !== options.referer)
|
|
|
|
throw new Error('"referer" is already specified as extra HTTP header');
|
|
|
|
referer = options.referer;
|
|
|
|
}
|
|
|
|
url = helper.completeUserURL(url);
|
|
|
|
|
|
|
|
const sameDocument = helper.waitForEvent(progress, this, Frame.Events.InternalNavigation, (e: NavigationEvent) => !e.newDocument);
|
|
|
|
const navigateResult = await this._page._delegate.navigateFrame(this, url, referer);
|
|
|
|
|
|
|
|
let event: NavigationEvent;
|
|
|
|
if (navigateResult.newDocumentId) {
|
|
|
|
sameDocument.dispose();
|
|
|
|
event = await helper.waitForEvent(progress, this, Frame.Events.InternalNavigation, (event: NavigationEvent) => {
|
|
|
|
// We are interested either in this specific document, or any other document that
|
|
|
|
// did commit and replaced the expected document.
|
|
|
|
return event.newDocument && (event.newDocument.documentId === navigateResult.newDocumentId || !event.error);
|
|
|
|
}).promise;
|
|
|
|
|
|
|
|
if (event.newDocument!.documentId !== navigateResult.newDocumentId) {
|
|
|
|
// This is just a sanity check. In practice, new navigation should
|
|
|
|
// cancel the previous one and report "request cancelled"-like error.
|
2022-06-21 11:01:01 -07:00
|
|
|
throw new NavigationAbortedError(navigateResult.newDocumentId, 'Navigation interrupted by another one');
|
2020-06-04 16:43:48 -07:00
|
|
|
}
|
2022-06-17 21:17:30 -07:00
|
|
|
if (event.error)
|
|
|
|
throw event.error;
|
|
|
|
} else {
|
|
|
|
event = await sameDocument.promise;
|
|
|
|
}
|
2020-07-07 15:22:05 -07:00
|
|
|
|
2022-08-26 13:48:05 -07:00
|
|
|
if (!this._firedLifecycleEvents.has(waitUntil))
|
2022-06-17 21:17:30 -07:00
|
|
|
await helper.waitForEvent(progress, this, Frame.Events.AddLifecycle, (e: types.LifecycleEvent) => e === waitUntil).promise;
|
2020-07-07 15:22:05 -07:00
|
|
|
|
2022-06-17 21:17:30 -07:00
|
|
|
const request = event.newDocument ? event.newDocument.request : undefined;
|
|
|
|
const response = request ? request._finalRequest().response() : null;
|
|
|
|
return response;
|
2020-02-10 18:35:47 -08:00
|
|
|
}
|
|
|
|
|
2022-08-12 13:48:47 -07:00
|
|
|
async _waitForNavigation(progress: Progress, requiresNewDocument: boolean, options: types.NavigateOptions): Promise<network.Response | null> {
|
2020-09-14 16:43:17 -07:00
|
|
|
const waitUntil = verifyLifecycle('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);
|
|
|
|
progress.log(`waiting for navigation until "${waitUntil}"`);
|
2020-07-07 15:22:05 -07:00
|
|
|
|
2022-06-17 21:17:30 -07:00
|
|
|
const navigationEvent: NavigationEvent = await helper.waitForEvent(progress, this, Frame.Events.InternalNavigation, (event: NavigationEvent) => {
|
2020-09-14 16:43:17 -07:00
|
|
|
// Any failed navigation results in a rejection.
|
|
|
|
if (event.error)
|
2020-08-19 13:27:58 -07:00
|
|
|
return true;
|
2022-08-12 13:48:47 -07:00
|
|
|
if (requiresNewDocument && !event.newDocument)
|
|
|
|
return false;
|
2020-09-14 16:43:17 -07:00
|
|
|
progress.log(` navigated to "${this._url}"`);
|
|
|
|
return true;
|
|
|
|
}).promise;
|
|
|
|
if (navigationEvent.error)
|
|
|
|
throw navigationEvent.error;
|
2020-07-07 15:22:05 -07:00
|
|
|
|
2022-08-26 13:48:05 -07:00
|
|
|
if (!this._firedLifecycleEvents.has(waitUntil))
|
2020-09-14 16:43:17 -07:00
|
|
|
await helper.waitForEvent(progress, this, Frame.Events.AddLifecycle, (e: types.LifecycleEvent) => e === waitUntil).promise;
|
2019-11-18 18:18:28 -08:00
|
|
|
|
2020-09-14 16:43:17 -07:00
|
|
|
const request = navigationEvent.newDocument ? navigationEvent.newDocument.request : undefined;
|
|
|
|
return request ? request._finalRequest().response() : null;
|
2020-06-04 16:43:48 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
async _waitForLoadState(progress: Progress, state: types.LifecycleEvent): Promise<void> {
|
2020-07-21 15:25:31 -07:00
|
|
|
const waitUntil = verifyLifecycle('state', state);
|
2022-08-26 13:48:05 -07:00
|
|
|
if (!this._firedLifecycleEvents.has(waitUntil))
|
2020-08-21 16:26:33 -07:00
|
|
|
await helper.waitForEvent(progress, this, Frame.Events.AddLifecycle, (e: types.LifecycleEvent) => e === waitUntil).promise;
|
2019-12-20 15:32:30 -08:00
|
|
|
}
|
|
|
|
|
2020-02-05 17:20:23 -08:00
|
|
|
async frameElement(): Promise<dom.ElementHandle> {
|
|
|
|
return this._page._delegate.getFrameElement(this);
|
|
|
|
}
|
|
|
|
|
2020-06-24 17:03:28 -07:00
|
|
|
_context(world: types.World): Promise<dom.FrameExecutionContext> {
|
2021-11-03 10:44:50 -07:00
|
|
|
return this._contextData.get(world)!.contextPromise.then(contextOrError => {
|
|
|
|
if (contextOrError instanceof js.ExecutionContext)
|
|
|
|
return contextOrError;
|
|
|
|
throw contextOrError;
|
|
|
|
});
|
2019-12-17 14:30:02 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
_mainContext(): Promise<dom.FrameExecutionContext> {
|
|
|
|
return this._context('main');
|
2019-11-26 15:37:25 -08:00
|
|
|
}
|
|
|
|
|
2021-04-29 09:28:19 -07:00
|
|
|
private _existingMainContext(): dom.FrameExecutionContext | null {
|
2021-03-01 12:20:04 -08:00
|
|
|
return this._contextData.get('main')?.context || null;
|
|
|
|
}
|
|
|
|
|
2019-12-12 21:11:52 -08:00
|
|
|
_utilityContext(): Promise<dom.FrameExecutionContext> {
|
2019-12-17 14:30:02 -08:00
|
|
|
return this._context('utility');
|
2019-11-28 12:50:52 -08:00
|
|
|
}
|
|
|
|
|
2023-05-31 14:08:44 -07:00
|
|
|
async evaluateExpression(expression: string, options: { isFunction?: boolean, exposeUtilityScript?: boolean, world?: types.World } = {}, arg?: any): Promise<any> {
|
|
|
|
const context = await this._context(options.world ?? 'main');
|
|
|
|
const value = await context.evaluateExpression(expression, options, arg);
|
2021-07-09 16:19:42 +02:00
|
|
|
return value;
|
|
|
|
}
|
|
|
|
|
2023-05-31 14:08:44 -07:00
|
|
|
async evaluateExpressionHandle(expression: string, options: { isFunction?: boolean, exposeUtilityScript?: boolean, world?: types.World } = {}, arg?: any): Promise<js.JSHandle<any>> {
|
|
|
|
const context = await this._context(options.world ?? 'main');
|
|
|
|
const value = await context.evaluateExpressionHandle(expression, options, arg);
|
2020-08-18 19:13:40 -07:00
|
|
|
return value;
|
2020-06-25 08:30:56 -07:00
|
|
|
}
|
|
|
|
|
2021-11-05 10:06:04 -08:00
|
|
|
async querySelector(selector: string, options: types.StrictOptions): Promise<dom.ElementHandle<Element> | null> {
|
2021-06-30 23:47:09 +05:30
|
|
|
debugLogger.log('api', ` finding element using the selector "${selector}"`);
|
2023-02-21 14:08:51 -08:00
|
|
|
return this.selectors.query(selector, options);
|
2019-12-18 14:28:16 -08:00
|
|
|
}
|
|
|
|
|
2022-12-27 13:39:35 -08:00
|
|
|
async waitForSelector(metadata: CallMetadata, selector: string, options: types.WaitForElementOptions, scope?: dom.ElementHandle): Promise<dom.ElementHandle<Element> | null> {
|
2021-02-09 14:44:48 -08:00
|
|
|
const controller = new ProgressController(metadata, this);
|
2020-06-01 08:54:18 -07:00
|
|
|
if ((options as any).visibility)
|
2020-05-04 11:03:44 -07:00
|
|
|
throw new Error('options.visibility is not supported, did you mean options.state?');
|
2020-06-01 08:54:18 -07:00
|
|
|
if ((options as any).waitFor && (options as any).waitFor !== 'visible')
|
2020-05-04 11:03:44 -07:00
|
|
|
throw new Error('options.waitFor is not supported, did you mean options.state?');
|
2020-06-01 08:54:18 -07:00
|
|
|
const { state = 'visible' } = options;
|
2020-05-04 11:03:44 -07:00
|
|
|
if (!['attached', 'detached', 'visible', 'hidden'].includes(state))
|
2020-07-21 15:25:31 -07:00
|
|
|
throw new Error(`state: expected one of (attached|detached|visible|hidden)`);
|
2021-02-09 14:44:48 -08:00
|
|
|
return controller.run(async progress => {
|
2022-11-04 15:19:16 -07:00
|
|
|
progress.log(`waiting for ${this._asLocator(selector)}${state === 'attached' ? '' : ' to be ' + state}`);
|
2022-12-27 13:39:35 -08:00
|
|
|
const promise = this.retryWithProgressAndTimeouts(progress, [0, 20, 50, 100, 100, 500], async continuePolling => {
|
2023-02-21 14:08:51 -08:00
|
|
|
const resolved = await this.selectors.resolveInjectedForSelector(selector, options, scope);
|
|
|
|
progress.throwIfAborted();
|
2023-03-31 10:54:07 -07:00
|
|
|
if (!resolved) {
|
|
|
|
if (state === 'hidden' || state === 'detached')
|
|
|
|
return null;
|
2022-12-27 13:39:35 -08:00
|
|
|
return continuePolling;
|
2023-03-31 10:54:07 -07:00
|
|
|
}
|
2022-12-27 13:39:35 -08:00
|
|
|
const result = await resolved.injected.evaluateHandle((injected, { info, root }) => {
|
|
|
|
const elements = injected.querySelectorAll(info.parsed, root || document);
|
|
|
|
const element: Element | undefined = elements[0];
|
|
|
|
const visible = element ? injected.isVisible(element) : false;
|
|
|
|
let log = '';
|
|
|
|
if (elements.length > 1) {
|
|
|
|
if (info.strict)
|
|
|
|
throw injected.strictModeViolationError(info.parsed, elements);
|
|
|
|
log = ` locator resolved to ${elements.length} elements. Proceeding with the first one: ${injected.previewNode(elements[0])}`;
|
|
|
|
} else if (element) {
|
|
|
|
log = ` locator resolved to ${visible ? 'visible' : 'hidden'} ${injected.previewNode(element)}`;
|
|
|
|
}
|
|
|
|
return { log, element, visible, attached: !!element };
|
|
|
|
}, { info: resolved.info, root: resolved.frame === this ? scope : undefined });
|
|
|
|
const { log, visible, attached } = await result.evaluate(r => ({ log: r.log, visible: r.visible, attached: r.attached }));
|
|
|
|
if (log)
|
|
|
|
progress.log(log);
|
|
|
|
const success = { attached, detached: !attached, visible, hidden: !visible }[state];
|
|
|
|
if (!success) {
|
2021-06-02 20:17:24 -07:00
|
|
|
result.dispose();
|
2022-12-27 13:39:35 -08:00
|
|
|
return continuePolling;
|
2021-06-02 20:17:24 -07:00
|
|
|
}
|
2023-04-18 14:11:46 -04:00
|
|
|
if (options.omitReturnValue) {
|
|
|
|
result.dispose();
|
|
|
|
return null;
|
|
|
|
}
|
2022-12-27 13:39:35 -08:00
|
|
|
const element = state === 'attached' || state === 'visible' ? await result.evaluateHandle(r => r.element) : null;
|
|
|
|
result.dispose();
|
|
|
|
if (!element)
|
|
|
|
return null;
|
2021-06-02 20:17:24 -07:00
|
|
|
if ((options as any).__testHookBeforeAdoptNode)
|
|
|
|
await (options as any).__testHookBeforeAdoptNode();
|
|
|
|
try {
|
2022-12-27 13:39:35 -08:00
|
|
|
return await element._adoptTo(await resolved.frame._mainContext());
|
2021-06-02 20:17:24 -07:00
|
|
|
} catch (e) {
|
2021-11-05 10:06:04 -08:00
|
|
|
return continuePolling;
|
2021-06-02 20:17:24 -07:00
|
|
|
}
|
2022-12-27 13:39:35 -08:00
|
|
|
});
|
|
|
|
return scope ? scope._context._raceAgainstContextDestroyed(promise) : promise;
|
2020-08-14 18:25:32 -07:00
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
2023-06-09 07:18:13 -07:00
|
|
|
async dispatchEvent(metadata: CallMetadata, selector: string, type: string, eventInit: Object = {}, options: types.QueryOnSelectorOptions = {}, scope?: dom.ElementHandle): Promise<void> {
|
2022-12-27 09:22:22 -08:00
|
|
|
await this._callOnElementOnceMatches(metadata, selector, (injectedScript, element, data) => {
|
|
|
|
injectedScript.dispatchEvent(element, data.type, data.eventInit);
|
2023-06-09 07:18:13 -07:00
|
|
|
}, { type, eventInit }, { mainWorld: true, ...options }, scope);
|
2020-04-23 14:58:37 -07:00
|
|
|
}
|
|
|
|
|
2023-06-09 07:18:13 -07:00
|
|
|
async evalOnSelector(selector: string, strict: boolean, expression: string, isFunction: boolean | undefined, arg: any, scope?: dom.ElementHandle): Promise<any> {
|
|
|
|
const handle = await this.selectors.query(selector, { strict }, scope);
|
2021-11-05 10:06:04 -08:00
|
|
|
if (!handle)
|
|
|
|
throw new Error(`Error: failed to find element matching selector "${selector}"`);
|
2023-05-31 14:08:44 -07:00
|
|
|
const result = await handle.evaluateExpression(expression, { isFunction }, arg);
|
2021-11-05 10:06:04 -08:00
|
|
|
handle.dispose();
|
|
|
|
return result;
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
2023-06-09 07:18:13 -07:00
|
|
|
async evalOnSelectorAll(selector: string, expression: string, isFunction: boolean | undefined, arg: any, scope?: dom.ElementHandle): Promise<any> {
|
|
|
|
const arrayHandle = await this.selectors.queryArrayInMainWorld(selector, scope);
|
2023-05-31 14:08:44 -07:00
|
|
|
const result = await arrayHandle.evaluateExpression(expression, { isFunction }, arg);
|
2021-11-05 10:06:04 -08:00
|
|
|
arrayHandle.dispose();
|
|
|
|
return result;
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
2023-05-22 19:44:44 -06:00
|
|
|
async maskSelectors(selectors: ParsedSelector[], color?: string): Promise<void> {
|
2022-02-15 08:05:05 -07:00
|
|
|
const context = await this._utilityContext();
|
|
|
|
const injectedScript = await context.injectedScript();
|
2023-05-22 19:44:44 -06:00
|
|
|
await injectedScript.evaluate((injected, { parsed, color }) => {
|
|
|
|
injected.maskSelectors(parsed, color);
|
|
|
|
}, { parsed: selectors, color: color });
|
2022-02-15 08:05:05 -07:00
|
|
|
}
|
|
|
|
|
2021-11-05 10:06:04 -08:00
|
|
|
async querySelectorAll(selector: string): Promise<dom.ElementHandle<Element>[]> {
|
2023-02-21 14:08:51 -08:00
|
|
|
return this.selectors.queryAll(selector);
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
2022-01-07 15:52:14 -08:00
|
|
|
async queryCount(selector: string): Promise<number> {
|
2023-02-21 14:08:51 -08:00
|
|
|
return await this.selectors.queryCount(selector);
|
2022-01-07 15:52:14 -08:00
|
|
|
}
|
|
|
|
|
2019-11-18 18:18:28 -08:00
|
|
|
async content(): Promise<string> {
|
2021-09-22 10:40:15 -07:00
|
|
|
try {
|
|
|
|
const context = await this._utilityContext();
|
|
|
|
return await context.evaluate(() => {
|
|
|
|
let retVal = '';
|
|
|
|
if (document.doctype)
|
|
|
|
retVal = new XMLSerializer().serializeToString(document.doctype);
|
|
|
|
if (document.documentElement)
|
|
|
|
retVal += document.documentElement.outerHTML;
|
|
|
|
return retVal;
|
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
if (js.isJavaScriptErrorInEvaluate(e) || isSessionClosedError(e))
|
|
|
|
throw e;
|
|
|
|
throw new Error(`Unable to retrieve content because the page is navigating and changing the content.`);
|
|
|
|
}
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
2021-02-09 14:44:48 -08:00
|
|
|
async setContent(metadata: CallMetadata, html: string, options: types.NavigateOptions = {}): Promise<void> {
|
2021-02-25 10:00:54 -08:00
|
|
|
const controller = new ProgressController(metadata, this);
|
2022-06-17 21:17:30 -07:00
|
|
|
return controller.run(async progress => {
|
|
|
|
await this.raceNavigationAction(progress, options, async () => {
|
|
|
|
const waitUntil = options.waitUntil === undefined ? 'load' : options.waitUntil;
|
|
|
|
progress.log(`setting frame content, waiting until "${waitUntil}"`);
|
|
|
|
const tag = `--playwright--set--content--${this._id}--${++this._setContentCounter}--`;
|
|
|
|
const context = await this._utilityContext();
|
|
|
|
const lifecyclePromise = new Promise((resolve, reject) => {
|
|
|
|
this._page._frameManager._consoleMessageTags.set(tag, () => {
|
|
|
|
// Clear lifecycle right after document.open() - see 'tag' below.
|
|
|
|
this._onClearLifecycle();
|
|
|
|
this._waitForLoadState(progress, waitUntil).then(resolve).catch(reject);
|
|
|
|
});
|
2020-06-04 16:43:48 -07:00
|
|
|
});
|
2022-06-17 21:17:30 -07:00
|
|
|
const contentPromise = context.evaluate(({ html, tag }) => {
|
|
|
|
window.stop();
|
|
|
|
document.open();
|
|
|
|
console.debug(tag); // eslint-disable-line no-console
|
|
|
|
document.write(html);
|
|
|
|
document.close();
|
|
|
|
}, { html, tag });
|
|
|
|
await Promise.all([contentPromise, lifecyclePromise]);
|
|
|
|
return null;
|
2020-02-10 18:35:47 -08:00
|
|
|
});
|
2022-06-17 21:17:30 -07:00
|
|
|
}, this._page._timeoutSettings.navigationTimeout(options));
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
name(): string {
|
|
|
|
return this._name || '';
|
|
|
|
}
|
|
|
|
|
|
|
|
url(): string {
|
|
|
|
return this._url;
|
|
|
|
}
|
|
|
|
|
2019-11-27 16:02:31 -08:00
|
|
|
parentFrame(): Frame | null {
|
2019-11-18 18:18:28 -08:00
|
|
|
return this._parentFrame;
|
|
|
|
}
|
|
|
|
|
2019-11-27 16:02:31 -08:00
|
|
|
childFrames(): Frame[] {
|
2019-11-18 18:18:28 -08:00
|
|
|
return Array.from(this._childFrames);
|
|
|
|
}
|
|
|
|
|
2020-12-14 15:27:02 -08:00
|
|
|
async addScriptTag(params: {
|
2020-08-18 18:46:56 -07:00
|
|
|
url?: string,
|
|
|
|
content?: string,
|
|
|
|
type?: string,
|
2019-11-27 16:02:31 -08:00
|
|
|
}): Promise<dom.ElementHandle> {
|
2019-11-26 08:57:53 -08:00
|
|
|
const {
|
|
|
|
url = null,
|
|
|
|
content = null,
|
|
|
|
type = ''
|
2020-12-14 15:27:02 -08:00
|
|
|
} = params;
|
2020-08-18 18:46:56 -07:00
|
|
|
if (!url && !content)
|
2019-12-11 13:51:03 -08:00
|
|
|
throw new Error('Provide an object with a `url`, `path` or `content` property');
|
|
|
|
|
|
|
|
const context = await this._mainContext();
|
|
|
|
return this._raceWithCSPError(async () => {
|
|
|
|
if (url !== null)
|
2021-03-18 01:47:07 +08:00
|
|
|
return (await context.evaluateHandle(addScriptUrl, { url, type })).asElement()!;
|
|
|
|
const result = (await context.evaluateHandle(addScriptContent, { content: content!, type })).asElement()!;
|
2020-04-17 08:51:54 -07:00
|
|
|
// Another round trip to the browser to ensure that we receive CSP error messages
|
|
|
|
// (if any) logged asynchronously in a separate task on the content main thread.
|
|
|
|
if (this._page._delegate.cspErrorsAsynchronousForInlineScipts)
|
2021-03-18 01:47:07 +08:00
|
|
|
await context.evaluate(() => true);
|
2020-04-17 08:51:54 -07:00
|
|
|
return result;
|
2019-12-11 13:51:03 -08:00
|
|
|
});
|
2019-11-26 08:57:53 -08:00
|
|
|
|
2020-12-14 15:27:02 -08:00
|
|
|
async function addScriptUrl(params: { url: string, type: string }): Promise<HTMLElement> {
|
2019-11-26 08:57:53 -08:00
|
|
|
const script = document.createElement('script');
|
2020-12-14 15:27:02 -08:00
|
|
|
script.src = params.url;
|
|
|
|
if (params.type)
|
|
|
|
script.type = params.type;
|
2019-11-26 08:57:53 -08:00
|
|
|
const promise = new Promise((res, rej) => {
|
|
|
|
script.onload = res;
|
2020-04-12 18:46:53 -07:00
|
|
|
script.onerror = e => rej(typeof e === 'string' ? new Error(e) : new Error(`Failed to load script at ${script.src}`));
|
2019-11-26 08:57:53 -08:00
|
|
|
});
|
|
|
|
document.head.appendChild(script);
|
|
|
|
await promise;
|
|
|
|
return script;
|
|
|
|
}
|
|
|
|
|
2020-12-14 15:27:02 -08:00
|
|
|
function addScriptContent(params: { content: string, type: string }): HTMLElement {
|
2019-11-26 08:57:53 -08:00
|
|
|
const script = document.createElement('script');
|
2020-12-14 15:27:02 -08:00
|
|
|
script.type = params.type || 'text/javascript';
|
|
|
|
script.text = params.content;
|
2019-11-26 08:57:53 -08:00
|
|
|
let error = null;
|
|
|
|
script.onerror = e => error = e;
|
|
|
|
document.head.appendChild(script);
|
|
|
|
if (error)
|
|
|
|
throw error;
|
|
|
|
return script;
|
|
|
|
}
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
2020-12-14 15:27:02 -08:00
|
|
|
async addStyleTag(params: { url?: string, content?: string }): Promise<dom.ElementHandle> {
|
2019-11-26 08:57:53 -08:00
|
|
|
const {
|
|
|
|
url = null,
|
|
|
|
content = null
|
2020-12-14 15:27:02 -08:00
|
|
|
} = params;
|
2020-08-18 18:46:56 -07:00
|
|
|
if (!url && !content)
|
2019-12-11 13:51:03 -08:00
|
|
|
throw new Error('Provide an object with a `url`, `path` or `content` property');
|
|
|
|
|
|
|
|
const context = await this._mainContext();
|
|
|
|
return this._raceWithCSPError(async () => {
|
|
|
|
if (url !== null)
|
2021-03-18 01:47:07 +08:00
|
|
|
return (await context.evaluateHandle(addStyleUrl, url)).asElement()!;
|
|
|
|
return (await context.evaluateHandle(addStyleContent, content!)).asElement()!;
|
2019-12-11 13:51:03 -08:00
|
|
|
});
|
2019-12-12 20:21:29 -08:00
|
|
|
|
2019-11-26 08:57:53 -08:00
|
|
|
async function addStyleUrl(url: string): Promise<HTMLElement> {
|
|
|
|
const link = document.createElement('link');
|
|
|
|
link.rel = 'stylesheet';
|
|
|
|
link.href = url;
|
|
|
|
const promise = new Promise((res, rej) => {
|
|
|
|
link.onload = res;
|
|
|
|
link.onerror = rej;
|
|
|
|
});
|
|
|
|
document.head.appendChild(link);
|
|
|
|
await promise;
|
|
|
|
return link;
|
|
|
|
}
|
|
|
|
|
|
|
|
async function addStyleContent(content: string): Promise<HTMLElement> {
|
|
|
|
const style = document.createElement('style');
|
|
|
|
style.type = 'text/css';
|
|
|
|
style.appendChild(document.createTextNode(content));
|
|
|
|
const promise = new Promise((res, rej) => {
|
|
|
|
style.onload = res;
|
|
|
|
style.onerror = rej;
|
|
|
|
});
|
|
|
|
document.head.appendChild(style);
|
|
|
|
await promise;
|
|
|
|
return style;
|
|
|
|
}
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
2019-12-11 13:51:03 -08:00
|
|
|
private async _raceWithCSPError(func: () => Promise<dom.ElementHandle>): Promise<dom.ElementHandle> {
|
|
|
|
const listeners: RegisteredListener[] = [];
|
2020-01-13 13:33:25 -08:00
|
|
|
let result: dom.ElementHandle;
|
2019-12-11 13:51:03 -08:00
|
|
|
let error: Error | undefined;
|
|
|
|
let cspMessage: ConsoleMessage | undefined;
|
2021-08-31 15:55:32 -07:00
|
|
|
const actionPromise = func().then(r => result = r).catch(e => error = e);
|
2021-02-03 13:49:25 -08:00
|
|
|
const errorPromise = new Promise<void>(resolve => {
|
2023-05-04 15:11:46 -07:00
|
|
|
listeners.push(eventsHelper.addEventListener(this._page._browserContext, BrowserContext.Events.Console, (message: ConsoleMessage) => {
|
|
|
|
if (message.page() === this._page && message.type() === 'error' && message.text().includes('Content Security Policy')) {
|
2019-12-11 13:51:03 -08:00
|
|
|
cspMessage = message;
|
|
|
|
resolve();
|
|
|
|
}
|
|
|
|
}));
|
|
|
|
});
|
|
|
|
await Promise.race([actionPromise, errorPromise]);
|
2021-07-07 21:14:16 +02:00
|
|
|
eventsHelper.removeEventListeners(listeners);
|
2019-12-11 13:51:03 -08:00
|
|
|
if (cspMessage)
|
|
|
|
throw new Error(cspMessage.text());
|
|
|
|
if (error)
|
|
|
|
throw error;
|
2020-01-13 13:33:25 -08:00
|
|
|
return result!;
|
2019-12-11 13:51:03 -08:00
|
|
|
}
|
|
|
|
|
2022-12-21 15:31:08 -08:00
|
|
|
async retryWithProgressAndTimeouts<R>(progress: Progress, timeouts: number[], action: (continuePolling: symbol) => Promise<R | symbol>): Promise<R> {
|
|
|
|
const continuePolling = Symbol('continuePolling');
|
|
|
|
timeouts = [0, ...timeouts];
|
|
|
|
let timeoutIndex = 0;
|
|
|
|
while (progress.isRunning()) {
|
|
|
|
const timeout = timeouts[Math.min(timeoutIndex++, timeouts.length - 1)];
|
|
|
|
if (timeout) {
|
|
|
|
// Make sure we react immediately upon page close or frame detach.
|
|
|
|
// We need this to show expected/received values in time.
|
|
|
|
await Promise.race([
|
|
|
|
this._page._disconnectedPromise,
|
|
|
|
this._page._crashedPromise,
|
|
|
|
this._detachedPromise,
|
|
|
|
new Promise(f => setTimeout(f, timeout)),
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
progress.throwIfAborted();
|
|
|
|
try {
|
|
|
|
const result = await action(continuePolling);
|
|
|
|
if (result === continuePolling)
|
|
|
|
continue;
|
|
|
|
return result as R;
|
|
|
|
} catch (e) {
|
|
|
|
if (this._isErrorThatCannotBeRetried(e))
|
|
|
|
throw e;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
progress.throwIfAborted();
|
|
|
|
return undefined as any;
|
|
|
|
}
|
|
|
|
|
|
|
|
private _isErrorThatCannotBeRetried(e: Error) {
|
|
|
|
// Always fail on JavaScript errors or when the main connection is closed.
|
|
|
|
if (js.isJavaScriptErrorInEvaluate(e) || isSessionClosedError(e))
|
|
|
|
return true;
|
|
|
|
// Certain errors opt-out of the retries, throw.
|
|
|
|
if (dom.isNonRecoverableDOMError(e) || isInvalidSelectorError(e))
|
|
|
|
return true;
|
|
|
|
// If the call is made on the detached frame - throw.
|
|
|
|
if (this.isDetached())
|
|
|
|
return true;
|
|
|
|
// Retry upon all other errors.
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2020-09-10 21:42:09 -07:00
|
|
|
private async _retryWithProgressIfNotConnected<R>(
|
|
|
|
progress: Progress,
|
|
|
|
selector: string,
|
2021-08-19 23:08:28 +02:00
|
|
|
strict: boolean | undefined,
|
2020-09-10 21:42:09 -07:00
|
|
|
action: (handle: dom.ElementHandle<Element>) => Promise<R | 'error:notconnected'>): Promise<R> {
|
2022-12-24 10:40:36 -08:00
|
|
|
progress.log(`waiting for ${this._asLocator(selector)}`);
|
|
|
|
return this.retryWithProgressAndTimeouts(progress, [0, 20, 50, 100, 100, 500], async continuePolling => {
|
2023-02-21 14:08:51 -08:00
|
|
|
const resolved = await this.selectors.resolveInjectedForSelector(selector, { strict });
|
|
|
|
progress.throwIfAborted();
|
2022-12-24 10:40:36 -08:00
|
|
|
if (!resolved)
|
|
|
|
return continuePolling;
|
|
|
|
const result = await resolved.injected.evaluateHandle((injected, { info }) => {
|
|
|
|
const elements = injected.querySelectorAll(info.parsed, document);
|
|
|
|
const element = elements[0] as Element | undefined;
|
|
|
|
let log = '';
|
|
|
|
if (elements.length > 1) {
|
|
|
|
if (info.strict)
|
|
|
|
throw injected.strictModeViolationError(info.parsed, elements);
|
|
|
|
log = ` locator resolved to ${elements.length} elements. Proceeding with the first one: ${injected.previewNode(elements[0])}`;
|
|
|
|
} else if (element) {
|
|
|
|
log = ` locator resolved to ${injected.previewNode(element)}`;
|
|
|
|
}
|
|
|
|
return { log, success: !!element, element };
|
|
|
|
}, { info: resolved.info });
|
|
|
|
const { log, success } = await result.evaluate(r => ({ log: r.log, success: r.success }));
|
|
|
|
if (log)
|
|
|
|
progress.log(log);
|
|
|
|
if (!success) {
|
|
|
|
result.dispose();
|
|
|
|
return continuePolling;
|
|
|
|
}
|
|
|
|
const element = await result.evaluateHandle(r => r.element) as dom.ElementHandle<Element>;
|
|
|
|
result.dispose();
|
2021-11-05 10:06:04 -08:00
|
|
|
try {
|
|
|
|
const result = await action(element);
|
|
|
|
if (result === 'error:notconnected') {
|
|
|
|
progress.log('element was detached from the DOM, retrying');
|
|
|
|
return continuePolling;
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
} finally {
|
|
|
|
element?.dispose();
|
2020-09-10 21:42:09 -07:00
|
|
|
}
|
2021-11-05 10:06:04 -08:00
|
|
|
});
|
2020-09-10 21:42:09 -07:00
|
|
|
}
|
|
|
|
|
2022-03-04 19:17:57 -07:00
|
|
|
async rafrafTimeoutScreenshotElementWithProgress(progress: Progress, selector: string, timeout: number, options: ScreenshotOptions): Promise<Buffer> {
|
2022-02-28 13:25:59 -07:00
|
|
|
return await this._retryWithProgressIfNotConnected(progress, selector, true /* strict */, async handle => {
|
|
|
|
await handle._frame.rafrafTimeout(timeout);
|
|
|
|
return await this._page._screenshotter.screenshotElement(progress, handle, options);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-02-09 14:44:48 -08:00
|
|
|
async click(metadata: CallMetadata, selector: string, options: types.MouseClickOptions & types.PointerActionWaitOptions & types.NavigatingActionWaitOptions) {
|
|
|
|
const controller = new ProgressController(metadata, this);
|
2020-09-17 09:32:54 -07:00
|
|
|
return controller.run(async progress => {
|
2021-08-19 23:08:28 +02:00
|
|
|
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._click(progress, options)));
|
2020-09-17 09:32:54 -07:00
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
2021-02-09 14:44:48 -08:00
|
|
|
async dblclick(metadata: CallMetadata, selector: string, options: types.MouseMultiClickOptions & types.PointerActionWaitOptions & types.NavigatingActionWaitOptions = {}) {
|
|
|
|
const controller = new ProgressController(metadata, this);
|
2020-09-17 09:32:54 -07:00
|
|
|
return controller.run(async progress => {
|
2021-08-19 23:08:28 +02:00
|
|
|
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._dblclick(progress, options)));
|
2020-09-17 09:32:54 -07:00
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
2021-08-03 13:12:34 -04:00
|
|
|
async dragAndDrop(metadata: CallMetadata, source: string, target: string, options: types.DragActionOptions & types.PointerActionWaitOptions & types.NavigatingActionWaitOptions = {}) {
|
2021-07-19 12:42:55 -05:00
|
|
|
const controller = new ProgressController(metadata, this);
|
|
|
|
await controller.run(async progress => {
|
2021-10-29 22:27:57 -07:00
|
|
|
dom.assertDone(await this._retryWithProgressIfNotConnected(progress, source, options.strict, async handle => {
|
2021-07-19 12:42:55 -05:00
|
|
|
return handle._retryPointerAction(progress, 'move and down', false, async point => {
|
|
|
|
await this._page.mouse.move(point.x, point.y);
|
|
|
|
await this._page.mouse.down();
|
|
|
|
}, {
|
|
|
|
...options,
|
2021-08-03 13:12:34 -04:00
|
|
|
position: options.sourcePosition,
|
2021-07-19 12:42:55 -05:00
|
|
|
timeout: progress.timeUntilDeadline(),
|
|
|
|
});
|
|
|
|
}));
|
2021-10-29 22:27:57 -07:00
|
|
|
dom.assertDone(await this._retryWithProgressIfNotConnected(progress, target, options.strict, async handle => {
|
2021-07-19 12:42:55 -05:00
|
|
|
return handle._retryPointerAction(progress, 'move and up', false, async point => {
|
|
|
|
await this._page.mouse.move(point.x, point.y);
|
|
|
|
await this._page.mouse.up();
|
|
|
|
}, {
|
|
|
|
...options,
|
2021-08-03 13:12:34 -04:00
|
|
|
position: options.targetPosition,
|
2021-07-19 12:42:55 -05:00
|
|
|
timeout: progress.timeUntilDeadline(),
|
|
|
|
});
|
|
|
|
}));
|
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
|
|
|
}
|
|
|
|
|
2021-02-09 14:44:48 -08:00
|
|
|
async tap(metadata: CallMetadata, selector: string, options: types.PointerActionWaitOptions & types.NavigatingActionWaitOptions) {
|
2023-01-27 15:51:57 -08:00
|
|
|
if (!this._page._browserContext._options.hasTouch)
|
|
|
|
throw new Error('The page does not support tap. Use hasTouch context option to enable touch support.');
|
2021-02-09 14:44:48 -08:00
|
|
|
const controller = new ProgressController(metadata, this);
|
2020-10-19 10:07:33 -07:00
|
|
|
return controller.run(async progress => {
|
2021-08-19 23:08:28 +02:00
|
|
|
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._tap(progress, options)));
|
2020-10-19 10:07:33 -07:00
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
|
|
|
}
|
|
|
|
|
2021-06-24 08:18:09 -07:00
|
|
|
async fill(metadata: CallMetadata, selector: string, value: string, options: types.NavigatingActionWaitOptions & { force?: boolean }) {
|
2021-02-09 14:44:48 -08:00
|
|
|
const controller = new ProgressController(metadata, this);
|
2020-09-17 09:32:54 -07:00
|
|
|
return controller.run(async progress => {
|
2021-08-19 23:08:28 +02:00
|
|
|
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._fill(progress, value, options)));
|
2020-09-17 09:32:54 -07:00
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
2021-12-03 10:22:50 -08:00
|
|
|
async focus(metadata: CallMetadata, selector: string, options: types.TimeoutOptions & types.StrictOptions = {}) {
|
2021-02-09 14:44:48 -08:00
|
|
|
const controller = new ProgressController(metadata, this);
|
2021-10-29 22:27:57 -07:00
|
|
|
await controller.run(async progress => {
|
2021-12-03 10:22:50 -08:00
|
|
|
dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._focus(progress)));
|
2021-10-29 22:27:57 -07:00
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
2022-10-25 06:10:40 -07:00
|
|
|
async blur(metadata: CallMetadata, selector: string, options: types.TimeoutOptions & types.StrictOptions = {}) {
|
|
|
|
const controller = new ProgressController(metadata, this);
|
|
|
|
await controller.run(async progress => {
|
|
|
|
dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._blur(progress)));
|
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
|
|
|
}
|
|
|
|
|
2023-06-09 07:18:13 -07:00
|
|
|
async textContent(metadata: CallMetadata, selector: string, options: types.QueryOnSelectorOptions = {}, scope?: dom.ElementHandle): Promise<string | null> {
|
|
|
|
return this._callOnElementOnceMatches(metadata, selector, (injected, element) => element.textContent, undefined, options, scope);
|
2020-05-18 17:58:23 -07:00
|
|
|
}
|
|
|
|
|
2023-06-09 07:18:13 -07:00
|
|
|
async innerText(metadata: CallMetadata, selector: string, options: types.QueryOnSelectorOptions = {}, scope?: dom.ElementHandle): Promise<string> {
|
2022-12-27 09:22:22 -08:00
|
|
|
return this._callOnElementOnceMatches(metadata, selector, (injectedScript, element) => {
|
2021-09-22 17:17:49 -07:00
|
|
|
if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml')
|
2022-12-27 09:22:22 -08:00
|
|
|
throw injectedScript.createStacklessError('Node is not an HTMLElement');
|
2021-09-22 17:17:49 -07:00
|
|
|
return (element as HTMLElement).innerText;
|
2023-06-09 07:18:13 -07:00
|
|
|
}, undefined, options, scope);
|
2020-05-18 17:58:23 -07:00
|
|
|
}
|
|
|
|
|
2023-06-09 07:18:13 -07:00
|
|
|
async innerHTML(metadata: CallMetadata, selector: string, options: types.QueryOnSelectorOptions = {}, scope?: dom.ElementHandle): Promise<string> {
|
|
|
|
return this._callOnElementOnceMatches(metadata, selector, (injected, element) => element.innerHTML, undefined, options, scope);
|
2020-05-18 17:58:23 -07:00
|
|
|
}
|
|
|
|
|
2023-06-09 07:18:13 -07:00
|
|
|
async getAttribute(metadata: CallMetadata, selector: string, name: string, options: types.QueryOnSelectorOptions = {}, scope?: dom.ElementHandle): Promise<string | null> {
|
|
|
|
return this._callOnElementOnceMatches(metadata, selector, (injected, element, data) => element.getAttribute(data.name), { name }, options, scope);
|
2020-05-18 17:58:23 -07:00
|
|
|
}
|
|
|
|
|
2023-06-09 07:18:13 -07:00
|
|
|
async inputValue(metadata: CallMetadata, selector: string, options: types.TimeoutOptions & types.StrictOptions = {}, scope?: dom.ElementHandle): Promise<string> {
|
2022-12-27 09:22:22 -08:00
|
|
|
return this._callOnElementOnceMatches(metadata, selector, (injectedScript, node) => {
|
|
|
|
const element = injectedScript.retarget(node, 'follow-label');
|
2021-12-02 10:31:06 -08:00
|
|
|
if (!element || (element.nodeName !== 'INPUT' && element.nodeName !== 'TEXTAREA' && element.nodeName !== 'SELECT'))
|
2022-12-27 09:22:22 -08:00
|
|
|
throw injectedScript.createStacklessError('Node is not an <input>, <textarea> or <select> element');
|
2021-09-22 17:17:49 -07:00
|
|
|
return (element as any).value;
|
2023-06-09 07:18:13 -07:00
|
|
|
}, undefined, options, scope);
|
2021-06-23 22:19:20 -07:00
|
|
|
}
|
|
|
|
|
2022-01-12 07:37:48 -08:00
|
|
|
async highlight(selector: string) {
|
2023-02-21 14:08:51 -08:00
|
|
|
const resolved = await this.selectors.resolveInjectedForSelector(selector);
|
|
|
|
if (!resolved)
|
2022-01-12 07:37:48 -08:00
|
|
|
return;
|
2023-02-21 14:08:51 -08:00
|
|
|
return await resolved.injected.evaluate((injected, { info }) => {
|
|
|
|
return injected.highlight(info.parsed);
|
|
|
|
}, { info: resolved.info });
|
2022-01-12 07:37:48 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
async hideHighlight() {
|
2022-03-15 14:13:45 -07:00
|
|
|
return this.raceAgainstEvaluationStallingEvents(async () => {
|
|
|
|
const context = await this._utilityContext();
|
|
|
|
const injectedScript = await context.injectedScript();
|
|
|
|
return await injectedScript.evaluate(injected => {
|
|
|
|
return injected.hideHighlight();
|
|
|
|
});
|
2022-01-12 07:37:48 -08:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-06-09 07:18:13 -07:00
|
|
|
private async _elementState(metadata: CallMetadata, selector: string, state: ElementStateWithoutStable, options: types.QueryOnSelectorOptions = {}, scope?: dom.ElementHandle): Promise<boolean> {
|
2022-12-27 09:22:22 -08:00
|
|
|
const result = await this._callOnElementOnceMatches(metadata, selector, (injected, element, data) => {
|
2021-09-23 16:46:46 -07:00
|
|
|
return injected.elementState(element, data.state);
|
2023-06-09 07:18:13 -07:00
|
|
|
}, { state }, options, scope);
|
2021-09-24 20:51:09 -07:00
|
|
|
return dom.throwRetargetableDOMError(result);
|
2021-02-10 12:36:26 -08:00
|
|
|
}
|
|
|
|
|
2023-06-09 07:18:13 -07:00
|
|
|
async isVisible(metadata: CallMetadata, selector: string, options: types.StrictOptions = {}, scope?: dom.ElementHandle): Promise<boolean> {
|
2021-02-09 14:44:48 -08:00
|
|
|
const controller = new ProgressController(metadata, this);
|
|
|
|
return controller.run(async progress => {
|
2022-11-04 15:19:16 -07:00
|
|
|
progress.log(` checking visibility of ${this._asLocator(selector)}`);
|
2023-06-09 07:18:13 -07:00
|
|
|
const resolved = await this.selectors.resolveInjectedForSelector(selector, options, scope);
|
2023-02-21 14:08:51 -08:00
|
|
|
if (!resolved)
|
2021-11-05 15:36:01 -08:00
|
|
|
return false;
|
2023-06-09 07:18:13 -07:00
|
|
|
return await resolved.injected.evaluate((injected, { info, root }) => {
|
|
|
|
const element = injected.querySelector(info.parsed, root || document, info.strict);
|
2022-07-28 14:09:36 -07:00
|
|
|
const state = element ? injected.elementState(element, 'visible') : false;
|
|
|
|
return state === 'error:notconnected' ? false : state;
|
2023-06-09 07:18:13 -07:00
|
|
|
}, { info: resolved.info, root: resolved.frame === this ? scope : undefined });
|
2023-05-10 16:56:59 -07:00
|
|
|
}, this._page._timeoutSettings.timeout({})).catch(e => {
|
|
|
|
if (js.isJavaScriptErrorInEvaluate(e) || isInvalidSelectorError(e) || isSessionClosedError(e))
|
|
|
|
throw e;
|
|
|
|
return false;
|
|
|
|
});
|
2021-01-08 12:27:54 -08:00
|
|
|
}
|
|
|
|
|
2023-06-09 07:18:13 -07:00
|
|
|
async isHidden(metadata: CallMetadata, selector: string, options: types.StrictOptions = {}, scope?: dom.ElementHandle): Promise<boolean> {
|
|
|
|
return !(await this.isVisible(metadata, selector, options, scope));
|
2021-01-08 12:27:54 -08:00
|
|
|
}
|
|
|
|
|
2023-06-09 07:18:13 -07:00
|
|
|
async isDisabled(metadata: CallMetadata, selector: string, options: types.QueryOnSelectorOptions = {}, scope?: dom.ElementHandle): Promise<boolean> {
|
|
|
|
return this._elementState(metadata, selector, 'disabled', options, scope);
|
2021-01-08 12:27:54 -08:00
|
|
|
}
|
|
|
|
|
2023-06-09 07:18:13 -07:00
|
|
|
async isEnabled(metadata: CallMetadata, selector: string, options: types.QueryOnSelectorOptions = {}, scope?: dom.ElementHandle): Promise<boolean> {
|
|
|
|
return this._elementState(metadata, selector, 'enabled', options, scope);
|
2021-01-08 12:27:54 -08:00
|
|
|
}
|
|
|
|
|
2023-06-09 07:18:13 -07:00
|
|
|
async isEditable(metadata: CallMetadata, selector: string, options: types.QueryOnSelectorOptions = {}, scope?: dom.ElementHandle): Promise<boolean> {
|
|
|
|
return this._elementState(metadata, selector, 'editable', options, scope);
|
2021-01-08 12:27:54 -08:00
|
|
|
}
|
|
|
|
|
2023-06-09 07:18:13 -07:00
|
|
|
async isChecked(metadata: CallMetadata, selector: string, options: types.QueryOnSelectorOptions = {}, scope?: dom.ElementHandle): Promise<boolean> {
|
|
|
|
return this._elementState(metadata, selector, 'checked', options, scope);
|
2021-01-08 17:36:17 -08:00
|
|
|
}
|
|
|
|
|
2022-10-07 12:43:48 -07:00
|
|
|
async hover(metadata: CallMetadata, selector: string, options: types.PointerActionOptions & types.PointerActionWaitOptions & types.NavigatingActionWaitOptions = {}) {
|
2021-02-09 14:44:48 -08:00
|
|
|
const controller = new ProgressController(metadata, this);
|
2020-09-17 09:32:54 -07:00
|
|
|
return controller.run(async progress => {
|
2021-08-19 23:08:28 +02:00
|
|
|
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._hover(progress, options)));
|
2020-09-17 09:32:54 -07:00
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
2021-06-24 08:18:09 -07:00
|
|
|
async selectOption(metadata: CallMetadata, selector: string, elements: dom.ElementHandle[], values: types.SelectOption[], options: types.NavigatingActionWaitOptions & types.ForceOptions = {}): Promise<string[]> {
|
2021-02-09 14:44:48 -08:00
|
|
|
const controller = new ProgressController(metadata, this);
|
2020-09-17 09:32:54 -07:00
|
|
|
return controller.run(async progress => {
|
2021-08-19 23:08:28 +02:00
|
|
|
return await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._selectOption(progress, elements, values, options));
|
2020-09-17 09:32:54 -07:00
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
2020-04-16 10:25:28 -07:00
|
|
|
}
|
|
|
|
|
2022-03-18 09:00:52 -07:00
|
|
|
async setInputFiles(metadata: CallMetadata, selector: string, items: InputFilesItems, options: types.NavigatingActionWaitOptions = {}): Promise<channels.FrameSetInputFilesResult> {
|
2021-02-09 14:44:48 -08:00
|
|
|
const controller = new ProgressController(metadata, this);
|
2020-09-17 09:32:54 -07:00
|
|
|
return controller.run(async progress => {
|
2022-03-18 09:00:52 -07:00
|
|
|
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._setInputFiles(progress, items, options)));
|
2020-09-17 09:32:54 -07:00
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
2021-02-09 14:44:48 -08:00
|
|
|
async type(metadata: CallMetadata, selector: string, text: string, options: { delay?: number } & types.NavigatingActionWaitOptions = {}) {
|
|
|
|
const controller = new ProgressController(metadata, this);
|
2020-09-17 09:32:54 -07:00
|
|
|
return controller.run(async progress => {
|
2021-08-19 23:08:28 +02:00
|
|
|
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._type(progress, text, options)));
|
2020-09-17 09:32:54 -07:00
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
2021-02-09 14:44:48 -08:00
|
|
|
async press(metadata: CallMetadata, selector: string, key: string, options: { delay?: number } & types.NavigatingActionWaitOptions = {}) {
|
|
|
|
const controller = new ProgressController(metadata, this);
|
2020-09-17 09:32:54 -07:00
|
|
|
return controller.run(async progress => {
|
2021-08-19 23:08:28 +02:00
|
|
|
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._press(progress, key, options)));
|
2020-09-17 09:32:54 -07:00
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
2020-03-06 09:38:08 -08:00
|
|
|
}
|
|
|
|
|
2021-02-09 14:44:48 -08:00
|
|
|
async check(metadata: CallMetadata, selector: string, options: types.PointerActionWaitOptions & types.NavigatingActionWaitOptions = {}) {
|
|
|
|
const controller = new ProgressController(metadata, this);
|
2020-09-17 09:32:54 -07:00
|
|
|
return controller.run(async progress => {
|
2021-08-19 23:08:28 +02:00
|
|
|
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._setChecked(progress, true, options)));
|
2020-09-17 09:32:54 -07:00
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
2020-02-04 14:39:11 -08:00
|
|
|
}
|
|
|
|
|
2021-02-09 14:44:48 -08:00
|
|
|
async uncheck(metadata: CallMetadata, selector: string, options: types.PointerActionWaitOptions & types.NavigatingActionWaitOptions = {}) {
|
|
|
|
const controller = new ProgressController(metadata, this);
|
2020-09-17 09:32:54 -07:00
|
|
|
return controller.run(async progress => {
|
2021-08-19 23:08:28 +02:00
|
|
|
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._setChecked(progress, false, options)));
|
2020-09-17 09:32:54 -07:00
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
2020-02-04 14:39:11 -08:00
|
|
|
}
|
|
|
|
|
2021-09-21 22:06:14 +02:00
|
|
|
async waitForTimeout(metadata: CallMetadata, timeout: number) {
|
|
|
|
const controller = new ProgressController(metadata, this);
|
|
|
|
return controller.run(async () => {
|
|
|
|
await new Promise(resolve => setTimeout(resolve, timeout));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-11-16 17:00:42 -08:00
|
|
|
async expect(metadata: CallMetadata, selector: string, options: FrameExpectParams): Promise<{ matches: boolean, received?: any, log?: string[], timedOut?: boolean }> {
|
2022-11-17 19:43:10 -08:00
|
|
|
let timeout = this._page._timeoutSettings.timeout(options);
|
|
|
|
const start = timeout > 0 ? monotonicTime() : 0;
|
2022-12-21 15:31:08 -08:00
|
|
|
const lastIntermediateResult: { received?: any, isSet: boolean } = { isSet: false };
|
|
|
|
const resultOneShot = await this._expectInternal(metadata, selector, options, true, timeout, lastIntermediateResult);
|
2022-11-17 19:43:10 -08:00
|
|
|
if (resultOneShot.matches !== options.isNot)
|
|
|
|
return resultOneShot;
|
|
|
|
if (timeout > 0) {
|
|
|
|
const elapsed = monotonicTime() - start;
|
|
|
|
timeout -= elapsed;
|
|
|
|
}
|
|
|
|
if (timeout < 0)
|
2023-02-10 14:59:21 -08:00
|
|
|
return { matches: options.isNot, log: metadata.log, timedOut: true, received: lastIntermediateResult.received };
|
2022-12-21 15:31:08 -08:00
|
|
|
return await this._expectInternal(metadata, selector, options, false, timeout, lastIntermediateResult);
|
2022-11-17 19:43:10 -08:00
|
|
|
}
|
|
|
|
|
2022-12-21 15:31:08 -08:00
|
|
|
private async _expectInternal(metadata: CallMetadata, selector: string, options: FrameExpectParams, oneShot: boolean, timeout: number, lastIntermediateResult: { received?: any, isSet: boolean }): Promise<{ matches: boolean, received?: any, log?: string[], timedOut?: boolean }> {
|
2021-09-23 16:46:46 -07:00
|
|
|
const controller = new ProgressController(metadata, this);
|
2022-12-21 15:31:08 -08:00
|
|
|
return controller.run(async progress => {
|
2023-04-03 15:05:40 -07:00
|
|
|
if (oneShot) {
|
2022-12-21 15:31:08 -08:00
|
|
|
progress.log(`${metadata.apiName}${timeout ? ` with timeout ${timeout}ms` : ''}`);
|
2023-04-03 15:05:40 -07:00
|
|
|
progress.log(`waiting for ${this._asLocator(selector)}`);
|
|
|
|
}
|
2022-12-21 15:31:08 -08:00
|
|
|
return await this.retryWithProgressAndTimeouts(progress, [100, 250, 500, 1000], async continuePolling => {
|
2023-02-21 14:08:51 -08:00
|
|
|
const selectorInFrame = await this.selectors.resolveFrameForSelector(selector, { strict: true });
|
2022-12-21 15:31:08 -08:00
|
|
|
progress.throwIfAborted();
|
|
|
|
|
|
|
|
const { frame, info } = selectorInFrame || { frame: this, info: undefined };
|
|
|
|
const world = options.expression === 'to.have.property' ? 'main' : (info?.world ?? 'utility');
|
|
|
|
const context = await frame._context(world);
|
|
|
|
const injected = await context.injectedScript();
|
|
|
|
progress.throwIfAborted();
|
|
|
|
|
2023-03-15 22:33:40 -07:00
|
|
|
const { log, matches, received, missingRecevied } = await injected.evaluate(async (injected, { info, options, callId }) => {
|
2022-12-21 15:31:08 -08:00
|
|
|
const elements = info ? injected.querySelectorAll(info.parsed, document) : [];
|
|
|
|
const isArray = options.expression === 'to.have.count' || options.expression.endsWith('.array');
|
|
|
|
let log = '';
|
|
|
|
if (isArray)
|
|
|
|
log = ` locator resolved to ${elements.length} element${elements.length === 1 ? '' : 's'}`;
|
|
|
|
else if (elements.length > 1)
|
|
|
|
throw injected.strictModeViolationError(info!.parsed, elements);
|
|
|
|
else if (elements.length)
|
|
|
|
log = ` locator resolved to ${injected.previewNode(elements[0])}`;
|
2023-03-15 22:33:40 -07:00
|
|
|
if (callId)
|
|
|
|
injected.markTargetElements(new Set(elements), callId);
|
2023-02-10 04:33:22 -08:00
|
|
|
return { log, ...(await injected.expect(elements[0], options, elements)) };
|
2023-03-15 22:33:40 -07:00
|
|
|
}, { info, options, callId: metadata.id });
|
2022-12-21 15:31:08 -08:00
|
|
|
|
|
|
|
if (log)
|
|
|
|
progress.log(log);
|
2023-02-10 14:59:21 -08:00
|
|
|
// Note: missingReceived avoids `unexpected value "undefined"` when element was not found.
|
|
|
|
if (matches === options.isNot && !missingRecevied) {
|
2022-12-21 15:31:08 -08:00
|
|
|
lastIntermediateResult.received = received;
|
|
|
|
lastIntermediateResult.isSet = true;
|
|
|
|
if (!Array.isArray(received))
|
|
|
|
progress.log(` unexpected value "${renderUnexpectedValue(options.expression, received)}"`);
|
|
|
|
}
|
|
|
|
if (!oneShot && matches === options.isNot) {
|
|
|
|
// Keep waiting in these cases:
|
|
|
|
// expect(locator).conditionThatDoesNotMatch
|
|
|
|
// expect(locator).not.conditionThatDoesMatch
|
|
|
|
return continuePolling;
|
|
|
|
}
|
|
|
|
return { matches, received };
|
|
|
|
});
|
2022-11-17 19:43:10 -08:00
|
|
|
}, oneShot ? 0 : timeout).catch(e => {
|
2021-10-20 12:01:05 -08:00
|
|
|
// Q: Why not throw upon isSessionClosedError(e) as in other places?
|
|
|
|
// A: We want user to receive a friendly message containing the last intermediate result.
|
2021-11-29 17:13:24 -08:00
|
|
|
if (js.isJavaScriptErrorInEvaluate(e) || isInvalidSelectorError(e))
|
2021-11-05 10:06:04 -08:00
|
|
|
throw e;
|
2022-11-16 17:00:42 -08:00
|
|
|
const result: { matches: boolean, received?: any, log?: string[], timedOut?: boolean } = { matches: options.isNot, log: metadata.log };
|
2022-12-21 15:31:08 -08:00
|
|
|
if (lastIntermediateResult.isSet)
|
|
|
|
result.received = lastIntermediateResult.received;
|
2023-04-03 15:06:13 -07:00
|
|
|
if (e instanceof TimeoutError)
|
2022-11-16 17:00:42 -08:00
|
|
|
result.timedOut = true;
|
|
|
|
return result;
|
2021-09-23 16:46:46 -07:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-04-29 14:53:53 -07:00
|
|
|
async _waitForFunctionExpression<R>(metadata: CallMetadata, expression: string, isFunction: boolean | undefined, arg: any, options: types.WaitForFunctionOptions, world: types.World = 'main'): Promise<js.SmartHandle<R>> {
|
2021-02-09 14:44:48 -08:00
|
|
|
const controller = new ProgressController(metadata, this);
|
2020-08-22 07:07:13 -07:00
|
|
|
if (typeof options.pollingInterval === 'number')
|
|
|
|
assert(options.pollingInterval > 0, 'Cannot poll with non-positive interval: ' + options.pollingInterval);
|
2021-02-04 08:45:59 -08:00
|
|
|
expression = js.normalizeEvaluationExpression(expression, isFunction);
|
2022-12-27 17:22:44 -08:00
|
|
|
return controller.run(async progress => {
|
|
|
|
return this.retryWithProgressAndTimeouts(progress, [100], async () => {
|
2023-02-03 10:01:23 -08:00
|
|
|
const context = world === 'main' ? await this._mainContext() : await this._utilityContext();
|
2022-12-27 17:22:44 -08:00
|
|
|
const injectedScript = await context.injectedScript();
|
|
|
|
const handle = await injectedScript.evaluateHandle((injected, { expression, isFunction, polling, arg }) => {
|
|
|
|
const predicate = (): R => {
|
2023-02-03 10:01:23 -08:00
|
|
|
// NOTE: make sure to use `globalThis.eval` instead of `self.eval` due to a bug with sandbox isolation
|
|
|
|
// in firefox.
|
|
|
|
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1814898
|
|
|
|
let result = globalThis.eval(expression);
|
2022-12-27 17:22:44 -08:00
|
|
|
if (isFunction === true) {
|
|
|
|
result = result(arg);
|
|
|
|
} else if (isFunction === false) {
|
|
|
|
result = result;
|
|
|
|
} else {
|
|
|
|
// auto detect.
|
|
|
|
if (typeof result === 'function')
|
|
|
|
result = result(arg);
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
};
|
|
|
|
|
|
|
|
let fulfill: (result: R) => void;
|
|
|
|
let reject: (error: Error) => void;
|
|
|
|
let aborted = false;
|
|
|
|
const result = new Promise<R>((f, r) => { fulfill = f; reject = r; });
|
|
|
|
|
|
|
|
const next = () => {
|
|
|
|
if (aborted)
|
|
|
|
return;
|
|
|
|
try {
|
|
|
|
const success = predicate();
|
|
|
|
if (success) {
|
|
|
|
fulfill(success);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (typeof polling !== 'number')
|
|
|
|
requestAnimationFrame(next);
|
|
|
|
else
|
|
|
|
setTimeout(next, polling);
|
|
|
|
} catch (e) {
|
|
|
|
reject(e);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
next();
|
|
|
|
return { result, abort: () => aborted = true };
|
|
|
|
}, { expression, isFunction, polling: options.pollingInterval, arg });
|
|
|
|
progress.cleanupWhenAborted(() => handle.evaluate(h => h.abort()).catch(() => {}));
|
|
|
|
return handle.evaluateHandle(h => h.result);
|
|
|
|
});
|
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
2019-12-18 18:11:02 -08:00
|
|
|
}
|
|
|
|
|
2021-04-29 14:53:53 -07:00
|
|
|
async waitForFunctionValueInUtility<R>(progress: Progress, pageFunction: js.Func1<any, R>) {
|
2021-04-07 07:01:38 +08:00
|
|
|
const expression = `() => {
|
|
|
|
const result = (${pageFunction})();
|
|
|
|
if (!result)
|
|
|
|
return result;
|
|
|
|
return JSON.stringify(result);
|
|
|
|
}`;
|
2022-03-17 17:27:33 -08:00
|
|
|
const handle = await this._waitForFunctionExpression(serverSideCallMetadata(), expression, true, undefined, { timeout: progress.timeUntilDeadline() }, 'utility');
|
2021-04-07 07:01:38 +08:00
|
|
|
return JSON.parse(handle.rawValue()) as R;
|
|
|
|
}
|
|
|
|
|
2019-11-18 18:18:28 -08:00
|
|
|
async title(): Promise<string> {
|
2019-11-26 15:37:25 -08:00
|
|
|
const context = await this._utilityContext();
|
2021-03-18 01:47:07 +08:00
|
|
|
return context.evaluate(() => document.title);
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
|
|
|
|
2022-02-28 13:25:59 -07:00
|
|
|
async rafrafTimeout(timeout: number): Promise<void> {
|
|
|
|
if (timeout === 0)
|
|
|
|
return;
|
|
|
|
const context = await this._utilityContext();
|
|
|
|
await Promise.all([
|
|
|
|
// wait for double raf
|
|
|
|
context.evaluate(() => new Promise(x => {
|
|
|
|
requestAnimationFrame(() => {
|
|
|
|
requestAnimationFrame(x);
|
|
|
|
});
|
|
|
|
})),
|
|
|
|
new Promise(fulfill => setTimeout(fulfill, timeout)),
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
2019-12-11 07:17:32 -08:00
|
|
|
_onDetached() {
|
2020-07-10 16:38:01 -07:00
|
|
|
this._stopNetworkIdleTimer();
|
2019-11-18 18:18:28 -08:00
|
|
|
this._detached = true;
|
2020-02-10 18:35:47 -08:00
|
|
|
this._detachedCallback();
|
2021-11-03 10:44:50 -07:00
|
|
|
const error = new Error('Frame was detached');
|
2019-12-12 21:11:52 -08:00
|
|
|
for (const data of this._contextData.values()) {
|
2021-11-03 10:44:50 -07:00
|
|
|
if (data.context)
|
|
|
|
data.context.contextDestroyed(error);
|
|
|
|
data.contextPromise.resolve(error);
|
2019-11-26 15:37:25 -08:00
|
|
|
}
|
2019-11-18 18:18:28 -08:00
|
|
|
if (this._parentFrame)
|
|
|
|
this._parentFrame._childFrames.delete(this);
|
|
|
|
this._parentFrame = null;
|
|
|
|
}
|
2019-11-26 15:37:25 -08:00
|
|
|
|
2023-06-09 07:18:13 -07:00
|
|
|
private async _callOnElementOnceMatches<T, R>(metadata: CallMetadata, selector: string, body: ElementCallback<T, R>, taskData: T, options: types.TimeoutOptions & types.StrictOptions & { mainWorld?: boolean } = {}, scope?: dom.ElementHandle): Promise<R> {
|
2022-12-27 09:22:22 -08:00
|
|
|
const callbackText = body.toString();
|
2021-09-22 17:17:49 -07:00
|
|
|
const controller = new ProgressController(metadata, this);
|
2021-11-17 17:28:30 -08:00
|
|
|
return controller.run(async progress => {
|
2022-11-04 15:19:16 -07:00
|
|
|
progress.log(`waiting for ${this._asLocator(selector)}`);
|
2023-06-09 07:18:13 -07:00
|
|
|
const promise = this.retryWithProgressAndTimeouts(progress, [0, 20, 50, 100, 100, 500], async continuePolling => {
|
|
|
|
const resolved = await this.selectors.resolveInjectedForSelector(selector, options, scope);
|
2023-02-21 14:08:51 -08:00
|
|
|
progress.throwIfAborted();
|
2022-12-27 09:22:22 -08:00
|
|
|
if (!resolved)
|
|
|
|
return continuePolling;
|
2023-06-09 07:18:13 -07:00
|
|
|
const { log, success, value } = await resolved.injected.evaluate((injected, { info, callbackText, taskData, callId, root }) => {
|
2022-12-27 09:22:22 -08:00
|
|
|
const callback = injected.eval(callbackText) as ElementCallback<T, R>;
|
2023-06-09 07:18:13 -07:00
|
|
|
const element = injected.querySelector(info.parsed, root || document, info.strict);
|
2022-12-27 09:22:22 -08:00
|
|
|
if (!element)
|
|
|
|
return { success: false };
|
|
|
|
const log = ` locator resolved to ${injected.previewNode(element)}`;
|
2023-03-15 22:33:40 -07:00
|
|
|
if (callId)
|
|
|
|
injected.markTargetElements(new Set([element]), callId);
|
2022-12-27 09:22:22 -08:00
|
|
|
return { log, success: true, value: callback(injected, element, taskData as T) };
|
2023-06-09 07:18:13 -07:00
|
|
|
}, { info: resolved.info, callbackText, taskData, callId: progress.metadata.id, root: resolved.frame === this ? scope : undefined });
|
2021-11-04 12:28:35 -08:00
|
|
|
|
2022-12-27 09:22:22 -08:00
|
|
|
if (log)
|
|
|
|
progress.log(log);
|
|
|
|
if (!success)
|
|
|
|
return continuePolling;
|
|
|
|
return value!;
|
|
|
|
});
|
2023-06-09 07:18:13 -07:00
|
|
|
return scope ? scope._context._raceAgainstContextDestroyed(promise) : promise;
|
2022-12-27 09:22:22 -08:00
|
|
|
}, this._page._timeoutSettings.timeout(options));
|
2020-06-26 16:32:42 -07:00
|
|
|
}
|
|
|
|
|
2020-06-24 17:03:28 -07:00
|
|
|
private _setContext(world: types.World, context: dom.FrameExecutionContext | null) {
|
|
|
|
const data = this._contextData.get(world)!;
|
2019-12-12 21:11:52 -08:00
|
|
|
data.context = context;
|
2022-12-27 17:22:44 -08:00
|
|
|
if (context)
|
2021-11-03 10:44:50 -07:00
|
|
|
data.contextPromise.resolve(context);
|
2022-12-27 17:22:44 -08:00
|
|
|
else
|
2021-11-03 10:44:50 -07:00
|
|
|
data.contextPromise = new ManualPromise();
|
2019-11-26 15:37:25 -08:00
|
|
|
}
|
|
|
|
|
2020-06-24 17:03:28 -07:00
|
|
|
_contextCreated(world: types.World, context: dom.FrameExecutionContext) {
|
|
|
|
const data = this._contextData.get(world)!;
|
2019-11-26 15:37:25 -08:00
|
|
|
// In case of multiple sessions to the same target, there's a race between
|
|
|
|
// connections so we might end up creating multiple isolated worlds.
|
|
|
|
// We can use either.
|
2021-11-03 10:44:50 -07:00
|
|
|
if (data.context) {
|
|
|
|
data.context.contextDestroyed(new Error('Execution context was destroyed, most likely because of a navigation'));
|
2020-06-24 17:03:28 -07:00
|
|
|
this._setContext(world, null);
|
2021-11-03 10:44:50 -07:00
|
|
|
}
|
2020-06-24 17:03:28 -07:00
|
|
|
this._setContext(world, context);
|
2019-11-26 15:37:25 -08:00
|
|
|
}
|
|
|
|
|
2019-12-12 21:11:52 -08:00
|
|
|
_contextDestroyed(context: dom.FrameExecutionContext) {
|
2021-11-03 10:44:50 -07:00
|
|
|
// Sometimes we get this after detach, in which case we should not reset
|
|
|
|
// our already destroyed contexts to something that will never resolve.
|
|
|
|
if (this._detached)
|
|
|
|
return;
|
|
|
|
context.contextDestroyed(new Error('Execution context was destroyed, most likely because of a navigation'));
|
2020-06-24 17:03:28 -07:00
|
|
|
for (const [world, data] of this._contextData) {
|
2019-12-12 21:11:52 -08:00
|
|
|
if (data.context === context)
|
2020-06-24 17:03:28 -07:00
|
|
|
this._setContext(world, null);
|
2019-11-26 15:37:25 -08:00
|
|
|
}
|
|
|
|
}
|
2020-04-20 16:52:26 -07:00
|
|
|
|
|
|
|
_startNetworkIdleTimer() {
|
|
|
|
assert(!this._networkIdleTimer);
|
2020-11-19 19:20:53 -08:00
|
|
|
// We should not start a timer and report networkidle in detached frames.
|
|
|
|
// This happens at least in Firefox for child frames, where we may get requestFinished
|
|
|
|
// after the frame was detached - probably a race in the Firefox itself.
|
|
|
|
if (this._firedLifecycleEvents.has('networkidle') || this._detached)
|
2020-04-20 16:52:26 -07:00
|
|
|
return;
|
2022-08-26 13:48:05 -07:00
|
|
|
this._networkIdleTimer = setTimeout(() => {
|
|
|
|
this._firedNetworkIdleSelf = true;
|
|
|
|
this._page.mainFrame()._recalculateNetworkIdle();
|
|
|
|
}, 500);
|
2020-04-20 16:52:26 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
_stopNetworkIdleTimer() {
|
|
|
|
if (this._networkIdleTimer)
|
|
|
|
clearTimeout(this._networkIdleTimer);
|
|
|
|
this._networkIdleTimer = undefined;
|
2022-10-25 13:35:18 -07:00
|
|
|
this._firedNetworkIdleSelf = false;
|
2020-04-20 16:52:26 -07:00
|
|
|
}
|
2020-09-07 15:50:25 -07:00
|
|
|
|
2021-09-08 14:27:05 -07:00
|
|
|
async extendInjectedScript(source: string, arg?: any): Promise<js.JSHandle> {
|
|
|
|
const context = await this._context('main');
|
2021-05-18 16:40:24 +00:00
|
|
|
const injectedScriptHandle = await context.injectedScript();
|
2021-09-27 18:58:08 +02:00
|
|
|
return injectedScriptHandle.evaluateHandle((injectedScript, { source, arg }) => {
|
2020-09-07 15:50:25 -07:00
|
|
|
return injectedScript.extend(source, arg);
|
|
|
|
}, { source, arg });
|
|
|
|
}
|
2021-11-04 12:28:35 -08:00
|
|
|
|
2022-09-07 19:15:04 -07:00
|
|
|
async resetStorageForCurrentOriginBestEffort(newStorage: channels.OriginStorage | undefined) {
|
2022-08-04 15:01:34 -07:00
|
|
|
const context = await this._utilityContext();
|
2022-09-07 19:15:04 -07:00
|
|
|
await context.evaluate(async ({ ls }) => {
|
|
|
|
// Clean DOMStorage.
|
2022-08-04 15:01:34 -07:00
|
|
|
sessionStorage.clear();
|
|
|
|
localStorage.clear();
|
|
|
|
|
2022-09-07 19:15:04 -07:00
|
|
|
// Add new DOM Storage values.
|
|
|
|
for (const entry of ls || [])
|
|
|
|
localStorage[entry.name] = entry.value;
|
|
|
|
|
2022-08-04 15:01:34 -07:00
|
|
|
// Clean Service Workers
|
2022-09-06 12:48:40 -07:00
|
|
|
const registrations = navigator.serviceWorker ? await navigator.serviceWorker.getRegistrations() : [];
|
2023-01-06 17:02:40 -08:00
|
|
|
await Promise.all(registrations.map(async r => {
|
|
|
|
// Heuristic for service workers that stalled during main script fetch or importScripts:
|
|
|
|
// Waiting for them to finish unregistering takes ages so we do not await.
|
|
|
|
// However, they will unregister immediately after fetch finishes and should not affect next page load.
|
|
|
|
// Unfortunately, loading next page in Chromium still takes 5 seconds waiting for
|
|
|
|
// some operation on this bogus service worker to finish.
|
|
|
|
if (!r.installing && !r.waiting && !r.active)
|
|
|
|
r.unregister().catch(() => {});
|
|
|
|
else
|
|
|
|
await r.unregister().catch(() => {});
|
|
|
|
}));
|
2022-08-04 15:01:34 -07:00
|
|
|
|
|
|
|
// Clean IndexedDB
|
|
|
|
for (const db of await indexedDB.databases?.() || []) {
|
|
|
|
// Do not wait for the callback - it is called on timer in Chromium (slow).
|
|
|
|
if (db.name)
|
|
|
|
indexedDB.deleteDatabase(db.name!);
|
|
|
|
}
|
2022-09-07 19:15:04 -07:00
|
|
|
}, { ls: newStorage?.localStorage }).catch(() => {});
|
2022-08-04 15:01:34 -07:00
|
|
|
}
|
2022-10-18 19:39:58 -04:00
|
|
|
|
|
|
|
private _asLocator(selector: string) {
|
2023-06-01 17:54:43 -07:00
|
|
|
return asLocator(this._page.attribution.playwright.options.sdkLanguage, selector);
|
2022-10-18 19:39:58 -04:00
|
|
|
}
|
2019-11-18 18:18:28 -08:00
|
|
|
}
|
2019-12-03 10:51:41 -08:00
|
|
|
|
2020-06-05 10:06:59 -07:00
|
|
|
class SignalBarrier {
|
2020-06-03 11:23:24 -07:00
|
|
|
private _progress: Progress | null;
|
2020-03-05 14:47:04 -08:00
|
|
|
private _protectCount = 0;
|
2021-08-29 11:21:06 -07:00
|
|
|
private _promise = new ManualPromise<void>();
|
2020-03-05 14:47:04 -08:00
|
|
|
|
2020-06-03 11:23:24 -07:00
|
|
|
constructor(progress: Progress | null) {
|
|
|
|
this._progress = progress;
|
2020-03-05 14:47:04 -08:00
|
|
|
this.retain();
|
|
|
|
}
|
|
|
|
|
2021-08-29 11:21:06 -07:00
|
|
|
waitFor(): PromiseLike<void> {
|
2020-03-05 14:47:04 -08:00
|
|
|
this.release();
|
|
|
|
return this._promise;
|
|
|
|
}
|
|
|
|
|
2020-04-16 13:09:24 -07:00
|
|
|
async addFrameNavigation(frame: Frame) {
|
2021-03-18 05:47:51 +08:00
|
|
|
// Auto-wait top-level navigations only.
|
|
|
|
if (frame.parentFrame())
|
|
|
|
return;
|
2020-03-05 14:47:04 -08:00
|
|
|
this.retain();
|
2022-06-17 21:17:30 -07:00
|
|
|
const waiter = helper.waitForEvent(null, frame, Frame.Events.InternalNavigation, (e: NavigationEvent) => {
|
|
|
|
if (!e.isPublic)
|
|
|
|
return false;
|
2020-07-07 15:22:05 -07:00
|
|
|
if (!e.error && this._progress)
|
2020-08-17 14:12:31 -07:00
|
|
|
this._progress.log(` navigated to "${frame._url}"`);
|
2020-07-07 15:22:05 -07:00
|
|
|
return true;
|
|
|
|
});
|
2020-06-04 16:43:48 -07:00
|
|
|
await Promise.race([
|
|
|
|
frame._page._disconnectedPromise,
|
2020-06-25 09:53:56 -07:00
|
|
|
frame._page._crashedPromise,
|
2020-06-04 16:43:48 -07:00
|
|
|
frame._detachedPromise,
|
2020-07-07 15:22:05 -07:00
|
|
|
waiter.promise,
|
2020-06-04 16:43:48 -07:00
|
|
|
]).catch(e => {});
|
2020-07-07 15:22:05 -07:00
|
|
|
waiter.dispose();
|
2020-03-05 14:47:04 -08:00
|
|
|
this.release();
|
|
|
|
}
|
|
|
|
|
|
|
|
retain() {
|
|
|
|
++this._protectCount;
|
|
|
|
}
|
|
|
|
|
|
|
|
release() {
|
|
|
|
--this._protectCount;
|
2020-05-13 17:20:33 -07:00
|
|
|
if (!this._protectCount)
|
2021-08-29 11:21:06 -07:00
|
|
|
this._promise.resolve();
|
2020-03-05 14:47:04 -08:00
|
|
|
}
|
|
|
|
}
|
2020-03-18 20:05:35 -07:00
|
|
|
|
2020-07-21 15:25:31 -07:00
|
|
|
function verifyLifecycle(name: string, waitUntil: types.LifecycleEvent): types.LifecycleEvent {
|
2020-07-07 15:22:05 -07:00
|
|
|
if (waitUntil as unknown === 'networkidle0')
|
|
|
|
waitUntil = 'networkidle';
|
|
|
|
if (!types.kLifecycleEvents.has(waitUntil))
|
2021-11-01 17:12:19 -07:00
|
|
|
throw new Error(`${name}: expected one of (load|domcontentloaded|networkidle|commit)`);
|
2020-07-07 15:22:05 -07:00
|
|
|
return waitUntil;
|
|
|
|
}
|
2022-12-21 15:31:08 -08:00
|
|
|
|
|
|
|
function renderUnexpectedValue(expression: string, received: any): string {
|
|
|
|
if (expression === 'to.be.checked')
|
|
|
|
return received ? 'checked' : 'unchecked';
|
|
|
|
if (expression === 'to.be.unchecked')
|
|
|
|
return received ? 'unchecked' : 'checked';
|
|
|
|
if (expression === 'to.be.visible')
|
|
|
|
return received ? 'visible' : 'hidden';
|
|
|
|
if (expression === 'to.be.hidden')
|
|
|
|
return received ? 'hidden' : 'visible';
|
|
|
|
if (expression === 'to.be.enabled')
|
|
|
|
return received ? 'enabled' : 'disabled';
|
|
|
|
if (expression === 'to.be.disabled')
|
|
|
|
return received ? 'disabled' : 'enabled';
|
|
|
|
if (expression === 'to.be.editable')
|
|
|
|
return received ? 'editable' : 'readonly';
|
|
|
|
if (expression === 'to.be.readonly')
|
|
|
|
return received ? 'readonly' : 'editable';
|
|
|
|
if (expression === 'to.be.empty')
|
|
|
|
return received ? 'empty' : 'not empty';
|
|
|
|
if (expression === 'to.be.focused')
|
|
|
|
return received ? 'focused' : 'not focused';
|
|
|
|
return received;
|
|
|
|
}
|