puppeteer/src/common/LifecycleWatcher.ts

264 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 { assert } from './assert.js';
import { helper, PuppeteerEventListener } from './helper.js';
import { TimeoutError } from './Errors.js';
import {
FrameManager,
Frame,
FrameManagerEmittedEvents,
} from './FrameManager.js';
import { HTTPRequest } from './HTTPRequest.js';
import { HTTPResponse } from './HTTPResponse.js';
import { NetworkManagerEmittedEvents } from './NetworkManager.js';
import { CDPSessionEmittedEvents } from './Connection.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'],
]);
const noop = (): void => {};
/**
* @internal
*/
export class LifecycleWatcher {
2022-06-13 09:16:25 +00:00
#expectedLifecycle: ProtocolLifeCycleEvent[];
#frameManager: FrameManager;
#frame: Frame;
#timeout: number;
#navigationRequest: HTTPRequest | null = null;
#eventListeners: PuppeteerEventListener[];
2022-06-13 09:16:25 +00:00
#sameDocumentNavigationCompleteCallback: (x?: Error) => void = noop;
#sameDocumentNavigationPromise = new Promise<Error | undefined>((fulfill) => {
this.#sameDocumentNavigationCompleteCallback = fulfill;
});
2022-06-13 09:16:25 +00:00
#lifecycleCallback: () => void = noop;
#lifecyclePromise: Promise<void> = new Promise((fulfill) => {
this.#lifecycleCallback = fulfill;
});
2022-06-13 09:16:25 +00:00
#newDocumentNavigationCompleteCallback: (x?: Error) => void = noop;
#newDocumentNavigationPromise: Promise<Error | undefined> = new Promise(
(fulfill) => {
2022-06-13 09:16:25 +00:00
this.#newDocumentNavigationCompleteCallback = fulfill;
}
);
2022-06-13 09:16:25 +00:00
#terminationCallback: (x?: Error) => void = noop;
#terminationPromise: Promise<Error | undefined> = new Promise((fulfill) => {
this.#terminationCallback = fulfill;
});
2022-06-13 09:16:25 +00:00
#timeoutPromise: Promise<TimeoutError | undefined>;
2022-06-13 09:16:25 +00:00
#maximumTimer?: NodeJS.Timeout;
#hasSameDocumentNavigation?: boolean;
#newDocumentNavigation?: boolean;
#swapped?: boolean;
2020-05-07 10:54:55 +00:00
constructor(
frameManager: FrameManager,
frame: Frame,
waitUntil: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[],
timeout: number
) {
if (Array.isArray(waitUntil)) waitUntil = waitUntil.slice();
else if (typeof waitUntil === 'string') waitUntil = [waitUntil];
2022-06-13 09:16:25 +00:00
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.#frameManager = frameManager;
this.#frame = frame;
this.#timeout = timeout;
this.#eventListeners = [
2020-05-07 10:54:55 +00:00
helper.addEventListener(
frameManager._client,
CDPSessionEmittedEvents.Disconnected,
2022-06-13 09:16:25 +00:00
this.#terminate.bind(
2022-06-09 17:00:50 +00:00
this,
new Error('Navigation failed because browser has disconnected!')
)
2020-05-07 10:54:55 +00:00
),
helper.addEventListener(
2022-06-13 09:16:25 +00:00
this.#frameManager,
FrameManagerEmittedEvents.LifecycleEvent,
2022-06-13 09:16:25 +00:00
this.#checkLifecycleComplete.bind(this)
2020-05-07 10:54:55 +00:00
),
helper.addEventListener(
2022-06-13 09:16:25 +00:00
this.#frameManager,
FrameManagerEmittedEvents.FrameNavigatedWithinDocument,
2022-06-13 09:16:25 +00:00
this.#navigatedWithinDocument.bind(this)
2020-05-07 10:54:55 +00:00
),
helper.addEventListener(
2022-06-13 09:16:25 +00:00
this.#frameManager,
FrameManagerEmittedEvents.FrameNavigated,
2022-06-13 09:16:25 +00:00
this.#navigated.bind(this)
),
helper.addEventListener(
2022-06-13 09:16:25 +00:00
this.#frameManager,
FrameManagerEmittedEvents.FrameSwapped,
2022-06-13 09:16:25 +00:00
this.#frameSwapped.bind(this)
),
2020-05-07 10:54:55 +00:00
helper.addEventListener(
2022-06-13 09:16:25 +00:00
this.#frameManager,
FrameManagerEmittedEvents.FrameDetached,
2022-06-13 09:16:25 +00:00
this.#onFrameDetached.bind(this)
2020-05-07 10:54:55 +00:00
),
helper.addEventListener(
2022-06-13 09:16:25 +00:00
this.#frameManager.networkManager(),
NetworkManagerEmittedEvents.Request,
2022-06-13 09:16:25 +00:00
this.#onRequest.bind(this)
2020-05-07 10:54:55 +00:00
),
];
2022-06-13 09:16:25 +00:00
this.#timeoutPromise = this.#createTimeoutPromise();
this.#checkLifecycleComplete();
}
2022-06-13 09:16:25 +00:00
#onRequest(request: HTTPRequest): void {
if (request.frame() !== this.#frame || !request.isNavigationRequest())
return;
2022-06-13 09:16:25 +00:00
this.#navigationRequest = request;
}
2022-06-13 09:16:25 +00:00
#onFrameDetached(frame: Frame): void {
if (this.#frame === frame) {
this.#terminationCallback.call(
2020-05-07 10:54:55 +00:00
null,
new Error('Navigating frame was detached')
);
return;
}
2022-06-13 09:16:25 +00:00
this.#checkLifecycleComplete();
}
async navigationResponse(): Promise<HTTPResponse | null> {
// We may need to wait for ExtraInfo events before the request is complete.
2022-06-13 09:16:25 +00:00
return this.#navigationRequest ? this.#navigationRequest.response() : null;
}
2022-06-13 09:16:25 +00:00
#terminate(error: Error): void {
this.#terminationCallback.call(null, error);
}
sameDocumentNavigationPromise(): Promise<Error | undefined> {
2022-06-13 09:16:25 +00:00
return this.#sameDocumentNavigationPromise;
}
newDocumentNavigationPromise(): Promise<Error | undefined> {
2022-06-13 09:16:25 +00:00
return this.#newDocumentNavigationPromise;
}
lifecyclePromise(): Promise<void> {
2022-06-13 09:16:25 +00:00
return this.#lifecyclePromise;
}
timeoutOrTerminationPromise(): Promise<Error | TimeoutError | undefined> {
2022-06-13 09:16:25 +00:00
return Promise.race([this.#timeoutPromise, this.#terminationPromise]);
}
2022-06-13 09:16:25 +00:00
async #createTimeoutPromise(): Promise<TimeoutError | undefined> {
if (!this.#timeout) return new Promise(noop);
2020-05-07 10:54:55 +00:00
const errorMessage =
2022-06-13 09:16:25 +00:00
'Navigation timeout of ' + this.#timeout + ' ms exceeded';
await new Promise(
(fulfill) => (this.#maximumTimer = setTimeout(fulfill, this.#timeout))
);
return new TimeoutError(errorMessage);
}
2022-06-13 09:16:25 +00:00
#navigatedWithinDocument(frame: Frame): void {
if (frame !== this.#frame) return;
this.#hasSameDocumentNavigation = true;
this.#checkLifecycleComplete();
}
2022-06-13 09:16:25 +00:00
#navigated(frame: Frame): void {
if (frame !== this.#frame) return;
this.#newDocumentNavigation = true;
this.#checkLifecycleComplete();
}
2022-06-13 09:16:25 +00:00
#frameSwapped(frame: Frame): void {
if (frame !== this.#frame) return;
this.#swapped = true;
this.#checkLifecycleComplete();
}
2022-06-13 09:16:25 +00:00
#checkLifecycleComplete(): void {
// We expect navigation to commit.
2022-06-13 09:16:25 +00:00
if (!checkLifecycle(this.#frame, this.#expectedLifecycle)) return;
this.#lifecycleCallback();
if (this.#hasSameDocumentNavigation)
this.#sameDocumentNavigationCompleteCallback();
if (this.#swapped || this.#newDocumentNavigation)
this.#newDocumentNavigationCompleteCallback();
2020-05-07 10:54:55 +00:00
function checkLifecycle(
frame: Frame,
expectedLifecycle: ProtocolLifeCycleEvent[]
): boolean {
for (const event of expectedLifecycle) {
2020-05-07 10:54:55 +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 {
2022-06-13 09:16:25 +00:00
helper.removeEventListeners(this.#eventListeners);
this.#maximumTimer !== undefined && clearTimeout(this.#maximumTimer);
}
}