-
Notifications
You must be signed in to change notification settings - Fork 2
/
phantomjs-prerender.js
85 lines (67 loc) · 2.23 KB
/
phantomjs-prerender.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
83
84
85
'use strict';
var system = require('system');
if (system.args.length < 3) {
console.log("Missing arguments.");
phantom.exit(1);
}
var server = require('webserver').create();
var port = parseInt(system.args[1], 10);
var urlPrefix = system.args[2];
var renderHtml = function (url, cb) {
var page = require('webpage').create();
page.settings.loadImages = false;
page.settings.localToRemoteUrlAccessEnabled = true;
page.onCallback = function () {
cb(page.content);
page.close();
};
page.onConsoleMessage = function(msg, lineNum, sourceId) {
console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};
page.onError = function (msg, trace) {
var msgStack = ['ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
var functionName = t['function'];
msgStack.push(' -> ' + t.file + ': ' + t.line + (functionName ? ' (in function "' + functionName + '")' : ''));
});
}
console.error(msgStack.join('\n'));
};
page.onInitialized = function () {
page.evaluate(function () {
setTimeout(function () {
window.callPhantom();
}, 10000);
});
};
page.open(url);
};
var serverStarted = server.listen(port, function (request, response) {
var extensionMatch = /.*\.(\w+)$/;
var filesExtensions = /css|js|ico|png|jpg|jpeg|gif/;
var path = request.url.slice(1);
var extension = extensionMatch.exec(path);
if (extension && filesExtensions.test(extension[1])) {
// ignore files, only let through HTML content
// this prevents infinite loop of incorrect rendering
response.statusCode = 200;
response.close();
return;
}
var url = urlPrefix + path;
console.log(url);
renderHtml(url, function (html) {
response.statusCode = 200;
response.write(html);
response.close();
});
});
if (serverStarted) {
console.log('Listening on ' + port + '...');
console.log('Press Ctrl+C to stop.');
} else {
console.error('Could not start server on port: ' + port);
phantom.exit(1);
}