-
-
Notifications
You must be signed in to change notification settings - Fork 745
/
Copy pathwithUtils.js
49 lines (48 loc) · 1.62 KB
/
withUtils.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
const utils = require('./index')
/**
* Wrap a page with utilities.
*
* @param {Puppeteer.Page} page
*/
module.exports = page => ({
/**
* Simple `page.evaluate` replacement to preload utils
*/
evaluate: async function (mainFunction, ...args) {
return page.evaluate(
({ _utilsFns, _mainFunction, _args }) => {
// Add this point we cannot use our utililty functions as they're just strings, we need to materialize them first
const utils = Object.fromEntries(
Object.entries(_utilsFns).map(([key, value]) => [key, eval(value)]) // eslint-disable-line no-eval
)
utils.init()
return eval(_mainFunction)(utils, ..._args) // eslint-disable-line no-eval
},
{
_utilsFns: utils.stringifyFns(utils),
_mainFunction: mainFunction.toString(),
_args: args || []
}
)
},
/**
* Simple `page.evaluateOnNewDocument` replacement to preload utils
*/
evaluateOnNewDocument: async function (mainFunction, ...args) {
return page.evaluateOnNewDocument(
({ _utilsFns, _mainFunction, _args }) => {
// Add this point we cannot use our utililty functions as they're just strings, we need to materialize them first
const utils = Object.fromEntries(
Object.entries(_utilsFns).map(([key, value]) => [key, eval(value)]) // eslint-disable-line no-eval
)
utils.init()
return eval(_mainFunction)(utils, ..._args) // eslint-disable-line no-eval
},
{
_utilsFns: utils.stringifyFns(utils),
_mainFunction: mainFunction.toString(),
_args: args || []
}
)
}
})