/
session.js
382 lines (331 loc) · 14.6 KB
/
session.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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/*
This file is part of the GhostDriver project from Neustar inc.
Copyright (c) 2012, Ivan De Marino <ivan.de.marino@gmail.com / detronizator@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var ghostdriver = ghostdriver || {};
ghostdriver.Session = function(desiredCapabilities) {
// private:
var
_defaultCapabilities = { // TODO - Actually try to match the "desiredCapabilities" instead of ignoring them
"browserName" : "phantomjs",
"version" : phantom.version.major + '.' + phantom.version.minor + '.' + phantom.version.patch,
"platform" : ghostdriver.system.os.name + '-' + ghostdriver.system.os.version + '-' + ghostdriver.system.os.architecture,
"javascriptEnabled" : true,
"takesScreenshot" : true,
"handlesAlerts" : false, //< TODO
"databaseEnabled" : false, //< TODO
"locationContextEnabled" : false, //< TODO Target is 1.1
"applicationCacheEnabled" : false, //< TODO Support for AppCache (?)
"browserConnectionEnabled" : false, //< TODO
"cssSelectorsEnabled" : true,
"webStorageEnabled" : false, //< TODO support for LocalStorage/SessionStorage
"rotatable" : false, //< TODO Target is 1.1
"acceptSslCerts" : false, //< TODO
"nativeEvents" : true, //< TODO Only some commands are Native Events currently
"proxy" : { //< TODO Support more proxy options - PhantomJS does allow setting from command line
"proxyType" : "direct"
}
},
_negotiatedCapabilities = {
"browserName" : _defaultCapabilities.browserName,
"version" : _defaultCapabilities.version,
"platform" : _defaultCapabilities.platform,
"javascriptEnabled" : typeof(desiredCapabilities.javascriptEnabled) === "undefined" ?
_defaultCapabilities.javascriptEnabled :
desiredCapabilities.javascriptEnabled,
"takesScreenshot" : typeof(desiredCapabilities.takesScreenshot) === "undefined" ?
_defaultCapabilities.takesScreenshot :
desiredCapabilities.takesScreenshot,
"handlesAlerts" : _defaultCapabilities.handlesAlerts,
"databaseEnabled" : _defaultCapabilities.databaseEnabled,
"locationContextEnabled" : _defaultCapabilities.locationContextEnabled,
"applicationCacheEnabled" : _defaultCapabilities.applicationCacheEnabled,
"browserConnectionEnabled" : _defaultCapabilities.browserConnectionEnabled,
"cssSelectorsEnabled" : _defaultCapabilities.cssSelectorsEnabled,
"webStorageEnabled" : _defaultCapabilities.webStorageEnabled,
"rotatable" : _defaultCapabilities.rotatable,
"acceptSslCerts" : _defaultCapabilities.acceptSslCerts,
"nativeEvents" : _defaultCapabilities.nativeEvents,
"proxy" : typeof(desiredCapabilities.proxy) === "undefined" ?
_defaultCapabilities.proxy :
desiredCapabilities.proxy
},
_timeouts = {
"script" : 500, //< 0.5s
"async script" : 5000, //< 5s
"implicit" : 0, //< 0s
"page load" : 10000 //< 10s
},
_const = {
TIMEOUT_NAMES : {
SCRIPT : "script",
ASYNC_SCRIPT : "async script",
IMPLICIT : "implicit",
PAGE_LOAD : "page load"
}
},
_windows = {}, //< NOTE: windows are "webpage" in Phantom-dialect
_currentWindowHandle = null,
_id = "SID-" + require("./third_party/uuid.js").v1(),
_inputs = ghostdriver.Inputs(),
/**
* Executes a function and waits for Load to happen.
*
* @param func Function to execute
* @param onLoadFunc Function to execute when page finishes Loading
* @param onErrorFunc Function to execute in case of error
* @param execTypeOpt Decides if to "apply" the function directly or page."eval" it.
* Optional. Default value is "apply".
*/
_execFuncAndWaitForLoadDecorator = function(func, onLoadFunc, onErrorFunc, execTypeOpt) {
// convert 'arguments' to a real Array
var args = Array.prototype.splice.call(arguments, 0),
timer,
loadingNewPage = false,
thisPage = this;
// Normalize "execTypeOpt" value
if (typeof(execexecTypeOpt) === "undefined" ||
(execexecTypeOpt !== "apply" && execTypeOpt !== "eval")) {
execTypeOpt = "apply";
}
// Separating arguments for the "function call" from the callback handlers.
if (execTypeOpt === "eval") {
// NOTE: I'm also passing 'evalFunc' as first parameter
// for the 'evaluate' call, and '0' as timeout.
args.splice(0, 3, evalFunc, 0);
} else {
args.splice(0, 3);
}
// This function used to ensure no callback is left behind
// after we are done here
function clearAllCallbacks() {
// console.log("Clearing callbacks for window: " + thisPage.windowHandle);
thisPage.onLoadStarted = null;
thisPage.onUrlChanged = null;
thisPage.onLoadFinished = null;
thisPage.onError = null;
}
// Register event handlers
// This logic bears some explaining. If we are loading a new page,
// the loadStarted event will fire, then urlChanged, then loadFinished,
// assuming no errors. However, when navigating to a fragment on the
// same page, neither the loadStarted nor the loadFinished events will
// fire. So if we receive a urlChanged event without a corresponding
// loadStarted event, we know we are only navigating to a fragment on
// the same page, and should fire the onLoadFunc callback. Otherwise,
// we need to wait until the loadFinished event before firing the
// callback.
this.setOneShotCallback("onLoadStarted", function () {
// console.log("onLoadStarted");
loadingNewPage = true;
});
this.setOneShotCallback("onUrlChanged", function () {
// console.log("onUrlChanged");
// If "not loading a new page" it's just a fragment change
// and we should call "onLoadFunc()"
if (!loadingNewPage) {
clearTimeout(timer);
clearAllCallbacks();
onLoadFunc.apply(thisPage, arguments);
}
});
this.setOneShotCallback("onLoadFinished", function () {
// console.log("onLoadFinished");
clearTimeout(timer);
clearAllCallbacks();
onLoadFunc.apply(thisPage, arguments);
});
this.setOneShotCallback("onError", function(message, stack) {
// console.log("onError: "+message+"\n");
// stack.forEach(function(item) {
// var message = item.file + ":" + item.line;
// if (item["function"])
// message += " in " + item["function"];
// console.log(" " + message);
// });
thisPage.stop(); //< stop the page from loading
clearTimeout(timer);
clearAllCallbacks();
onErrorFunc.apply(thisPage, arguments);
});
// Starting timer
timer = setTimeout(function() {
thisPage.stop(); //< stop the page from loading
clearAllCallbacks();
onErrorFunc.apply(thisPage, arguments);
}, _getTimeout(_const.TIMEOUT_NAMES.PAGE_LOAD));
// We are ready to execute
if (execTypeOpt === "eval") {
// Invoke the Page Eval with the provided function
this.evaluateAsync.apply(this, args);
} else {
// "Apply" the provided function
func.apply(this, args);
}
},
_setOneShotCallbackDecorator = function(callbackName, handlerFunc) {
var thisPage = this;
thisPage[callbackName] = function() {
// console.log("Invoking one-shot-callback for: " + callbackName);
thisPage[callbackName] = null; //< once done, get rid of the handling
handlerFunc.apply(thisPage, arguments); //< call the actual handler
};
},
// Add any new page to the "_windows" container of this session
_addNewPage = function(newPage) {
_decorateNewWindow(newPage); //< decorate the new page
_windows[newPage.windowHandle] = newPage; //< store the page/window
},
// Delete any closing page from the "_windows" container of this session
_deleteClosingPage = function(closingPage) {
// Need to be defensive, as the "closing" can be cause by Client Commands
if (_windows.hasOwnProperty(closingPage.windowHandle)) {
delete _windows[closingPage.windowHandle];
}
},
_decorateNewWindow = function(page) {
// Decorating:
// 0. Pages lifetime will be managed by Driver, not the pages
page.ownsPages = false;
// 1. Random Window Handle
page.windowHandle = "WH-" + require("./third_party/uuid.js").v1();
// 2. Utility methods
page.execFuncAndWaitForLoad = _execFuncAndWaitForLoadDecorator;
page.setOneShotCallback = _setOneShotCallbackDecorator;
// 3. Store every newly created page
page.onPageCreated = _addNewPage;
// 4. Remove every closing page
page.onClosing = _deleteClosingPage;
// page.onConsoleMessage = function(msg) { console.log(msg); };
return page;
},
_getWindow = function(handleOrName) {
var page = null,
k;
if (_isValidWindowHandle(handleOrName)) {
// Search by "handle"
page = _windows[handleOrName];
} else {
// Search by "name"
for (k in _windows) {
if (_windows[k].windowName === handleOrName) {
page = _windows[k];
break;
}
}
}
return page;
},
_getCurrentWindow = function() {
var page = null;
if (_currentWindowHandle === null) {
// First call to get the current window: need to create one
page = _decorateNewWindow(require("webpage").create());
_currentWindowHandle = page.windowHandle;
_windows[_currentWindowHandle] = page;
} else if (_windows.hasOwnProperty(_currentWindowHandle)) {
page = _windows[_currentWindowHandle];
}
// TODO Handle "null" cases throwing a "no such window" error
return page;
},
_switchToWindow = function(handleOrName) {
var page = _getWindow(handleOrName);
if (page !== null) {
// Switch current window and return "true"
_currentWindowHandle = page.windowHandle;
return true;
}
// Couldn't find the window, so return "false"
return false;
},
_closeCurrentWindow = function() {
if (_currentWindowHandle !== null) {
return _closeWindow(_currentWindowHandle);
}
return false;
},
_closeWindow = function(handleOrName) {
var page = _getWindow(handleOrName),
handle;
if (page !== null) {
handle = page.windowHandle;
_windows[handle].close();
delete _windows[handle];
return true;
}
return false;
},
_getWindowsCount = function() {
return Object.keys(_windows).length;
},
_getCurrentWindowHandle = function() {
if (!_isValidWindowHandle(_currentWindowHandle)) {
return null;
}
return _currentWindowHandle;
},
_isValidWindowHandle = function(handle) {
return _windows.hasOwnProperty(handle);
},
_getWindowHandles = function() {
return Object.keys(_windows);
},
_setTimeout = function(type, ms) {
_timeouts[type] = ms;
},
_getTimeout = function(type) {
return _timeouts[type];
},
_timeoutNames = function() {
return _const.TIMEOUT_NAMES;
},
_aboutToDelete = function() {
var k;
// Close current window first
_closeCurrentWindow();
// Releasing page resources and deleting the objects
for (k in _windows) {
_closeWindow(k);
}
};
// console.log("Session '" + _id + "' - Capabilities: " + JSON.stringify(_negotiatedCapabilities, null, " "));
// console.log("Desired: "+JSON.stringify(desiredCapabilities, null, " "));
// public:
return {
getCapabilities : function() { return _negotiatedCapabilities; },
getId : function() { return _id; },
switchToWindow : _switchToWindow,
getCurrentWindow : _getCurrentWindow,
closeCurrentWindow : _closeCurrentWindow,
getWindow : _getWindow,
closeWindow : _closeWindow,
getWindowsCount : _getWindowsCount,
getCurrentWindowHandle : _getCurrentWindowHandle,
getWindowHandles: _getWindowHandles,
isValidWindowHandle: _isValidWindowHandle,
aboutToDelete : _aboutToDelete,
setTimeout : _setTimeout,
getTimeout : _getTimeout,
timeoutNames : _timeoutNames,
inputs: _inputs
};
};