-
Notifications
You must be signed in to change notification settings - Fork 0
/
formInteraction.ts
53 lines (42 loc) · 1.64 KB
/
formInteraction.ts
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
import {setTimeout} from 'node:timers/promises';
import type {ElementHandle} from 'puppeteer';
import {getPageFromHandle} from './puppeteerUtils';
function getRandomUpTo(maxValue: number) {
return Math.random() * maxValue;
}
export async function focusElement(handle: ElementHandle, clickDwellTimeMs: number) {
const page = getPageFromHandle(handle)!;
await page.bringToFront();
await smoothScrollToElement(handle);
await handle.hover();
await handle.click({delay: clickDwellTimeMs});
}
async function smoothScrollToElement(handle: ElementHandle) {
await handle.evaluate(el => el.scrollIntoView({behavior: 'smooth', block: 'end', inline: 'end'}));
}
async function fillInputElement(elem: ElementHandle, text: string, options: FillTimesMs) {
await focusElement(elem, options.clickDwell);
const page = getPageFromHandle(elem)!;
for (const key of text) {
await elem.type(key, {delay: getRandomUpTo(options.keyDwell)});
await setTimeout(getRandomUpTo(options.betweenKeys));
}
await page.keyboard.press('Tab'); // Trigger blur
}
export async function fillPasswordField(elem: ElementHandle, password: string, options: FillTimesMs) {
await fillInputElement(elem, password, options);
}
export async function fillEmailField(
elem: ElementHandle, hostname: string, email: string, options: FillTimesMs) {
await fillInputElement(elem, email, options);
}
export async function submitField(elem: ElementHandle, clickDwellTimeMs: number) {
await focusElement(elem, clickDwellTimeMs);
const page = getPageFromHandle(elem)!;
await page.keyboard.press('Enter');
}
export interface FillTimesMs {
clickDwell: number;
keyDwell: number;
betweenKeys: number;
}