-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrender.js
164 lines (150 loc) · 5.39 KB
/
render.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
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
var phantom = require('node-phantom');
var ph;
var nconf;
function noop() {
}
function phantomCrashHandler(code, signal) {
console.warn('phantom crash: signal', signal);
// https://github.com/alexscheelmeyer/node-phantom/issues/80
// Убиваем себя, чтобы внешний скрипт мог нас перезапустить
process.exit(code ? 100 + code : 2);
}
exports.init = function(cfg, cb) {
nconf = cfg;
cb = cb || noop;
phantom.create(function(err, instance) {
ph = instance;
ph._phantom.on('exit', phantomCrashHandler);
cb();
}, {
parameters: nconf.get('phantom')
});
};
exports.exit = function(cb) {
cb = cb || noop;
if (ph) {
ph._phantom.removeListener('exit', phantomCrashHandler);
// https://github.com/alexscheelmeyer/node-phantom/issues/85
ph.exit(cb);
} else {
console.error('ERROR: No phantom instance');
cb();
}
};
exports.render = function(data, handler) {
ph.createPage(function(err, page) {
if (nconf.get('pageLog')) {
page.onConsoleMessage = function(msg) {
console.log('LOG:', msg);
};
page.onError = function(msg) {
console.error('ERROR:', msg);
};
}
new PageHandler(page, data, handler).open();
});
};
function PageHandler(page, data, handler) {
var status, statusText;
// https://github.com/ariya/phantomjs/issues/10185
page.onResourceReceived = function(response) {
// if (response.status !== null && response.stage === 'end') {
// console.log(response.url, response.status);
// }
// NB: Точное совпадение URL. Может поломаться из-за небольших различий типа слеша в конце
if (response.status !== null && response.stage === 'end' && response.url === data.url) {
status = response.status;
statusText = response.statusText;
}
};
// https://github.com/alexscheelmeyer/node-phantom/issues/83
// Хак! Не поддерживает вложенные свойства, но есть eval
page.setFn('EVIL_EVAL', 'page.settings.userAgent = "' + (data.userAgent || nconf.get('userAgent')) + '"');
function waitFor(testFx, onReady, timeOutMillis) {
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000,
start = new Date().getTime(),
condition = false,
interval = setInterval(function() {
var now = new Date().getTime();
if (((now - start) < maxtimeOutMillis) && !condition) {
condition = testFx();
} else {
onReady(condition);
clearInterval(interval);
}
}, 250);
}
function doRender() {
if (typeof data.selector === 'undefined' && data.width && data.height) {
page.set('viewportSize', {width: data.width, height: data.height});
}
page.evaluate(function(data) {
document.body.style.webkitTransform = "scale(" + data.zoom + ")";
document.body.style.webkitTransformOrigin = "0% 0%";
if (data.selector) {
var e = document.querySelector(data.selector);
if (e) {
return e.getBoundingClientRect();
}
}
}, function(err, clip) {
if (clip) {
if (clip.left < 0) {
clip.width += clip.left;
clip.left = 0;
}
if (clip.top < 0) {
clip.height += clip.top;
clip.top = 0;
}
page.set('clipRect', clip);
}
page.renderBase64('png', function(err, data) {
handler(true, data);
});
}, data);
}
function handleOpen(err, st) {
if (st !== 'success' || (status && status !== 200)) {
handler(false, {
error: 'open_fail',
message: 'Не удалось открыть страницу',
status: status,
statusText: statusText
});
return;
}
var waitResult = false;
waitFor(function() {
page.evaluate(function(check) {
// Специальная проверка на строковое значение
if (check && check !== 'undefined') {
return this[check] === true;
} else {
return (document.readyState === 'complete');
}
}, function(err, r) {
waitResult = r;
}, data.check);
return waitResult;
}, function(ready) {
if (ready) {
if (data.delay) {
setTimeout(doRender, data.delay);
} else {
doRender();
}
} else {
handler(false, {
error: 'timeout',
message: 'Превышен лимит ожидания'
});
}
}, data.timeout);
}
return {
open: function() {
page.open(data.url, handleOpen);
}
};
}