forked from baudehlo/node-phantom-simple
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bridge.js
292 lines (251 loc) · 8.25 KB
/
bridge.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
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/*global phantom*/
/*eslint-disable strict*/
var webpage = require('webpage');
var webserver = require('webserver').create();
var system = require('system');
var pages = {};
var page_id = 1;
var callback_stack = [];
// Max interval without requests from master process
var WATCHDOG_TIMEOUT = 30000;
phantom.onError = function (msg, trace) {
var msgStack = [ 'PHANTOM ERROR: ' + msg ];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function + ')' : ''));
});
}
system.stderr.writeLine(msgStack.join('\n'));
phantom.exit(1);
};
var watchdog_timer_id = null;
// Kill phantom if parent disconnected
function watchdog_clear() {
clearTimeout(watchdog_timer_id);
watchdog_timer_id = setTimeout(function () {
// phantom.exit(0);
}, WATCHDOG_TIMEOUT);
}
function lookup(obj, key, value) {
// key can be either string or an array of strings
if (!(typeof obj === 'object')) {
return null;
}
if (typeof key === 'string') {
key = key.split('.');
}
if (!Array.isArray(key)) {
return null;
}
if (arguments.length > 2) {
if (key.length === 1) {
obj[key[0]] = value;
} else {
obj[key[0]] = lookup(typeof obj[key[0]] === 'object' ? obj[key[0]] : {}, key.slice(1), value);
}
return obj;
}
if (key.length === 1) {
return obj[key[0]];
}
return lookup(obj[key[0]], key.slice(1));
}
function page_open (res, page, args) {
page.open.apply(page, args.concat(function (success) {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.write(JSON.stringify({ data: success }));
res.close();
}));
}
function include_js (res, page, args) {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.write(JSON.stringify({ data: 'success' }));
page.includeJs.apply(page, args.concat(function () {
try {
res.write('');
res.close();
} catch (e) {
if (!/cannot call function of deleted QObject/.test(e)) { // Ignore this error
page.onError(e);
}
}
}));
}
webserver.listen('127.0.0.1:0', function (req, res) {
// Update watchdog timer on every request
// watchdog_clear();
if (req.method === 'GET') {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.write(JSON.stringify({ data: callback_stack }));
callback_stack = [];
res.close();
} else if (req.method === 'POST') {
var request, error, output;
try {
request = JSON.parse(req.post);
} catch (err) {
error = err;
}
if (!error) {
if (request.page) {
if (request.method === 'open') { // special case this as it's the only one with a callback
return page_open(res, pages[request.page], request.args);
} else if (request.method === 'includeJs') {
return include_js(res, pages[request.page], request.args);
}
try {
output = pages[request.page][request.method].apply(pages[request.page], request.args);
} catch (err) {
error = err;
}
} else {
try {
output = global_methods[request.method].apply(global_methods, request.args);
} catch (err) {
error = err;
}
}
}
res.setHeader('Content-Type', 'application/json');
if (error) {
res.statusCode = 500;
res.write(JSON.stringify(error));
} else {
res.statusCode = 200;
res.write(JSON.stringify({ data: output }));
}
res.close();
} else {
throw 'Unknown request type!';
}
});
var callbacks = [
'onAlert', 'onCallback', 'onClosing', 'onConfirm', 'onConsoleMessage', 'onError', 'onFilePicker',
'onInitialized', 'onLoadFinished', 'onLoadStarted', 'onNavigationRequested',
'onPrompt', 'onResourceRequested', 'onResourceReceived', 'onResourceTimeout', 'onResourceError', 'onUrlChanged',
// SlimerJS only
'onAuthPrompt'
];
function setup_callbacks (id, page) {
if (callbacks.indexOf('onInitialized') === -1) {
callbacks.push('onInitialized');
}
callbacks.forEach(function (cb) {
page[cb] = function (parm) {
var args = Array.prototype.slice.call(arguments);
if (cb === 'onInitialized') {
page.evaluate(function() {
var htmlAddEventListener = HTMLElement.prototype.addEventListener;
HTMLElement.prototype.addEventListener = function(name, cb) {
HTMLElement.boundEvents || (HTMLElement.boundEvents = {});
(HTMLElement.boundEvents[name] || (HTMLElement.boundEvents[name] = [])).push(cb + '');
return htmlAddEventListener.apply(this, arguments);
}
var documentAddEventListener = Document.prototype.addEventListener;
Document.prototype.addEventListener = function(name, cb) {
Document.boundEvents || (Document.boundEvents = {});
(Document.boundEvents[name] || (Document.boundEvents[name] = [])).push(cb + '');
return documentAddEventListener.apply(this, arguments);
}
var windowAddEventListener = window.addEventListener;
window.addEventListener = function(name, cb) {
window.boundEvents || (window.boundEvents = {});
(window.boundEvents[name] || (window.boundEvents[name] = [])).push(cb + '');
return windowAddEventListener.apply(this, arguments);
}
var windowOpen = window.open;
window.open = function (url, name, features) {
// set name if missing here
name = name || 'default_window_name';
(window.boundUrls || (window.boundUrls = [])).push(url);
return url;
// return windowOpen.apply(this, arguments);
};
});
}
if ((cb === 'onResourceRequested') && (parm.url.indexOf('data:image') === 0)) {
return;
}
if (cb === 'onClosing') { args = []; }
callback_stack.push({ 'page_id': id, 'callback': cb, 'args': args });
};
});
// Special case this
page.onPageCreated = function(page) {
var new_id = setup_page(page);
callback_stack.push({ 'page_id': id, 'callback': 'onPageCreated', 'args': [ new_id ] });
};
}
function setup_page (page) {
var id = page_id++;
page.getProperty = function (prop) {
return lookup(page, prop);
};
page.setProperty = function (prop, val) {
// Special case for `paperSize.header.contents` property.
if (prop === 'paperSize.header.contents' && val) {
val = phantom.callback(eval('(' + val + ')'));
} else if (prop === 'paperSize.header' && val.contents) {
val.contents = phantom.callback(eval('(' + val.contents + ')'));
} else if (prop === 'paperSize' && val.header && val.header.contents) {
val.header.contents = phantom.callback(eval('(' + val.header.contents + ')'));
}
// Special case for `paperSize.footer.contents` property.
if (prop === 'paperSize.footer.contents' && val) {
val = phantom.callback(eval('(' + val + ')'));
} else if (prop === 'paperSize.footer' && val.contents) {
val.contents = phantom.callback(eval('(' + val.contents + ')'));
} else if (prop === 'paperSize' && val.footer && val.footer.contents) {
val.footer.contents = phantom.callback(eval('(' + val.footer.contents + ')'));
}
lookup(page, prop, val);
return true;
};
page.setFunction = function (name, fn) {
page[name] = eval('(' + fn + ')');
return true;
};
pages[id] = page;
setup_callbacks(id, page);
return id;
}
var global_methods = {
setProxy: function (ip, port, proxyType, user, password) {
return phantom.setProxy(ip, port, proxyType, user, password);
},
createPage: function () {
var page = webpage.create();
var id = setup_page(page);
return { page_id: id };
},
injectJs: function (filename) {
return phantom.injectJs(filename);
},
exit: function (code) {
return phantom.exit(code);
},
addCookie: function (cookie) {
return phantom.addCookie(cookie);
},
clearCookies: function () {
return phantom.clearCookies();
},
deleteCookie: function (name) {
return phantom.deleteCookie(name);
},
getProperty: function (prop) {
return lookup(phantom, prop);
},
setProperty: function (prop, value) {
lookup(phantom, prop, value);
return true;
}
};
// Start watchdog timer
// watchdog_clear();
/*eslint-disable no-console*/
console.log('Ready [' + system.pid + '] [' + webserver.port + ']');