This repository has been archived by the owner on Jun 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 980
/
Copy pathcasper.js
3242 lines (3063 loc) · 112 KB
/
casper.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Casper is a navigation utility for PhantomJS.
*
* Documentation: http://casperjs.org/
* Repository: http://github.com/casperjs/casperjs
*
* Copyright (c) 2011-2012 Nicolas Perriault
*
* Part of source code is Copyright Joyent, Inc. and other Node contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*global __utils__, CasperError, console, exports, phantom, slimer, patchRequire, require:true*/
require = patchRequire(require);
var colorizer = require('colorizer');
var events = require('events');
var fs = require('fs');
var http = require('http');
var mouse = require('mouse');
var pagestack = require('pagestack');
var qs = require('querystring');
var tester = require('tester');
var utils = require('utils');
var f = utils.format;
var defaultUserAgent = phantom.defaultPageSettings.userAgent
.replace(/(PhantomJS|SlimerJS)/, f("CasperJS/%s", phantom.casperVersion) + '+$&');
exports.create = function create(options) {
"use strict";
// This is a bit of a hack to check if one is trying to override the preconfigured
// casper instance from within a test environment.
if (phantom.casperTest && window.casper) {
console.error("Fatal: you can't override the preconfigured casper instance in a test environment.");
console.error("Docs: http://docs.casperjs.org/en/latest/testing.html#test-command-args-and-options");
phantom.exit(1);
}
return new Casper(options);
};
/**
* Shortcut to build an XPath selector object.
*
* @param String expression The XPath expression
* @return Object
* @see http://casperjs.org/selectors.html
*/
function selectXPath(expression) {
"use strict";
return {
type: 'xpath',
path: expression,
toString: function() {
return this.type + ' selector: ' + this.path;
}
};
}
exports.selectXPath = selectXPath;
/**
* Main Casper object.
*
* @param Object options Casper options
*/
var Casper = function Casper(options) {
"use strict";
/*eslint max-statements:0*/
// init & checks
if (!(this instanceof Casper)) {
return new Casper(options);
}
// default options
this.defaults = {
clientScripts: [],
colorizerType: 'Colorizer',
exitOnError: true,
logLevel: "error",
httpStatusHandlers: {},
safeLogs: true,
onAlert: null,
onDie: null,
onError: null,
onLoadError: null,
onPageInitialized: null,
onResourceReceived: null,
onResourceRequested: null,
onRunComplete: function _onRunComplete() {
this.exit();
},
onStepComplete: null,
onStepTimeout: function _onStepTimeout(timeout, stepNum) {
this.die("Maximum step execution timeout exceeded for step " + stepNum);
},
onTimeout: function _onTimeout(timeout) {
this.die(f("Script timeout of %dms reached, exiting.", timeout));
},
onWaitTimeout: function _onWaitTimeout(timeout) {
this.die(f("Wait timeout of %dms expired, exiting.", timeout));
},
page: null,
pageSettings: {
localToRemoteUrlAccessEnabled: true,
javascriptEnabled: true,
userAgent: defaultUserAgent
},
remoteScripts: [],
silentErrors: false,
stepTimeout: null,
timeout: null,
verbose: false,
retryTimeout: 20,
waitTimeout: 5000,
clipRect : null,
viewportSize : null
};
// options
this.options = utils.mergeObjects(this.defaults, options);
// factories
this.cli = phantom.casperArgs;
this.options.logLevel = this.cli.get('log-level', this.options.logLevel);
if (!this.options.verbose) {
this.options.verbose = this.cli.has('direct') || this.cli.has('verbose');
}
this.colorizer = this.getColorizer();
this.mouse = mouse.create(this);
this.popups = pagestack.create();
// properties
this.checker = null;
this.currentResponse = {};
this.currentUrl = 'about:blank';
this.currentHTTPStatus = null;
this.history = [];
this.navigationRequested = false;
this.logFormats = {};
this.logLevels = ["debug", "info", "warning", "error"];
this.logStyles = {
debug: 'INFO',
info: 'PARAMETER',
warning: 'COMMENT',
error: 'ERROR'
};
this.page = null;
this.pendingWait = false;
this.requestUrl = 'about:blank';
this.requestData = {};
this.resources = [];
this.result = {
log: [],
status: "success",
time: 0
};
this.started = false;
this.step = -1;
this.steps = [];
this.waiters = [];
this._test = undefined;
this.__defineGetter__('test', function() {
if (!phantom.casperTest) {
throw new CasperError('casper.test property is only available using the `casperjs test` command');
}
if (!utils.isObject(this._test)) {
this._test = tester.create(this, {
concise: this.cli.get('concise')
});
}
return this._test;
});
// init phantomjs error handler
this.initErrorHandler();
this.on('error', function(msg, backtrace) {
var c = this.getColorizer();
var match = /^(.*): __mod_error(.*):: (.*)/.exec(msg);
var notices = [];
if (match && match.length === 4) {
notices.push(' in module ' + match[2]);
msg = match[3];
}
console.log(c.colorize(msg, 'RED_BAR', 80));
notices.forEach(function(notice) {
console.log(c.colorize(notice, 'COMMENT'));
});
(backtrace || []).forEach(function(item) {
var message = fs.absolute(item.file) + ":" + c.colorize(item.line, "COMMENT");
if (item['function']) {
message += " in " + c.colorize(item['function'], "PARAMETER");
}
console.log(" " + message);
});
});
// deprecated feature event handler
this.on('deprecated', function onDeprecated(message) {
this.warn('[deprecated] ' + message);
});
// dispatching an event when instance has been constructed
this.emit('init');
// deprecated direct option
if (this.cli.has('direct')) {
this.emit("deprecated", "--direct option has been deprecated since 1.1; you should use --verbose instead.");
}
};
// Casper class is an EventEmitter
utils.inherits(Casper, events.EventEmitter);
/**
* Go a step back in browser's history
*
* @return Casper
*/
Casper.prototype.back = function back() {
"use strict";
this.checkStarted();
return this.then(function() {
this.emit('back');
this.page.goBack();
});
};
/**
* Encodes a resource using the base64 algorithm synchronously using
* client-side XMLHttpRequest.
*
* NOTE: we cannot use window.btoa() for some strange reasons here.
*
* @param String url The url to download
* @param String method The method to use, optional: default GET
* @param String data The data to send, optional
* @return string Base64 encoded result
*/
Casper.prototype.base64encode = function base64encode(url, method, data) {
"use strict";
return this.callUtils("getBase64", url, method, data);
};
/**
* Bypasses `nb` steps.
*
* @param Integer nb Number of steps to bypass
*/
Casper.prototype.bypass = function bypass(nb) {
"use strict";
var step = this.step,
steps = this.steps,
last = steps.length,
targetStep = Math.min(step + nb, last);
this.checkStarted();
this.step = targetStep;
this.emit('step.bypassed', targetStep, step);
return this;
};
/**
* Invokes a client side utils object method within the remote page, with arguments.
*
* @param {String} method Method name
* @return {...args} Arguments
* @return {Mixed}
* @throws {CasperError} If invokation failed.
*/
Casper.prototype.callUtils = function callUtils(method) {
"use strict";
var args = [].slice.call(arguments, 1);
var result = this.evaluate(function(method, args) {
return __utils__.__call(method, args);
}, method, args);
if (utils.isObject(result) && result.__isCallError) {
throw new CasperError(f("callUtils(%s) with args %s thrown an error: %s",
method, args, result.message));
}
return result;
};
/**
* Proxy method for WebPage#render. Adds a clipRect parameter for
* automatically set page clipRect setting values and sets it back once
* done. If the cliprect parameter is omitted, the full page viewport
* area will be rendered.
*
* @param String targetFile A target filename
* @param mixed clipRect An optional clipRect object (optional)
* @return Casper
*/
Casper.prototype.capture = function capture(targetFile, clipRect, imgOptions) {
"use strict";
/*eslint max-statements:0*/
this.checkStarted();
var previousClipRect;
targetFile = fs.absolute(targetFile);
if (clipRect) {
if (!utils.isClipRect(clipRect)) {
throw new CasperError("clipRect must be a valid ClipRect object.");
}
previousClipRect = this.page.clipRect;
this.page.clipRect = clipRect;
this.log(f("Capturing page to %s with clipRect %s", targetFile, JSON.stringify(clipRect)), "debug");
} else {
this.log(f("Capturing page to %s", targetFile), "debug");
}
if (!this.page.render(this.filter('capture.target_filename', targetFile) || targetFile, imgOptions)) {
this.log(f("Failed to save screenshot to %s; please check permissions", targetFile), "error");
} else {
this.log(f("Capture saved to %s", targetFile), "info");
this.emit('capture.saved', targetFile);
}
if (previousClipRect) {
this.page.clipRect = previousClipRect;
}
return this;
};
/**
* Returns a Base64 representation of a binary image capture of the current
* page, or an area within the page, in a given format.
*
* Supported image formats are `bmp`, `jpg`, `jpeg`, `png`, `ppm`, `tiff`,
* `xbm` and `xpm`.
*
* @param String format The image format
* @param String|Object|undefined selector DOM CSS3/XPath selector or clipRect object (optional)
* @return Casper
*/
Casper.prototype.captureBase64 = function captureBase64(format, area) {
"use strict";
/*eslint max-statements:0*/
this.checkStarted();
var base64, previousClipRect, formats = ['bmp', 'jpg', 'jpeg', 'png', 'ppm', 'tiff', 'xbm', 'xpm'];
if (formats.indexOf(format.toLowerCase()) === -1) {
throw new CasperError(f('Unsupported format "%s"', format));
}
if (utils.isClipRect(area)) {
// if area is a clipRect object
this.log(f("Capturing base64 %s representation of %s", format, utils.serialize(area)), "debug");
previousClipRect = this.page.clipRect;
this.page.clipRect = area;
base64 = this.page.renderBase64(format);
} else if (utils.isValidSelector(area)) {
// if area is a selector string or object
this.log(f("Capturing base64 %s representation of %s", format, area), "debug");
var scrollPos = this.evaluate(function() {
return { x: scrollX, y: scrollY };
});
var elementBounds = this.getElementBounds(area);
elementBounds.top += scrollPos.y;
elementBounds.left += scrollPos.x;
base64 = this.captureBase64(format, elementBounds);
} else {
// whole page capture
this.log(f("Capturing base64 %s representation of page", format), "debug");
base64 = this.page.renderBase64(format);
}
if (previousClipRect) {
this.page.clipRect = previousClipRect;
}
return base64;
};
/**
* Captures the page area matching the provided selector.
*
* @param String targetFile Target destination file path.
* @param String selector DOM CSS3/XPath selector
* @return Casper
*/
Casper.prototype.captureSelector = function captureSelector(targetFile, selector, imgOptions) {
"use strict";
var scrollPos = this.evaluate(function() {
return { x: scrollX, y: scrollY };
});
var elementBounds = this.getElementBounds(selector);
elementBounds.top += scrollPos.y;
elementBounds.left += scrollPos.x;
return this.capture(targetFile, elementBounds, imgOptions);
};
/**
* Checks if response header contains a "content disposition" value
* it calls the onFileDownloadError callback when browser couldn't download it.
*
* @param Object resource PhantomJS HTTP resource
* @return Casper
*/
Casper.prototype.checkContentDisposition = function checkContentDisposition(resource) {
"use strict";
if (utils.isHTTPResource(resource)) {
var request = this.requestData[resource.id];
delete this.requestData[resource.id];
if (resource.hasOwnProperty("isFileDownloading") && resource.isFileDownloading === true) {
return;
}
var contentDisposition = resource.headers.get("Content-Disposition");
if (contentDisposition !== null) {
var filename = contentDisposition.match(/filename=["']?([^"']*)["']?/i);
if (filename !== null) {
this.page.onFileDownloadError("Can't download file : \"" + filename[1] +"\"");
this.emit('fileToDownload', {
"url": resource.url,
"filename": filename[1],
"size": resource.bodySize || 0,
"contentType": resource.contentType,
"method": request.method,
"postData": request.postData,
"headers": request.headers
});
}
}
}
return this;
};
/**
* Checks for any further navigation step to process.
*
* @param Casper self A self reference
* @param function onComplete An options callback to apply on completion
*/
Casper.prototype.checkStep = function checkStep(self, onComplete) {
"use strict";
if (self.page !== null && (self.pendingWait || self.page.loadInProgress || self.navigationRequested || self.page.browserInitializing )) {
return;
}
var step = self.steps[self.step++];
if (utils.isFunction(step)) {
return self.runStep(step);
}
self.result.time = new Date().getTime() - self.startTime;
self.log(f("Done %s steps in %dms", self.steps.length, self.result.time), "info");
clearInterval(self.checker);
self.step -= 1;
self.emit('run.complete');
try {
if (utils.isFunction(onComplete)) {
onComplete.call(self, self);
} else if (utils.isFunction(self.options.onRunComplete)) {
self.options.onRunComplete.call(self, self);
}
} catch (error) {
self.emit('complete.error', error);
if (!self.options.silentErrors) {
throw error;
}
}
};
/**
* Checks if this instance is started.
*
* @return Boolean
* @throws CasperError
*/
Casper.prototype.checkStarted = function checkStarted() {
"use strict";
if (!this.started) {
throw new CasperError(f("Casper is not started, can't execute `%s()`",
checkStarted.caller.name));
}
if (this.page === null) {
this.newPage();
}
};
/**
* Clears the current page execution environment context. Useful to avoid
* having previously loaded DOM contents being still active (refs #34).
*
* Think of it as a way to stop javascript execution within the remote DOM
* environment.
*
* @return Casper
*/
Casper.prototype.clear = function clear() {
"use strict";
this.checkStarted();
this.page.content = '';
return this;
};
/**
* Replace currente page by a new page object, with newPage()
* Clears the memory cache, with clearMemoryCache()
*
* @return Casper
*/
Casper.prototype.clearCache = function clearCache() {
"use strict";
this.checkStarted();
this.page = this.newPage();
this.clearMemoryCache();
return this;
};
/**
* Clears the memory cache, using engine method
* reference: https://github.com/ariya/phantomjs/issues/10357
*
* @return Casper
*/
Casper.prototype.clearMemoryCache = function clearMemoryCache() {
"use strict";
this.checkStarted();
if (typeof this.page.clearMemoryCache === 'function') {
this.page.clearMemoryCache();
} else if ( phantom.casperEngine === 'slimerjs' || utils.matchEngine({name: 'phantomjs', version: {min: '2.0.0'}}) ) {
this.log('clearMemoryCache() did nothing: page.clearMemoryCache is not avliable in this engine', "warning");
} else {
throw new CasperError("clearMemoryCache(): page.clearMemoryCache should be avaliable in this engine");
}
return this;
};
/**
* Emulates a click on the element from the provided selector using the mouse
* pointer, if possible.
*
* In case of success, `true` is returned, `false` otherwise.
*
* @param String selector A DOM CSS3 compatible selector
* @param String target A HTML target '_blank','_self','_parent','_top','framename' (optional)
* @param Number x X position (optional)
* @param Number y Y position (optional)
* @return Boolean
*/
Casper.prototype.click = function click(selector, x, y) {
"use strict";
this.checkStarted();
if (!this.visible(selector)) {
this.log(f("Trying to click on hidden element : %s", JSON.stringify(selector)), "debug");
}
var success = this.mouseEvent('mousedown', selector, x, y) && this.mouseEvent('mouseup', selector, x, y);
success = success && this.mouseEvent('click', selector, x, y);
this.evaluate(function(selector) {
var element = __utils__.findOne(selector);
if (element) {
element.focus();
}
}, selector);
this.emit('click', selector);
return success;
};
/**
* Emulates a click on the element having `label` as innerText. The first
* element matching this label will be selected, so use with caution.
*
* @param String label Element innerText value
* @param String tag An element tag name (eg. `a` or `button`) (optional)
* @return Boolean
*/
Casper.prototype.clickLabel = function clickLabel(label, tag) {
"use strict";
this.checkStarted();
tag = tag || "*";
var escapedLabel = utils.quoteXPathAttributeString(label);
var selector = selectXPath(f('//%s[text()=%s]', tag, escapedLabel));
return this.click(selector);
};
/**
* Configures HTTP authentication parameters. Will try parsing auth credentials from
* the passed location first, then check for configured settings if any.
*
* @param String location Requested url
* @param Object settings Request settings
* @return Casper
*/
Casper.prototype.configureHttpAuth = function configureHttpAuth(location, settings) {
"use strict";
var httpAuthMatch = location.match(/^https?:\/\/(.+):(.+)@/i);
this.checkStarted();
if (httpAuthMatch) {
this.page.settings.userName = httpAuthMatch[1];
this.page.settings.password = httpAuthMatch[2];
} else if (utils.isObject(settings) && settings.username) {
this.page.settings.userName = settings.username;
this.page.settings.password = settings.password;
} else {
return;
}
this.emit('http.auth', this.page.settings.userName, this.page.settings.password);
this.log("Setting HTTP authentication for user " + this.page.settings.userName, "info");
return this;
};
/**
* Creates a step definition.
*
* @param Function fn The step function to call
* @param Object options Step options
* @return Function The final step function
*/
Casper.prototype.createStep = function createStep(fn, options) {
"use strict";
if (!utils.isFunction(fn)) {
throw new CasperError("createStep(): a step definition must be a function");
}
fn.options = utils.isObject(options) ? options : {};
this.emit('step.created', fn);
return fn;
};
/**
* Logs the HTML code of the current page.
*
* @param String selector A DOM CSS3/XPath selector (optional)
* @param Boolean outer Whether to fetch outer HTML contents (default: false)
* @return Casper
*/
Casper.prototype.debugHTML = function debugHTML(selector, outer) {
"use strict";
this.checkStarted();
return this.echo(this.getHTML(selector, outer));
};
/**
* Logs the textual contents of the current page.
*
* @return Casper
*/
Casper.prototype.debugPage = function debugPage() {
"use strict";
this.checkStarted();
this.echo(this.evaluate(function _evaluate() {
return document.body.textContent || document.body.innerText;
}));
return this;
};
/**
* Exit phantom on failure, with a logged error message.
*
* @param String message An optional error message
* @param Number status An optional exit status code (must be > 0)
* @return Casper
*/
Casper.prototype.die = function die(message, status) {
"use strict";
this.result.status = "error";
this.result.time = new Date().getTime() - this.startTime;
if (!utils.isString(message) || !message.length) {
message = "Suite explicitly interrupted without any message given.";
}
this.log(message, "error");
this.echo(message, "ERROR");
this.emit('die', message, status);
if (utils.isFunction(this.options.onDie)) {
this.options.onDie.call(this, this, message, status);
}
return this.exit(~~status > 0 ? ~~status : 1);
};
/**
* Downloads a resource and saves it on the filesystem.
*
* @param String url The url of the resource to download
* @param String targetPath The destination file path
* @param String method The HTTP method to use (default: GET)
* @param String data Optional data to pass performing the request
* @return Casper
*/
Casper.prototype.download = function download(url, targetPath, method, data) {
"use strict";
this.checkStarted();
var cu = require('clientutils').create(utils.mergeObjects({}, this.options));
try {
fs.write(targetPath, cu.decode(this.base64encode(url, method, data)), 'wb');
this.emit('downloaded.file', targetPath);
this.log(f("Downloaded and saved resource in %s", targetPath));
} catch (e) {
this.emit('downloaded.error', url);
this.log(f("Error while downloading %s to %s: %s", url, targetPath, e), "error");
}
return this;
};
/**
* Iterates over the values of a provided array and execute a callback for each
* item.
*
* @param Array array
* @param Function fn Callback: function(casper, item, index)
* @return Casper
*/
Casper.prototype.each = function each(array, fn) {
"use strict";
if (!utils.isArray(array)) {
this.log("each() only works with arrays", "error");
return this;
}
array.forEach(function _forEach(item, i) {
fn.call(this, this, item, i);
}, this);
return this;
};
/**
* Iterates over the values of a provided array and adds a step for each item.
*
* @param Array array
* @param Function then Step: function(response); item will be attached to response.data
* @return Casper
*/
Casper.prototype.eachThen = function each(array, then) {
"use strict";
if (!utils.isArray(array)) {
this.log("eachThen() only works with arrays", "error");
return this;
}
array.forEach(function _forEach(item) {
this.then(function() {
this.then(this.createStep(then, {data: item}));
});
}, this);
return this;
};
/**
* Prints something to stdout.
*
* @param String text A string to echo to stdout
* @param String style An optional style name
* @param Number pad An optional pad value
* @return Casper
*/
Casper.prototype.echo = function echo(text, style, pad) {
"use strict";
if (!utils.isString(text)) {
try {
text = text.toString();
} catch (e) {
try {
text = utils.serialize(text);
} catch (e2) {
text = '';
}
}
}
var message = style ? this.colorizer.colorize(text, style, pad) : text;
console.log(this.filter('echo.message', message) || message);
return this;
};
/**
* Evaluates an expression in the page context, a bit like what
* WebPage#evaluate does, but the passed function can also accept
* parameters if a context Object is also passed:
*
* casper.evaluate(function(username, password) {
* document.querySelector('#username').value = username;
* document.querySelector('#password').value = password;
* document.querySelector('#submit').click();
* }, 'Bazoonga', 'baz00nga');
*
* @param Function fn The function to be evaluated within current page DOM
* @param Object context Object containing the parameters to inject into the function
* @return mixed
* @see WebPage#evaluate
*/
Casper.prototype.evaluate = function evaluate(fn, context) {
"use strict";
this.checkStarted();
// check whether javascript is enabled !!
if (this.options.pageSettings.javascriptEnabled === false) {
throw new CasperError("evaluate() requires javascript to be enabled");
}
// preliminary checks
if (!utils.isFunction(fn) && !utils.isString(fn)) { // phantomjs allows functions defs as string
throw new CasperError("evaluate() only accepts functions or strings");
}
// ensure client utils are always injected
this.injectClientUtils();
// function context
if (arguments.length === 1) {
return utils.clone(this.page.evaluate(fn));
} else if (arguments.length === 2) {
// check for closure signature if it matches context
if (utils.isObject(context) && fn.length === Object.keys(context).length) {
/*
* in case if user passes argument as one array with only one object.
* evaluate shlould return original array with one object
* instead of converte this array to object
*/
if (utils.isArray(context) && context.length === 1) {
context = [context];
} else {
context = utils.objectValues(context);
}
} else {
context = [context];
}
} else {
// phantomjs-style signature
context = [].slice.call(arguments, 1);
}
return utils.clone(this.page.evaluate.apply(this.page, [fn].concat(context)));
};
/**
* Evaluates an expression within the current page DOM and die() if it
* returns false.
*
* @param function fn The expression to evaluate
* @param String message The error message to log
* @param Number status An optional exit status code (must be > 0)
*
* @return Casper
*/
Casper.prototype.evaluateOrDie = function evaluateOrDie(fn, message, status) {
"use strict";
this.checkStarted();
if (!this.evaluate(fn)) {
return this.die(message, status);
}
return this;
};
/**
* Checks if an element matching the provided DOM CSS3/XPath selector exists in
* current page DOM.
*
* @param String selector A DOM CSS3/XPath selector
* @return Boolean
*/
Casper.prototype.exists = function exists(selector) {
"use strict";
this.checkStarted();
return this.callUtils("exists", selector);
};
/**
* Exits phantom.
*
* @param Number status Status
* @return Casper
*/
Casper.prototype.exit = function exit(status) {
"use strict";
this.emit('exit', status);
this.die = function(){};
setTimeout(function() { phantom.exit(status); }, 0);
};
/**
* Fetches plain text contents contained in the DOM element(s) matching a given CSS3/XPath
* selector.
*
* @param String selector A DOM CSS3/XPath selector
* @return String
*/
Casper.prototype.fetchText = function fetchText(selector) {
"use strict";
this.checkStarted();
return this.callUtils("fetchText", selector);
};
/**
* Fills a form with provided field values.
*
* @param String selector A DOM CSS3/XPath selector to the target form to fill
* @param Object vals Field values
* @param Object options The fill settings (optional)
*/
Casper.prototype.fillForm = function fillForm(selector, vals, options) {
"use strict";
this.checkStarted();
var self = this;
var selectorType = options && options.selectorType || "names",
submit = !!(options && options.submit);
this.emit('fill', selector, vals, options);
var fillResults = this.evaluate(function _evaluate(selector, vals, selectorType) {
try {
return __utils__.fill(selector, vals, selectorType);
} catch (exception) {
return {exception: exception.toString()};
}
}, selector, vals, selectorType);
if (!fillResults) {
throw new CasperError("Unable to fill form");
} else if (fillResults && fillResults.exception) {
throw new CasperError("Unable to fill form: " + fillResults.exception);
} else if (fillResults.errors.length > 0) {
throw new CasperError(f('Errors encountered while filling form: %s',
fillResults.errors.join('; ')));
}
// File uploads
if (fillResults.files && fillResults.files.length > 0) {
fillResults.files.forEach(function _forEach(file) {
if (!file || !file.path) {
return;
}
var paths = (utils.isArray(file.path) && file.path.length > 0) ? file.path : [file.path];
paths.map(function(filePath) {
if (!fs.exists(filePath)) {
throw new CasperError('Cannot upload nonexistent file: ' + filePath);
}
},this);
var fileFieldSelector;
if (file.type === "names") {
fileFieldSelector = [selector, 'input[name="' + file.selector + '"]'].join(' ');
} else if (file.type === "css" || file.type === "labels") {
fileFieldSelector = [selector, file.selector].join(' ');
} else if (file.type === "xpath") {
fileFieldSelector = [selector, self.evaluate(function _evaluate(selector, scope, limit) {
return __utils__.getCssSelector(selector, scope, limit);
}, selectXPath(file.selector), selector, 'FORM')].join(' ');
}
this.page.uploadFile(fileFieldSelector, paths);
}.bind(this));
}
// Form submission?
if (submit) {
this.evaluate(function _evaluate(selector) {
var form = __utils__.findOne(selector);
var method = (form.getAttribute('method') || "GET").toUpperCase();
var action = form.getAttribute('action') || "unknown";
__utils__.log('submitting form to ' + action + ', HTTP ' + method, 'info');
var event = document.createEvent('Event');
event.initEvent('submit', true, true);
if (!form.dispatchEvent(event)) {
__utils__.log('unable to submit form', 'warning');
return;
}
if (typeof form.submit === "function") {
form.submit();
} else {
// http://www.spiration.co.uk/post/1232/Submit-is-not-a-function
form.submit.click();
}
}, selector);
}
return this;
};
/**
* Fills a form with provided field values using the Name attribute.
*
* @param String formSelector A DOM CSS3/XPath selector to the target form to fill
* @param Object vals Field values
* @param Boolean submit Submit the form?
*/
Casper.prototype.fillNames = function fillNames(formSelector, vals, submit) {
"use strict";
return this.fillForm(formSelector, vals, {
submit: submit,
selectorType: 'names'
});
};
/**
* Fills a form with provided field values using associated label text.
*
* @param String formSelector A DOM CSS3/XPath selector to the target form to fill
* @param Object vals Field values
* @param Boolean submit Submit the form?
*/
Casper.prototype.fillLabels = function fillLabels(formSelector, vals, submit) {
"use strict";
return this.fillForm(formSelector, vals, {
submit: submit,
selectorType: 'labels'
});
};
/**
* Fills a form with provided field values using CSS3 selectors.
*