puppeteer/packages/puppeteer-core/src/common/LifecycleWatcher.ts

274 lines
7.7 KiB
TypeScript
Raw Normal View History

/**
* Copyright 2019 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Protocol from 'devtools-protocol';
import {HTTPResponse} from '../api/HTTPResponse.js';
import {assert} from '../util/assert.js';
2023-05-31 21:36:19 +00:00
import {Deferred} from '../util/Deferred.js';
import {TimeoutError} from './Errors.js';
import {CDPFrame, FrameEmittedEvents} from './Frame.js';
import {HTTPRequest} from './HTTPRequest.js';
import {NetworkManager, NetworkManagerEmittedEvents} from './NetworkManager.js';
import {
addEventListener,
PuppeteerEventListener,
removeEventListeners,
} from './util.js';
/**
* @public
*/
2020-05-07 10:54:55 +00:00
export type PuppeteerLifeCycleEvent =
| 'load'
| 'domcontentloaded'
| 'networkidle0'
| 'networkidle2';
/**
* @public
*/
export type ProtocolLifeCycleEvent =
2020-05-07 10:54:55 +00:00
| 'load'
| 'DOMContentLoaded'
| 'networkIdle'
| 'networkAlmostIdle';
const puppeteerToProtocolLifecycle = new Map<
PuppeteerLifeCycleEvent,
ProtocolLifeCycleEvent
>([
['load', 'load'],
['domcontentloaded', 'DOMContentLoaded'],
['networkidle0', 'networkIdle'],
['networkidle2', 'networkAlmostIdle'],
]);
/**
* @internal
*/
export class LifecycleWatcher {
2022-06-13 09:16:25 +00:00
#expectedLifecycle: ProtocolLifeCycleEvent[];
#frame: CDPFrame;
2022-06-13 09:16:25 +00:00
#timeout: number;
#navigationRequest: HTTPRequest | null = null;
#eventListeners: PuppeteerEventListener[];
#initialLoaderId: string;
#terminationDeferred: Deferred<Error>;
2023-05-31 21:36:19 +00:00
#sameDocumentNavigationDeferred = Deferred.create<undefined>();
#lifecycleDeferred = Deferred.create<void>();
#newDocumentNavigationDeferred = Deferred.create<undefined>();
2022-06-13 09:16:25 +00:00
#hasSameDocumentNavigation?: boolean;
#swapped?: boolean;
#navigationResponseReceived?: Deferred<void>;
2020-05-07 10:54:55 +00:00
constructor(
networkManager: NetworkManager,
frame: CDPFrame,
2020-05-07 10:54:55 +00:00
waitUntil: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[],
timeout: number
) {
2022-06-14 11:55:35 +00:00
if (Array.isArray(waitUntil)) {
waitUntil = waitUntil.slice();
} else if (typeof waitUntil === 'string') {
waitUntil = [waitUntil];
}
this.#initialLoaderId = frame._loaderId;
this.#expectedLifecycle = waitUntil.map(value => {
const protocolEvent = puppeteerToProtocolLifecycle.get(value);
assert(protocolEvent, 'Unknown value for options.waitUntil: ' + value);
return protocolEvent as ProtocolLifeCycleEvent;
});
2022-06-13 09:16:25 +00:00
this.#frame = frame;
this.#timeout = timeout;
this.#eventListeners = [
addEventListener(
frame,
FrameEmittedEvents.LifecycleEvent,
2022-06-13 09:16:25 +00:00
this.#checkLifecycleComplete.bind(this)
2020-05-07 10:54:55 +00:00
),
addEventListener(
frame,
FrameEmittedEvents.FrameNavigatedWithinDocument,
2022-06-13 09:16:25 +00:00
this.#navigatedWithinDocument.bind(this)
2020-05-07 10:54:55 +00:00
),
addEventListener(
frame,
FrameEmittedEvents.FrameNavigated,
2022-06-13 09:16:25 +00:00
this.#navigated.bind(this)
),
addEventListener(
frame,
FrameEmittedEvents.FrameSwapped,
2022-06-13 09:16:25 +00:00
this.#frameSwapped.bind(this)
),
addEventListener(
2023-08-28 06:20:57 +00:00
frame,
FrameEmittedEvents.FrameSwappedByActivation,
this.#frameSwapped.bind(this)
),
addEventListener(
frame,
FrameEmittedEvents.FrameDetached,
2022-06-13 09:16:25 +00:00
this.#onFrameDetached.bind(this)
2020-05-07 10:54:55 +00:00
),
addEventListener(
networkManager,
NetworkManagerEmittedEvents.Request,
2022-06-13 09:16:25 +00:00
this.#onRequest.bind(this)
2020-05-07 10:54:55 +00:00
),
addEventListener(
networkManager,
NetworkManagerEmittedEvents.Response,
this.#onResponse.bind(this)
),
addEventListener(
networkManager,
NetworkManagerEmittedEvents.RequestFailed,
this.#onRequestFailed.bind(this)
),
];
this.#terminationDeferred = Deferred.create<Error>({
timeout: this.#timeout,
message: `Navigation timeout of ${this.#timeout} ms exceeded`,
});
2022-06-13 09:16:25 +00:00
this.#checkLifecycleComplete();
}
2022-06-13 09:16:25 +00:00
#onRequest(request: HTTPRequest): void {
2022-06-14 11:55:35 +00:00
if (request.frame() !== this.#frame || !request.isNavigationRequest()) {
return;
2022-06-14 11:55:35 +00:00
}
2022-06-13 09:16:25 +00:00
this.#navigationRequest = request;
// Resolve previous navigation response in case there are multiple
// navigation requests reported by the backend. This generally should not
// happen by it looks like it's possible.
this.#navigationResponseReceived?.resolve();
2023-05-31 21:36:19 +00:00
this.#navigationResponseReceived = Deferred.create();
if (request.response() !== null) {
this.#navigationResponseReceived?.resolve();
}
}
#onRequestFailed(request: HTTPRequest): void {
if (this.#navigationRequest?._requestId !== request._requestId) {
return;
}
this.#navigationResponseReceived?.resolve();
}
#onResponse(response: HTTPResponse): void {
if (this.#navigationRequest?._requestId !== response.request()._requestId) {
return;
}
this.#navigationResponseReceived?.resolve();
}
#onFrameDetached(frame: CDPFrame): void {
2022-06-13 09:16:25 +00:00
if (this.#frame === frame) {
this.#terminationDeferred.resolve(
2020-05-07 10:54:55 +00:00
new Error('Navigating frame was detached')
);
return;
}
2022-06-13 09:16:25 +00:00
this.#checkLifecycleComplete();
}
async navigationResponse(): Promise<HTTPResponse | null> {
// Continue with a possibly null response.
await this.#navigationResponseReceived?.valueOrThrow();
2022-06-13 09:16:25 +00:00
return this.#navigationRequest ? this.#navigationRequest.response() : null;
}
sameDocumentNavigationPromise(): Promise<Error | undefined> {
return this.#sameDocumentNavigationDeferred.valueOrThrow();
}
newDocumentNavigationPromise(): Promise<Error | undefined> {
return this.#newDocumentNavigationDeferred.valueOrThrow();
}
lifecyclePromise(): Promise<void> {
return this.#lifecycleDeferred.valueOrThrow();
}
terminationPromise(): Promise<Error | TimeoutError | undefined> {
return this.#terminationDeferred.valueOrThrow();
}
#navigatedWithinDocument(): void {
2022-06-13 09:16:25 +00:00
this.#hasSameDocumentNavigation = true;
this.#checkLifecycleComplete();
}
#navigated(navigationType: Protocol.Page.NavigationType): void {
if (navigationType === 'BackForwardCacheRestore') {
return this.#frameSwapped();
}
2022-06-13 09:16:25 +00:00
this.#checkLifecycleComplete();
}
#frameSwapped(): void {
2022-06-13 09:16:25 +00:00
this.#swapped = true;
this.#checkLifecycleComplete();
}
2022-06-13 09:16:25 +00:00
#checkLifecycleComplete(): void {
// We expect navigation to commit.
2022-06-14 11:55:35 +00:00
if (!checkLifecycle(this.#frame, this.#expectedLifecycle)) {
return;
}
this.#lifecycleDeferred.resolve();
2022-06-14 11:55:35 +00:00
if (this.#hasSameDocumentNavigation) {
this.#sameDocumentNavigationDeferred.resolve(undefined);
2022-06-14 11:55:35 +00:00
}
if (this.#swapped || this.#frame._loaderId !== this.#initialLoaderId) {
this.#newDocumentNavigationDeferred.resolve(undefined);
2022-06-14 11:55:35 +00:00
}
2020-05-07 10:54:55 +00:00
function checkLifecycle(
frame: CDPFrame,
2020-05-07 10:54:55 +00:00
expectedLifecycle: ProtocolLifeCycleEvent[]
): boolean {
for (const event of expectedLifecycle) {
2022-06-14 11:55:35 +00:00
if (!frame._lifecycleEvents.has(event)) {
return false;
}
}
for (const child of frame.childFrames()) {
if (
child._hasStartedLoading &&
!checkLifecycle(child, expectedLifecycle)
) {
return false;
}
}
return true;
}
}
dispose(): void {
removeEventListeners(this.#eventListeners);
this.#terminationDeferred.resolve(new Error('LifecycleWatcher disposed'));
}
}