forked from sorribas/phantom-render-stream
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphantom-process.js
More file actions
251 lines (208 loc) · 6.2 KB
/
phantom-process.js
File metadata and controls
251 lines (208 loc) · 6.2 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
// Code to be run by PhantomJS.
// The docs for these modules are here: http://phantomjs.org/api/
// Note that the 'fs' module here has a different API than the one in node.js core.
var webpage = require('webpage');
var system = require('system');
var page = createWebPage();
function createWebPage (id) {
var page = webpage.create();
page.id = id;
page.log = function(message) {
var json = JSON.stringify({
id: page.id,
log: message
});
console.log(json);
}
page.onConsoleMessage = function (msg, lineNum, sourceId) {
page.log({
type: 'consoleMessage',
data: {
msg: msg,
lineNum: lineNum,
sourceId: sourceId
}
});
};
page.onError = function (msg, trace) {
page.log({
type: 'error',
data: {
msg: msg,
trace: trace
}
});
};
page.onResourceError = function (resourceError) {
page.log({
type: 'resourceError',
data: {
resourceError: resourceError
}
});
};
page.onResourceTimeout = function(request) {
page.log({
type: 'resourceTimeout',
data: {
request: request
}
});
};
return page;
}
var forcePrintMedia = function() {
page.evaluate(function() {
var findPrintMedia = function() {
var styles = [];
Array.prototype.slice.call(document.querySelectorAll('style')).forEach(function(el) {
styles.push(el.innerText);
});
Array.prototype.slice.call(document.querySelectorAll('link')).forEach(function(el) {
if (el.rel && el.rel.indexOf('stylesheet') === -1) return;
try {
// try-catch is just precaution (we already set web-security to no)
var xhr = new XMLHttpRequest();
// 99.99% of the cases we just hit the cache so no real io
xhr.open('GET', el.href, false);
xhr.send(null);
styles.push(xhr.responseText);
} catch (err) {
// do nothing
}
});
var style = styles.join('\n');
return style.split('@media print').slice(1).filter(function(text) {
return text.indexOf('attr(href)') === -1;
}).map(function(text) {
var lvl = 0;
var from = text.indexOf('{');
for (var i = from; i < text.length; i++) {
if (text[i] === '{') lvl++;
if (text[i] === '}') lvl--;
if (lvl === 0) break;
}
return text.substring(from+1, i-1);
}).join('\n');
};
var div = document.createElement('div');
div.innerHTML = '<style>\n'+findPrintMedia()+'\n</style>';
document.body.appendChild(div);
document.body.style.backgroundImage = 'none';
document.body.style.backgroundColor = 'white';
});
};
var renders = 0, maxRenders = 500;
var loop = function() {
var line = system.stdin.readLine();
if (!line.trim()) return phantom.exit(0);
try {
line = JSON.parse(line);
} catch (err) {
return phantom.exit(1);
}
if (!page) page = createWebPage(line.id);
else page.id = line.id;
if (line.cookies && line.cookies.length > 0) {
line.cookies.forEach(function (c) {
phantom.addCookie(c);
});
}
// inject polyfills or other scripts if necessary
if (line.injectJs && line.injectJs.length > 0) {
page.onInitialized = function () {
line.injectJs.forEach(function (path) {
page.log({
type: 'injectedScript',
data: {path: path}
});
page.injectJs(path);
});
};
}
if (line.maxRenders) maxRenders = line.maxRenders;
page.viewportSize = {
width: line.width || 1280,
height: line.height || 960
};
page.paperSize = line.paperSize ||
{
format: line.paperFormat || 'A4',
orientation: line.orientation || 'portrait',
margin: line.margin || '0cm'
};
if (line.userAgent) page.settings.userAgent = line.userAgent;
if (line.headers) page.customHeaders = line.headers;
if (line.crop) {
page.clipRect = {
width: line.crop.width || page.viewportSize.width,
height: line.crop.height || page.viewportSize.height,
top: line.crop.top || 0,
left: line.crop.left || 0
}
}
var onerror = function(message) {
page.log(message);
line.success = false;
console.log(JSON.stringify(line));
page = null;
loop();
}
page.open(line.url, function(requestStatus) {
if (requestStatus !== 'success') return onerror({
type: 'pageFetchError',
data: {status: requestStatus}
});
var render = function() {
setTimeout(function() {
if (line.printMedia) forcePrintMedia();
page.render(line.filename, {format:line.format || 'png', quality:line.quality || 100});
page = null;
line.success = true;
console.log(JSON.stringify(line));
if (maxRenders && renders++ >= maxRenders) return phantom.exit(0);
loop();
}, 0);
};
var waitAndRender = function() {
var timeout = setTimeout(function() {
page.onAlert('webpage-error');
}, line.timeout);
var rendered = false;
page.onAlert = function(msg) {
if (msg !== 'webpage-renderable' && msg !== 'webpage-error') return;
if (rendered) return;
rendered = true;
clearTimeout(timeout);
if (msg === 'webpage-renderable') render();
else onerror({
type: 'expectError',
data: {expects: line.expects}
});
};
page.evaluate(function(expects) {
if (window.renderable === expects) return alert('webpage-renderable');
if (window.renderable) return alert('webpage-error');
var renderable = false;
Object.defineProperty(window, 'renderable', {
get: function() {
return renderable;
},
set: function(val) {
renderable = val;
if (renderable === expects) alert('webpage-renderable');
else alert('webpage-error');
}
});
}, line.expects);
};
var renderable = page.evaluate(function() {
return window.renderable;
});
if (renderable === false && !line.expects) line.expects = true;
if (line.expects === renderable) return render();
if (line.expects) return waitAndRender();
render();
});
};
loop();