Commit 51b41755 51b41755e3344502401042b7cfc81cc0e03fe1de by Nicolas Perriault

added Casper#base64encode for retrieving a base64 encoded representation of any …

…resource behind an url
1 parent 6d4f7d54
Showing 1 changed file with 54 additions and 3 deletions
...@@ -77,6 +77,57 @@ ...@@ -77,6 +77,57 @@
77 */ 77 */
78 phantom.Casper.prototype = { 78 phantom.Casper.prototype = {
79 /** 79 /**
80 * Encodes a resource using the base64 algorithm synchroneously using
81 * client-side XMLHttpRequest.
82 *
83 * NOTE: we cannot use window.btoa() for some strange reasons here.
84 *
85 * @param string url The url to download
86 * @return string Base64 encoded result
87 */
88 base64encode: function(url) {
89 return result = this.evaluate(function() {
90 function encode(str) {
91 var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
92 var out = "", i = 0, len = str.length, c1, c2, c3;
93 while (i < len) {
94 c1 = str.charCodeAt(i++) & 0xff;
95 if (i == len) {
96 out += CHARS.charAt(c1 >> 2);
97 out += CHARS.charAt((c1 & 0x3) << 4);
98 out += "==";
99 break;
100 }
101 c2 = str.charCodeAt(i++);
102 if (i == len) {
103 out += CHARS.charAt(c1 >> 2);
104 out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
105 out += CHARS.charAt((c2 & 0xF) << 2);
106 out += "=";
107 break;
108 }
109 c3 = str.charCodeAt(i++);
110 out += CHARS.charAt(c1 >> 2);
111 out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
112 out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
113 out += CHARS.charAt(c3 & 0x3F);
114 }
115 return out;
116 }
117 function getBinary(url) {
118 var xhr = new XMLHttpRequest();
119 xhr.open("GET", url, false);
120 xhr.overrideMimeType("text/plain; charset=x-user-defined");
121 xhr.send(null);
122 return xhr.responseText;
123 }
124 return encode(getBinary('%url%'));
125 }, {
126 url: url
127 });
128 },
129
130 /**
80 * Proxy method for WebPage#render. Adds a clipRect parameter for 131 * Proxy method for WebPage#render. Adds a clipRect parameter for
81 * automatically set page clipRect setting values and sets it back once 132 * automatically set page clipRect setting values and sets it back once
82 * done. 133 * done.
...@@ -291,13 +342,13 @@ ...@@ -291,13 +342,13 @@
291 * Repeats a step a given number of times. 342 * Repeats a step a given number of times.
292 * 343 *
293 * @param Number times Number of times to repeat step 344 * @param Number times Number of times to repeat step
294 * @aram function step The step closure 345 * @aram function then The step closure
295 * @return Casper 346 * @return Casper
296 * @see Casper#then 347 * @see Casper#then
297 */ 348 */
298 repeat: function(times, step) { 349 repeat: function(times, then) {
299 for (var i = 0; i < times; i++) { 350 for (var i = 0; i < times; i++) {
300 this.then(step); 351 this.then(then);
301 } 352 }
302 return this; 353 return this;
303 }, 354 },
......