-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
60 lines (56 loc) · 1.49 KB
/
index.js
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
export default async function findElement(
tab,
selector,
text,
{timeout = 5000} = {},
) {
const {
puppeteer: {browser, page},
} = tab
try {
const [frame, elementHandle] = await Promise.race(
page.frames().map(async (frame) => [
frame,
text
? await frame.waitForFunction(
// eslint-disable-next-line no-new-func
new Function(`
const [selector, text] = arguments
return Array.from(document.querySelectorAll(selector))
.find(e => e.textContent.includes(text))
`),
{timeout},
selector,
text,
)
: await frame.waitForSelector(selector, {timeout}),
]),
)
const metadata = await frame.evaluate(
// eslint-disable-next-line no-new-func
new Function(`
const [element] = arguments
return {
attributes: Array.from(element.attributes).reduce(
(memo, attr) => Object.assign(memo, { [attr.name]: attr.value }),
{}
),
innerText: element.innerText,
textContent: element.textContent,
outerHTML: element.outerHTML
}
`),
elementHandle,
)
return {
...metadata,
puppeteer: {browser, page, frame, elementHandle},
}
} catch {
throw new Error(
`Could not find element with selector "${selector}"${
text ? ` and text "${text}"` : ''
}`,
)
}
}