-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathwaitForHelpers.ts
More file actions
139 lines (124 loc) · 3.47 KB
/
waitForHelpers.ts
File metadata and controls
139 lines (124 loc) · 3.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type {CdpPage} from 'puppeteer-core/internal/cdp/Page.js';
import {Page, Protocol} from 'puppeteer-core';
import {logger} from './logger.js';
async function waitForStableDom(
page: Page,
signal: AbortSignal,
): Promise<void> {
const stableDomObserver = await page.evaluateHandle(() => {
let timeoutId: ReturnType<typeof setTimeout>;
function callback() {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
domObserver.resolver.resolve();
domObserver.observer.disconnect();
}, 100);
}
const domObserver = {
resolver: Promise.withResolvers<void>(),
observer: new MutationObserver(callback),
};
// It's possible that the DOM is not gonna change so we
// need to start the timeout initially.
callback();
domObserver.observer.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
});
return domObserver;
});
signal.addEventListener('abort', async () => {
try {
await stableDomObserver.evaluate(observer => {
observer.observer.disconnect();
observer.resolver.resolve();
});
await stableDomObserver.dispose();
} catch {
// Ignored cleanup errors
}
});
return Promise.race([
stableDomObserver.evaluate(async observer => {
return await observer.resolver.promise;
}),
timeout(3000, signal).then(() => {
throw new Error('Timeout');
}),
]);
}
async function waitForNavigationStarted(page: CdpPage, signal: AbortSignal) {
// Currently Puppeteer does not have API
// For when a navigation is about to start
const navigationStartedPromise = new Promise<boolean>(resolve => {
const listener = (event: Protocol.Page.FrameStartedNavigatingEvent) => {
if (
[
'historySameDocument',
'historyDifferentDocument',
'sameDocument',
].includes(event.navigationType)
) {
resolve(false);
return;
}
resolve(true);
};
page._client().on('Page.frameStartedNavigating', listener);
signal.addEventListener('abort', () => {
resolve(false);
page._client().off('Page.frameStartedNavigating', listener);
});
});
return await Promise.race([
navigationStartedPromise,
timeout(100).then(() => false),
]);
}
function timeout(time: number, signal?: AbortSignal): Promise<void> {
return new Promise<void>(res => {
const id = setTimeout(res, time);
signal?.addEventListener('abort', () => {
res();
clearTimeout(id);
});
});
}
/**
* A wrapper that executes a action and waits for
* a potential navigation, after which it waits
* for the DOM to be stable before returning.
*/
export async function waitForEventsAfterAction(
page: Page,
callback: () => Promise<void>,
) {
const controller = new AbortController();
const navigationStartedPromise = waitForNavigationStarted(
page as unknown as CdpPage,
controller.signal,
);
await callback();
try {
const navigationStated = await navigationStartedPromise;
if (navigationStated) {
await page.waitForNavigation({
timeout: 3000,
signal: controller.signal,
});
}
// Wait for stable dom after navigation so we execute in
// the correct context
await waitForStableDom(page, controller.signal);
} catch (error) {
logger(error);
} finally {
controller.abort();
}
}