-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
82 lines (69 loc) · 2.05 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const debug = require('debug')('prerender');
const puppeteer = require('puppeteer');
module.exports = function (source, options = {}) {
debug('Calling prerender function for page %s', source);
const chromeFlags = (options.length ? options : options.chromeFlags) || [];
const delayLaunch = options.delayLaunch || 0;
const delayPageLoad = options.delayPageLoad || 0;
const puppeteerOptions = options.puppeteerOptions || {};
if (chromeFlags.length) {
puppeteerOptions.args = chromeFlags;
}
debug(`Launching chrome in ${delayLaunch}ms`);
return wait(delayLaunch).then(() =>
chain(
'puppeteer.launch',
() => puppeteer.launch(puppeteerOptions),
'browser.newPage',
(browser) => browser.newPage(),
`adding console listeners`,
(page) => page.on('pageerror', options.onPageError || noop) || page,
`page.goto('${source}')`,
(page) => page.goto(source)
)
.then(([browser, page]) => chain(
`Waiting ${delayPageLoad}ms after page load event`,
() => page.waitFor(delayPageLoad),
'Extracting HTML from the page',
() => page.content(),
(result) => extractHtml(result),
'Terminating Chrome',
() => browser.close()
))
.then(
(results) => results.find(r => r && r.extractedHTML).extractedHTML
));
}
function extractHtml(result) {
debug('Got result from runtime');
return { extractedHTML: result };
}
function chain(...actions) {
const results = [];
let didCallAFunction = false;
return actions.reduce((promise, fnOrString) => {
return promise.then((previous) => {
if (typeof fnOrString === 'function') {
if (didCallAFunction) {
results.push(previous);
}
didCallAFunction = true;
return fnOrString(previous);
} else {
debug(fnOrString);
return previous;
}
});
}, Promise.resolve())
.then((last) => {
results.push(last);
return results;
});
}
function wait(time) {
if (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
return Promise.resolve();
}
function noop () {}