This repository has been archived by the owner on Sep 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 150
/
index.js
361 lines (312 loc) Β· 11.6 KB
/
index.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
'use strict';
var path = require('path'),
util = require('util'),
inherit = require('inherit'),
debug = require('debug'),
wd = require('wd'),
q = require('q'),
chalk = require('chalk'),
polyfillService = require('polyfill-service'),
browserify = require('browserify'),
Image = require('../image'),
Actions = require('./actions'),
ClientBridge = require('./client-bridge'),
GeminiError = require('../errors/gemini-error'),
OPERA_NOT_SUPPORTED = 'Not supported in OperaDriver yet';
var Browser = inherit({
__constructor: function(config) {
this.config = config;
this.id = config.id;
this._browser = wd.promiseRemote(config.gridUrl);
this.log = debug('gemini:browser:' + this.id);
var wdLog = debug('gemini:webdriver:' + this.id);
this._browser.on('connection', function(code, message, error) {
wdLog('Error: code %d, %s', code, message);
});
this._browser.on('status', function(info) {
wdLog(info);
});
this._browser.on('command', function(eventType, command, response) {
if (eventType === 'RESPONSE' && command === 'takeScreenshot()') {
response = '<binary-data>';
}
if (typeof response !== 'string') {
response = JSON.stringify(response);
}
wdLog(chalk.cyan(eventType), command, chalk.grey(response || ''));
});
},
launch: function(calibrator) {
var _this = this;
return this.initSession()
.then(function() {
return _this._setDefaultSize();
})
.then(function() {
//maximize is required, because default
//windows size in phantomjs can prevent
//some shadows from fitting in
if (_this._shouldMaximize()) {
return _this._maximize();
}
})
.then(function() {
if (!_this.config.calibrate || _this._calibration) {
return;
}
return calibrator.calibrate(_this)
.then(function(result) {
_this._calibration = result;
});
})
.then(function() {
return _this._buildPolyfills();
})
.then(function() {
return _this.buildScripts();
})
.then(function() {
return _this.chooseLocator();
})
.fail(function(e) {
if (e.code === 'ECONNREFUSED') {
return q.reject(new GeminiError(
'Unable to connect to ' + _this.config.gridUrl,
'Make sure that URL in config file is correct and selenium\nserver is running.'
));
}
var error = new GeminiError(
util.format('Cannot launch browser %s:\n%s', _this.id, e.message)
);
error.browserId = _this.id;
error.browserSessionId = _this.sessionId;
// sadly, selenium does not provide a way to distinguish different
// reasons of failure
return q.reject(error);
});
},
initSession: function() {
var _this = this;
return this._browser
.configureHttp({
retries: 'never',
timeout: this.config.httpTimeout
})
.then(function() {
return _this._browser.init(_this.capabilities);
})
.spread(function(sessionId, actualCapabilities) {
_this.sessionId = sessionId;
_this.log('launched session %o', _this);
});
},
_setDefaultSize: function() {
var size = this.config.windowSize;
if (!size) {
return;
}
return this._browser.setWindowSize(size.width, size.height)
.fail(function(e) {
// Its the only reliable way to detect not supported operation
// in legacy operadriver.
var message = e.cause && e.cause.value && e.cause.value.message;
if (message === OPERA_NOT_SUPPORTED) {
console.warn(chalk.yellow('WARNING!'));
console.warn('Legacy Opera Driver does not support window resizing');
console.warn('windowSize setting will be ignored.');
return;
}
return q.reject(e);
});
},
_buildPolyfills: function() {
/*jshint evil:true*/
//polyfills are needed for older browsers, namely, IE8
var _this = this;
return _this._browser.eval('navigator.userAgent')
.then(function(ua) {
return polyfillService.getPolyfillString({
uaString: ua,
minify: true,
features: {
'getComputedStyle': {flags: ['gated']},
'matchMedia': {flags: ['gated']},
'document.querySelector': {flags: ['gated']},
'String.prototype.trim': {flags: ['gated']}
}
});
})
.then(function(polyfill) {
_this._polyfill = polyfill;
});
},
openRelative: function(relativeURL) {
return this.open(this.config.getAbsoluteUrl(relativeURL));
},
open: function(url) {
return this._browser.get(url);
},
injectScript: function(script) {
return this._browser.execute(script);
},
evalScript: function(script) {
/*jshint evil:true*/
return this._browser.eval(script);
},
buildScripts: function() {
var script = browserify({
entries: './gemini',
basedir: path.join(__dirname, 'client-scripts')
});
if (!this.config.system.coverage.enabled) {
script.exclude('./gemini.coverage');
}
script.transform({sourcemap: false, global: true}, 'uglifyify');
var queryLib = this._needsSizzle? './query.sizzle.js' : './query.native.js';
script.transform({
aliases: {
'./query': {relative: queryLib}
},
verbose: false
}, 'aliasify');
var _this = this;
return q.nfcall(script.bundle.bind(script))
.then(function(buf) {
var scripts = _this._polyfill + '\n' + buf.toString();
_this._clientBridge = new ClientBridge(_this, scripts);
return scripts;
});
},
get _needsSizzle() {
return this._calibration && !this._calibration.hasCSS3Selectors;
},
chooseLocator: function() {
this.findElement = this._needsSizzle? this._findElementScript : this._findElementWd;
},
reset: function() {
var _this = this;
// We can't use findElement here because it requires page with body tag
return this.evalScript('document.body')
.then(function(body) {
// Selenium IEDriver doesn't move cursor to (0, 0) first time
// https://github.com/SeleniumHQ/selenium/issues/672
// So we do it in two steps: -> (1, 1) -> (0, 0)
return _this._browser.moveTo(body, 1, 1)
.then(_this._browser.moveTo.bind(_this._browser, body, 0, 0));
});
},
get browserName() {
return this.capabilities.browserName;
},
get version() {
return this.capabilities.version;
},
get capabilities() {
return this.config.desiredCapabilities;
},
_shouldMaximize: function() {
return this.browserName === 'phantomjs';
},
_maximize: function() {
var _this = this;
return _this._browser.windowHandle()
.then(function(handle) {
return _this._browser.maximize(handle);
});
},
findElement: function(selector) {
throw new Error('findElement is called before appropriate locator is chosen');
},
_findElementWd: function(selector) {
return this._browser.elementByCssSelector(selector)
.fail(function(error) {
if (error.status === Browser.ELEMENT_NOT_FOUND) {
error.selector = selector;
}
return q.reject(error);
});
},
_findElementScript: function(selector) {
return this._clientBridge.call('query.first', [selector])
.then(function(element) {
if (element) {
return element;
}
var error = new Error('Unable to find element');
error.status = Browser.ELEMENT_NOT_FOUND;
error.selector = selector;
return q.reject(error);
});
},
prepareScreenshot: function(selectors, opts) {
return this._clientBridge.call('prepareScreenshot', [selectors, opts || {}]);
},
captureFullscreenImage: function() {
var _this = this;
return this._tryScreenshotMethod('_takeScreenshot')
.fail(function(originalError) {
return _this._tryScreenshotMethod('_takeScreenshotWithNativeContext')
.fail(function() {
// if _takeScreenshotWithNativeContext fails too, the original error
// most likely was not related to the different Appium contexts and
// it is more useful to report it instead of second one
return q.reject(originalError);
});
});
},
_tryScreenshotMethod: function(method) {
var _this = this;
return this[method]()
.then(function(screenshot) {
_this.captureFullscreenImage = _this[method];
return screenshot;
});
},
_takeScreenshot: function() {
var _this = this;
return this._browser.takeScreenshot()
.then(function(base64) {
var image = new Image(new Buffer(base64, 'base64'));
if (_this._calibration) {
image = image.crop({
left: _this._calibration.left,
top: _this._calibration.top,
width: image.getSize().width - _this._calibration.left,
height: image.getSize().height - _this._calibration.top
});
}
return image;
});
},
_takeScreenshotWithNativeContext: function() {
var _this = this;
return this._browser.currentContext()
.then(function(oldContext) {
return _this._browser.context('NATIVE_APP')
.then(_this._takeScreenshot.bind(_this))
.fin(function() {
return _this._browser.context(oldContext);
});
});
},
get usePixelRatio() {
return this._calibration && this._calibration.usePixelRatio;
},
quit: function() {
var _this = this;
return this._browser
.quit()
.then(function() {
_this.log('kill browser %o', _this);
});
},
createActionSequence: function() {
return new Actions(this);
},
inspect: function() {
return util.format('[%s (%s)]', this.id, this.sessionId);
}
}, {
ELEMENT_NOT_FOUND: 7
});
module.exports = Browser;