-
Notifications
You must be signed in to change notification settings - Fork 0
/
phantom-function.js
60 lines (56 loc) · 1.41 KB
/
phantom-function.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
const phantom = require('phantom');
const waitFor = (page, selector) => {
var count = 0;
return new Promise(function evaluateFunc(resolve) {
page.evaluate(function(selector){
return document.querySelector(selector);
}, selector).then((result) => {
if(!!result) {
return resolve(true);
}
console.log('Count', count);
count += 1;
if(count > 3) {
return resolve(false);
}
return setTimeout(() => evaluateFunc(resolve), 500);
});
});
};
/**
* @param context {WebtaskContext}
*/
module.exports = function(context, req, res) {
var url = req.url.split('/phantom-function/')[1] || context.query.url;
if(!url) {
return res.end('No url provided.');
}
var instance, page, status, content, error;
phantom
.create()
.then((_instance) => {
instance = _instance;
return instance.createPage();
})
.then((_page) => {
page = _page;
return page.open(url);
})
.then((_status) => {
status = _status;
return page.property('content');
})
.then((_content) => {
content = _content;
res.writeHead(200, { 'Content-Type': 'text/html '});
res.end(content);
page.close();
instance.exit();
})
.catch((_error) => {
error = _error;
res.writeHead(400, { 'Content-Type': 'text/html '});
res.end(error);
instance && instance.exit();
});
};