├── README.md ├── examples ├── arguments.js ├── child_process-examples.js ├── colorwheel.js ├── countdown.js ├── detectsniff.js ├── echoToFile.js ├── features.js ├── fibo.js ├── hello.js ├── injectme.js ├── loadspeed.js ├── loadurlwithoutcss.js ├── modernizr.js ├── module.js ├── netlog.js ├── netsniff.js ├── openurlwithproxy.js ├── outputEncoding.js ├── page_events.js ├── pagecallback.js ├── phantomwebintro.js ├── post.js ├── postjson.js ├── postserver.js ├── printenv.js ├── printheaderfooter.js ├── printmargins.js ├── rasterize.js ├── render_multi_url.js ├── responsive-screenshot.js ├── run-jasmine.js ├── run-jasmine2.js ├── run-qunit.js ├── scandir.js ├── server.js ├── serverkeepalive.js ├── simpleserver.js ├── sleepsort.js ├── stdin-stdout-stderr.js ├── universe.js ├── unrandomize.js ├── useragent.js ├── version.js ├── waitfor.js └── walk_through_frames.js └── phantomjs.zip /README.md: -------------------------------------------------------------------------------- 1 | # PhantomJS-Raspberry-Pi-3- 2 | PhantomJS compiled on a Raspberry Pi 3, working binary ready to download and run. 3 | 4 | ##Directions 5 | -Unzip phantomjs.zip 6 | ####(note this is zipped because I couldn't upload it to github otherwise and you need the compiled binary which still takes many hours on a Raspberry Pi 3 to do). 7 | 8 | ###Directions to run 9 | - Without direct installation you will have to run the full directory of the location 10 | - /{current working directory}/phantomjs -arg1 11 | 12 | Problems? Please let me know. 13 | -------------------------------------------------------------------------------- /examples/arguments.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var system = require('system'); 3 | if (system.args.length === 1) { 4 | console.log('Try to pass some args when invoking this script!'); 5 | } else { 6 | system.args.forEach(function (arg, i) { 7 | console.log(i + ': ' + arg); 8 | }); 9 | } 10 | phantom.exit(); 11 | -------------------------------------------------------------------------------- /examples/child_process-examples.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var spawn = require("child_process").spawn 3 | var execFile = require("child_process").execFile 4 | 5 | var child = spawn("ls", ["-lF", "/rooot"]) 6 | 7 | child.stdout.on("data", function (data) { 8 | console.log("spawnSTDOUT:", JSON.stringify(data)) 9 | }) 10 | 11 | child.stderr.on("data", function (data) { 12 | console.log("spawnSTDERR:", JSON.stringify(data)) 13 | }) 14 | 15 | child.on("exit", function (code) { 16 | console.log("spawnEXIT:", code) 17 | }) 18 | 19 | //child.kill("SIGKILL") 20 | 21 | execFile("ls", ["-lF", "/usr"], null, function (err, stdout, stderr) { 22 | console.log("execFileSTDOUT:", JSON.stringify(stdout)) 23 | console.log("execFileSTDERR:", JSON.stringify(stderr)) 24 | }) 25 | 26 | setTimeout(function () { 27 | phantom.exit(0) 28 | }, 2000) 29 | -------------------------------------------------------------------------------- /examples/colorwheel.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var page = require('webpage').create(); 3 | page.viewportSize = { width: 400, height : 400 }; 4 | page.content = ''; 5 | page.evaluate(function() { 6 | var el = document.getElementById('surface'), 7 | context = el.getContext('2d'), 8 | width = window.innerWidth, 9 | height = window.innerHeight, 10 | cx = width / 2, 11 | cy = height / 2, 12 | radius = width / 2.3, 13 | imageData, 14 | pixels, 15 | hue, sat, value, 16 | i = 0, x, y, rx, ry, d, 17 | f, g, p, u, v, w, rgb; 18 | 19 | el.width = width; 20 | el.height = height; 21 | imageData = context.createImageData(width, height); 22 | pixels = imageData.data; 23 | 24 | for (y = 0; y < height; y = y + 1) { 25 | for (x = 0; x < width; x = x + 1, i = i + 4) { 26 | rx = x - cx; 27 | ry = y - cy; 28 | d = rx * rx + ry * ry; 29 | if (d < radius * radius) { 30 | hue = 6 * (Math.atan2(ry, rx) + Math.PI) / (2 * Math.PI); 31 | sat = Math.sqrt(d) / radius; 32 | g = Math.floor(hue); 33 | f = hue - g; 34 | u = 255 * (1 - sat); 35 | v = 255 * (1 - sat * f); 36 | w = 255 * (1 - sat * (1 - f)); 37 | pixels[i] = [255, v, u, u, w, 255, 255][g]; 38 | pixels[i + 1] = [w, 255, 255, v, u, u, w][g]; 39 | pixels[i + 2] = [u, u, w, 255, 255, v, u][g]; 40 | pixels[i + 3] = 255; 41 | } 42 | } 43 | } 44 | 45 | context.putImageData(imageData, 0, 0); 46 | document.body.style.backgroundColor = 'white'; 47 | document.body.style.margin = '0px'; 48 | }); 49 | 50 | page.render('colorwheel.png'); 51 | 52 | phantom.exit(); 53 | -------------------------------------------------------------------------------- /examples/countdown.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var t = 10, 3 | interval = setInterval(function(){ 4 | if ( t > 0 ) { 5 | console.log(t--); 6 | } else { 7 | console.log("BLAST OFF!"); 8 | phantom.exit(); 9 | } 10 | }, 1000); 11 | -------------------------------------------------------------------------------- /examples/detectsniff.js: -------------------------------------------------------------------------------- 1 | // Detect if a web page sniffs the user agent or not. 2 | 3 | "use strict"; 4 | var page = require('webpage').create(), 5 | system = require('system'), 6 | sniffed, 7 | address; 8 | 9 | page.onInitialized = function () { 10 | page.evaluate(function () { 11 | 12 | (function () { 13 | var userAgent = window.navigator.userAgent, 14 | platform = window.navigator.platform; 15 | 16 | window.navigator = { 17 | appCodeName: 'Mozilla', 18 | appName: 'Netscape', 19 | cookieEnabled: false, 20 | sniffed: false 21 | }; 22 | 23 | window.navigator.__defineGetter__('userAgent', function () { 24 | window.navigator.sniffed = true; 25 | return userAgent; 26 | }); 27 | 28 | window.navigator.__defineGetter__('platform', function () { 29 | window.navigator.sniffed = true; 30 | return platform; 31 | }); 32 | })(); 33 | }); 34 | }; 35 | 36 | if (system.args.length === 1) { 37 | console.log('Usage: detectsniff.js '); 38 | phantom.exit(1); 39 | } else { 40 | address = system.args[1]; 41 | console.log('Checking ' + address + '...'); 42 | page.open(address, function (status) { 43 | if (status !== 'success') { 44 | console.log('FAIL to load the address'); 45 | phantom.exit(); 46 | } else { 47 | window.setTimeout(function () { 48 | sniffed = page.evaluate(function () { 49 | return navigator.sniffed; 50 | }); 51 | if (sniffed) { 52 | console.log('The page tried to sniff the user agent.'); 53 | } else { 54 | console.log('The page did not try to sniff the user agent.'); 55 | } 56 | phantom.exit(); 57 | }, 1500); 58 | } 59 | }); 60 | } 61 | -------------------------------------------------------------------------------- /examples/echoToFile.js: -------------------------------------------------------------------------------- 1 | // echoToFile.js - Write in a given file all the parameters passed on the CLI 2 | "use strict"; 3 | var fs = require('fs'), 4 | system = require('system'); 5 | 6 | if (system.args.length < 3) { 7 | console.log("Usage: echoToFile.js DESTINATION_FILE "); 8 | phantom.exit(1); 9 | } else { 10 | var content = '', 11 | f = null, 12 | i; 13 | for ( i= 2; i < system.args.length; ++i ) { 14 | content += system.args[i] + (i === system.args.length-1 ? '' : ' '); 15 | } 16 | 17 | try { 18 | fs.write(system.args[1], content, 'w'); 19 | } catch(e) { 20 | console.log(e); 21 | } 22 | 23 | phantom.exit(); 24 | } 25 | -------------------------------------------------------------------------------- /examples/features.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var feature, supported = [], unsupported = []; 3 | 4 | phantom.injectJs('modernizr.js'); 5 | console.log('Detected features (using Modernizr ' + Modernizr._version + '):'); 6 | for (feature in Modernizr) { 7 | if (Modernizr.hasOwnProperty(feature)) { 8 | if (feature[0] !== '_' && typeof Modernizr[feature] !== 'function' && 9 | feature !== 'input' && feature !== 'inputtypes') { 10 | if (Modernizr[feature]) { 11 | supported.push(feature); 12 | } else { 13 | unsupported.push(feature); 14 | } 15 | } 16 | } 17 | } 18 | 19 | console.log(''); 20 | console.log('Supported:'); 21 | supported.forEach(function (e) { 22 | console.log(' ' + e); 23 | }); 24 | 25 | console.log(''); 26 | console.log('Not supported:'); 27 | unsupported.forEach(function (e) { 28 | console.log(' ' + e); 29 | }); 30 | phantom.exit(); 31 | -------------------------------------------------------------------------------- /examples/fibo.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var fibs = [0, 1]; 3 | var ticker = window.setInterval(function () { 4 | console.log(fibs[fibs.length - 1]); 5 | fibs.push(fibs[fibs.length - 1] + fibs[fibs.length - 2]); 6 | if (fibs.length > 10) { 7 | window.clearInterval(ticker); 8 | phantom.exit(); 9 | } 10 | }, 300); 11 | -------------------------------------------------------------------------------- /examples/hello.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | console.log('Hello, world!'); 3 | phantom.exit(); 4 | -------------------------------------------------------------------------------- /examples/injectme.js: -------------------------------------------------------------------------------- 1 | // Use 'page.injectJs()' to load the script itself in the Page context 2 | 3 | "use strict"; 4 | if ( typeof(phantom) !== "undefined" ) { 5 | var page = require('webpage').create(); 6 | 7 | // Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this") 8 | page.onConsoleMessage = function(msg) { 9 | console.log(msg); 10 | }; 11 | 12 | page.onAlert = function(msg) { 13 | console.log(msg); 14 | }; 15 | 16 | console.log("* Script running in the Phantom context."); 17 | console.log("* Script will 'inject' itself in a page..."); 18 | page.open("about:blank", function(status) { 19 | if ( status === "success" ) { 20 | console.log(page.injectJs("injectme.js") ? "... done injecting itself!" : "... fail! Check the $PWD?!"); 21 | } 22 | phantom.exit(); 23 | }); 24 | } else { 25 | alert("* Script running in the Page context."); 26 | } 27 | -------------------------------------------------------------------------------- /examples/loadspeed.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var page = require('webpage').create(), 3 | system = require('system'), 4 | t, address; 5 | 6 | if (system.args.length === 1) { 7 | console.log('Usage: loadspeed.js '); 8 | phantom.exit(1); 9 | } else { 10 | t = Date.now(); 11 | address = system.args[1]; 12 | page.open(address, function (status) { 13 | if (status !== 'success') { 14 | console.log('FAIL to load the address'); 15 | } else { 16 | t = Date.now() - t; 17 | console.log('Page title is ' + page.evaluate(function () { 18 | return document.title; 19 | })); 20 | console.log('Loading time ' + t + ' msec'); 21 | } 22 | phantom.exit(); 23 | }); 24 | } 25 | -------------------------------------------------------------------------------- /examples/loadurlwithoutcss.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var page = require('webpage').create(), 3 | system = require('system'); 4 | 5 | if (system.args.length < 2) { 6 | console.log('Usage: loadurlwithoutcss.js URL'); 7 | phantom.exit(); 8 | } 9 | 10 | var address = system.args[1]; 11 | 12 | page.onResourceRequested = function(requestData, request) { 13 | if ((/http:\/\/.+?\.css/gi).test(requestData['url']) || requestData.headers['Content-Type'] == 'text/css') { 14 | console.log('The url of the request is matching. Aborting: ' + requestData['url']); 15 | request.abort(); 16 | } 17 | }; 18 | 19 | page.open(address, function(status) { 20 | if (status === 'success') { 21 | phantom.exit(); 22 | } else { 23 | console.log('Unable to load the address!'); 24 | phantom.exit(); 25 | } 26 | }); -------------------------------------------------------------------------------- /examples/modernizr.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Modernizr v2.8.2 3 | * www.modernizr.com 4 | * 5 | * Copyright (c) Faruk Ates, Paul Irish, Alex Sexton 6 | * Available under the BSD and MIT licenses: www.modernizr.com/license/ 7 | */ 8 | 9 | /* 10 | * Modernizr tests which native CSS3 and HTML5 features are available in 11 | * the current UA and makes the results available to you in two ways: 12 | * as properties on a global Modernizr object, and as classes on the 13 | * element. This information allows you to progressively enhance 14 | * your pages with a granular level of control over the experience. 15 | * 16 | * Modernizr has an optional (not included) conditional resource loader 17 | * called Modernizr.load(), based on Yepnope.js (yepnopejs.com). 18 | * To get a build that includes Modernizr.load(), as well as choosing 19 | * which tests to include, go to www.modernizr.com/download/ 20 | * 21 | * Authors Faruk Ates, Paul Irish, Alex Sexton 22 | * Contributors Ryan Seddon, Ben Alman 23 | */ 24 | 25 | window.Modernizr = (function( window, document, undefined ) { 26 | 27 | var version = '2.8.2', 28 | 29 | Modernizr = {}, 30 | 31 | /*>>cssclasses*/ 32 | // option for enabling the HTML classes to be added 33 | enableClasses = true, 34 | /*>>cssclasses*/ 35 | 36 | docElement = document.documentElement, 37 | 38 | /** 39 | * Create our "modernizr" element that we do most feature tests on. 40 | */ 41 | mod = 'modernizr', 42 | modElem = document.createElement(mod), 43 | mStyle = modElem.style, 44 | 45 | /** 46 | * Create the input element for various Web Forms feature tests. 47 | */ 48 | inputElem /*>>inputelem*/ = document.createElement('input') /*>>inputelem*/ , 49 | 50 | /*>>smile*/ 51 | smile = ':)', 52 | /*>>smile*/ 53 | 54 | toString = {}.toString, 55 | 56 | // TODO :: make the prefixes more granular 57 | /*>>prefixes*/ 58 | // List of property values to set for css tests. See ticket #21 59 | prefixes = ' -webkit- -moz- -o- -ms- '.split(' '), 60 | /*>>prefixes*/ 61 | 62 | /*>>domprefixes*/ 63 | // Following spec is to expose vendor-specific style properties as: 64 | // elem.style.WebkitBorderRadius 65 | // and the following would be incorrect: 66 | // elem.style.webkitBorderRadius 67 | 68 | // Webkit ghosts their properties in lowercase but Opera & Moz do not. 69 | // Microsoft uses a lowercase `ms` instead of the correct `Ms` in IE8+ 70 | // erik.eae.net/archives/2008/03/10/21.48.10/ 71 | 72 | // More here: github.com/Modernizr/Modernizr/issues/issue/21 73 | omPrefixes = 'Webkit Moz O ms', 74 | 75 | cssomPrefixes = omPrefixes.split(' '), 76 | 77 | domPrefixes = omPrefixes.toLowerCase().split(' '), 78 | /*>>domprefixes*/ 79 | 80 | /*>>ns*/ 81 | ns = {'svg': 'http://www.w3.org/2000/svg'}, 82 | /*>>ns*/ 83 | 84 | tests = {}, 85 | inputs = {}, 86 | attrs = {}, 87 | 88 | classes = [], 89 | 90 | slice = classes.slice, 91 | 92 | featureName, // used in testing loop 93 | 94 | 95 | /*>>teststyles*/ 96 | // Inject element with style element and some CSS rules 97 | injectElementWithStyles = function( rule, callback, nodes, testnames ) { 98 | 99 | var style, ret, node, docOverflow, 100 | div = document.createElement('div'), 101 | // After page load injecting a fake body doesn't work so check if body exists 102 | body = document.body, 103 | // IE6 and 7 won't return offsetWidth or offsetHeight unless it's in the body element, so we fake it. 104 | fakeBody = body || document.createElement('body'); 105 | 106 | if ( parseInt(nodes, 10) ) { 107 | // In order not to give false positives we create a node for each test 108 | // This also allows the method to scale for unspecified uses 109 | while ( nodes-- ) { 110 | node = document.createElement('div'); 111 | node.id = testnames ? testnames[nodes] : mod + (nodes + 1); 112 | div.appendChild(node); 113 | } 114 | } 115 | 116 | // '].join(''); 122 | div.id = mod; 123 | // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody. 124 | // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270 125 | (body ? div : fakeBody).innerHTML += style; 126 | fakeBody.appendChild(div); 127 | if ( !body ) { 128 | //avoid crashing IE8, if background image is used 129 | fakeBody.style.background = ''; 130 | //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible 131 | fakeBody.style.overflow = 'hidden'; 132 | docOverflow = docElement.style.overflow; 133 | docElement.style.overflow = 'hidden'; 134 | docElement.appendChild(fakeBody); 135 | } 136 | 137 | ret = callback(div, rule); 138 | // If this is done after page load we don't want to remove the body so check if body exists 139 | if ( !body ) { 140 | fakeBody.parentNode.removeChild(fakeBody); 141 | docElement.style.overflow = docOverflow; 142 | } else { 143 | div.parentNode.removeChild(div); 144 | } 145 | 146 | return !!ret; 147 | 148 | }, 149 | /*>>teststyles*/ 150 | 151 | /*>>mq*/ 152 | // adapted from matchMedia polyfill 153 | // by Scott Jehl and Paul Irish 154 | // gist.github.com/786768 155 | testMediaQuery = function( mq ) { 156 | 157 | var matchMedia = window.matchMedia || window.msMatchMedia; 158 | if ( matchMedia ) { 159 | return matchMedia(mq) && matchMedia(mq).matches || false; 160 | } 161 | 162 | var bool; 163 | 164 | injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) { 165 | bool = (window.getComputedStyle ? 166 | getComputedStyle(node, null) : 167 | node.currentStyle)['position'] == 'absolute'; 168 | }); 169 | 170 | return bool; 171 | 172 | }, 173 | /*>>mq*/ 174 | 175 | 176 | /*>>hasevent*/ 177 | // 178 | // isEventSupported determines if a given element supports the given event 179 | // kangax.github.com/iseventsupported/ 180 | // 181 | // The following results are known incorrects: 182 | // Modernizr.hasEvent("webkitTransitionEnd", elem) // false negative 183 | // Modernizr.hasEvent("textInput") // in Webkit. github.com/Modernizr/Modernizr/issues/333 184 | // ... 185 | isEventSupported = (function() { 186 | 187 | var TAGNAMES = { 188 | 'select': 'input', 'change': 'input', 189 | 'submit': 'form', 'reset': 'form', 190 | 'error': 'img', 'load': 'img', 'abort': 'img' 191 | }; 192 | 193 | function isEventSupported( eventName, element ) { 194 | 195 | element = element || document.createElement(TAGNAMES[eventName] || 'div'); 196 | eventName = 'on' + eventName; 197 | 198 | // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those 199 | var isSupported = eventName in element; 200 | 201 | if ( !isSupported ) { 202 | // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element 203 | if ( !element.setAttribute ) { 204 | element = document.createElement('div'); 205 | } 206 | if ( element.setAttribute && element.removeAttribute ) { 207 | element.setAttribute(eventName, ''); 208 | isSupported = is(element[eventName], 'function'); 209 | 210 | // If property was created, "remove it" (by setting value to `undefined`) 211 | if ( !is(element[eventName], 'undefined') ) { 212 | element[eventName] = undefined; 213 | } 214 | element.removeAttribute(eventName); 215 | } 216 | } 217 | 218 | element = null; 219 | return isSupported; 220 | } 221 | return isEventSupported; 222 | })(), 223 | /*>>hasevent*/ 224 | 225 | // TODO :: Add flag for hasownprop ? didn't last time 226 | 227 | // hasOwnProperty shim by kangax needed for Safari 2.0 support 228 | _hasOwnProperty = ({}).hasOwnProperty, hasOwnProp; 229 | 230 | if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) { 231 | hasOwnProp = function (object, property) { 232 | return _hasOwnProperty.call(object, property); 233 | }; 234 | } 235 | else { 236 | hasOwnProp = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */ 237 | return ((property in object) && is(object.constructor.prototype[property], 'undefined')); 238 | }; 239 | } 240 | 241 | // Adapted from ES5-shim https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js 242 | // es5.github.com/#x15.3.4.5 243 | 244 | if (!Function.prototype.bind) { 245 | Function.prototype.bind = function bind(that) { 246 | 247 | var target = this; 248 | 249 | if (typeof target != "function") { 250 | throw new TypeError(); 251 | } 252 | 253 | var args = slice.call(arguments, 1), 254 | bound = function () { 255 | 256 | if (this instanceof bound) { 257 | 258 | var F = function(){}; 259 | F.prototype = target.prototype; 260 | var self = new F(); 261 | 262 | var result = target.apply( 263 | self, 264 | args.concat(slice.call(arguments)) 265 | ); 266 | if (Object(result) === result) { 267 | return result; 268 | } 269 | return self; 270 | 271 | } else { 272 | 273 | return target.apply( 274 | that, 275 | args.concat(slice.call(arguments)) 276 | ); 277 | 278 | } 279 | 280 | }; 281 | 282 | return bound; 283 | }; 284 | } 285 | 286 | /** 287 | * setCss applies given styles to the Modernizr DOM node. 288 | */ 289 | function setCss( str ) { 290 | mStyle.cssText = str; 291 | } 292 | 293 | /** 294 | * setCssAll extrapolates all vendor-specific css strings. 295 | */ 296 | function setCssAll( str1, str2 ) { 297 | return setCss(prefixes.join(str1 + ';') + ( str2 || '' )); 298 | } 299 | 300 | /** 301 | * is returns a boolean for if typeof obj is exactly type. 302 | */ 303 | function is( obj, type ) { 304 | return typeof obj === type; 305 | } 306 | 307 | /** 308 | * contains returns a boolean for if substr is found within str. 309 | */ 310 | function contains( str, substr ) { 311 | return !!~('' + str).indexOf(substr); 312 | } 313 | 314 | /*>>testprop*/ 315 | 316 | // testProps is a generic CSS / DOM property test. 317 | 318 | // In testing support for a given CSS property, it's legit to test: 319 | // `elem.style[styleName] !== undefined` 320 | // If the property is supported it will return an empty string, 321 | // if unsupported it will return undefined. 322 | 323 | // We'll take advantage of this quick test and skip setting a style 324 | // on our modernizr element, but instead just testing undefined vs 325 | // empty string. 326 | 327 | // Because the testing of the CSS property names (with "-", as 328 | // opposed to the camelCase DOM properties) is non-portable and 329 | // non-standard but works in WebKit and IE (but not Gecko or Opera), 330 | // we explicitly reject properties with dashes so that authors 331 | // developing in WebKit or IE first don't end up with 332 | // browser-specific content by accident. 333 | 334 | function testProps( props, prefixed ) { 335 | for ( var i in props ) { 336 | var prop = props[i]; 337 | if ( !contains(prop, "-") && mStyle[prop] !== undefined ) { 338 | return prefixed == 'pfx' ? prop : true; 339 | } 340 | } 341 | return false; 342 | } 343 | /*>>testprop*/ 344 | 345 | // TODO :: add testDOMProps 346 | /** 347 | * testDOMProps is a generic DOM property test; if a browser supports 348 | * a certain property, it won't return undefined for it. 349 | */ 350 | function testDOMProps( props, obj, elem ) { 351 | for ( var i in props ) { 352 | var item = obj[props[i]]; 353 | if ( item !== undefined) { 354 | 355 | // return the property name as a string 356 | if (elem === false) return props[i]; 357 | 358 | // let's bind a function 359 | if (is(item, 'function')){ 360 | // default to autobind unless override 361 | return item.bind(elem || obj); 362 | } 363 | 364 | // return the unbound function or obj or value 365 | return item; 366 | } 367 | } 368 | return false; 369 | } 370 | 371 | /*>>testallprops*/ 372 | /** 373 | * testPropsAll tests a list of DOM properties we want to check against. 374 | * We specify literally ALL possible (known and/or likely) properties on 375 | * the element including the non-vendor prefixed one, for forward- 376 | * compatibility. 377 | */ 378 | function testPropsAll( prop, prefixed, elem ) { 379 | 380 | var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1), 381 | props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' '); 382 | 383 | // did they call .prefixed('boxSizing') or are we just testing a prop? 384 | if(is(prefixed, "string") || is(prefixed, "undefined")) { 385 | return testProps(props, prefixed); 386 | 387 | // otherwise, they called .prefixed('requestAnimationFrame', window[, elem]) 388 | } else { 389 | props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' '); 390 | return testDOMProps(props, prefixed, elem); 391 | } 392 | } 393 | /*>>testallprops*/ 394 | 395 | 396 | /** 397 | * Tests 398 | * ----- 399 | */ 400 | 401 | // The *new* flexbox 402 | // dev.w3.org/csswg/css3-flexbox 403 | 404 | tests['flexbox'] = function() { 405 | return testPropsAll('flexWrap'); 406 | }; 407 | 408 | // The *old* flexbox 409 | // www.w3.org/TR/2009/WD-css3-flexbox-20090723/ 410 | 411 | tests['flexboxlegacy'] = function() { 412 | return testPropsAll('boxDirection'); 413 | }; 414 | 415 | // On the S60 and BB Storm, getContext exists, but always returns undefined 416 | // so we actually have to call getContext() to verify 417 | // github.com/Modernizr/Modernizr/issues/issue/97/ 418 | 419 | tests['canvas'] = function() { 420 | var elem = document.createElement('canvas'); 421 | return !!(elem.getContext && elem.getContext('2d')); 422 | }; 423 | 424 | tests['canvastext'] = function() { 425 | return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function')); 426 | }; 427 | 428 | // webk.it/70117 is tracking a legit WebGL feature detect proposal 429 | 430 | // We do a soft detect which may false positive in order to avoid 431 | // an expensive context creation: bugzil.la/732441 432 | 433 | tests['webgl'] = function() { 434 | return !!window.WebGLRenderingContext; 435 | }; 436 | 437 | /* 438 | * The Modernizr.touch test only indicates if the browser supports 439 | * touch events, which does not necessarily reflect a touchscreen 440 | * device, as evidenced by tablets running Windows 7 or, alas, 441 | * the Palm Pre / WebOS (touch) phones. 442 | * 443 | * Additionally, Chrome (desktop) used to lie about its support on this, 444 | * but that has since been rectified: crbug.com/36415 445 | * 446 | * We also test for Firefox 4 Multitouch Support. 447 | * 448 | * For more info, see: modernizr.github.com/Modernizr/touch.html 449 | */ 450 | 451 | tests['touch'] = function() { 452 | var bool; 453 | 454 | if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) { 455 | bool = true; 456 | } else { 457 | injectElementWithStyles(['@media (',prefixes.join('touch-enabled),('),mod,')','{#modernizr{top:9px;position:absolute}}'].join(''), function( node ) { 458 | bool = node.offsetTop === 9; 459 | }); 460 | } 461 | 462 | return bool; 463 | }; 464 | 465 | 466 | // geolocation is often considered a trivial feature detect... 467 | // Turns out, it's quite tricky to get right: 468 | // 469 | // Using !!navigator.geolocation does two things we don't want. It: 470 | // 1. Leaks memory in IE9: github.com/Modernizr/Modernizr/issues/513 471 | // 2. Disables page caching in WebKit: webk.it/43956 472 | // 473 | // Meanwhile, in Firefox < 8, an about:config setting could expose 474 | // a false positive that would throw an exception: bugzil.la/688158 475 | 476 | tests['geolocation'] = function() { 477 | return 'geolocation' in navigator; 478 | }; 479 | 480 | 481 | tests['postmessage'] = function() { 482 | return !!window.postMessage; 483 | }; 484 | 485 | 486 | // Chrome incognito mode used to throw an exception when using openDatabase 487 | // It doesn't anymore. 488 | tests['websqldatabase'] = function() { 489 | return !!window.openDatabase; 490 | }; 491 | 492 | // Vendors had inconsistent prefixing with the experimental Indexed DB: 493 | // - Webkit's implementation is accessible through webkitIndexedDB 494 | // - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB 495 | // For speed, we don't test the legacy (and beta-only) indexedDB 496 | tests['indexedDB'] = function() { 497 | return !!testPropsAll("indexedDB", window); 498 | }; 499 | 500 | // documentMode logic from YUI to filter out IE8 Compat Mode 501 | // which false positives. 502 | tests['hashchange'] = function() { 503 | return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7); 504 | }; 505 | 506 | // Per 1.6: 507 | // This used to be Modernizr.historymanagement but the longer 508 | // name has been deprecated in favor of a shorter and property-matching one. 509 | // The old API is still available in 1.6, but as of 2.0 will throw a warning, 510 | // and in the first release thereafter disappear entirely. 511 | tests['history'] = function() { 512 | return !!(window.history && history.pushState); 513 | }; 514 | 515 | tests['draganddrop'] = function() { 516 | var div = document.createElement('div'); 517 | return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div); 518 | }; 519 | 520 | // FF3.6 was EOL'ed on 4/24/12, but the ESR version of FF10 521 | // will be supported until FF19 (2/12/13), at which time, ESR becomes FF17. 522 | // FF10 still uses prefixes, so check for it until then. 523 | // for more ESR info, see: mozilla.org/en-US/firefox/organizations/faq/ 524 | tests['websockets'] = function() { 525 | return 'WebSocket' in window || 'MozWebSocket' in window; 526 | }; 527 | 528 | 529 | // css-tricks.com/rgba-browser-support/ 530 | tests['rgba'] = function() { 531 | // Set an rgba() color and check the returned value 532 | 533 | setCss('background-color:rgba(150,255,150,.5)'); 534 | 535 | return contains(mStyle.backgroundColor, 'rgba'); 536 | }; 537 | 538 | tests['hsla'] = function() { 539 | // Same as rgba(), in fact, browsers re-map hsla() to rgba() internally, 540 | // except IE9 who retains it as hsla 541 | 542 | setCss('background-color:hsla(120,40%,100%,.5)'); 543 | 544 | return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla'); 545 | }; 546 | 547 | tests['multiplebgs'] = function() { 548 | // Setting multiple images AND a color on the background shorthand property 549 | // and then querying the style.background property value for the number of 550 | // occurrences of "url(" is a reliable method for detecting ACTUAL support for this! 551 | 552 | setCss('background:url(https://),url(https://),red url(https://)'); 553 | 554 | // If the UA supports multiple backgrounds, there should be three occurrences 555 | // of the string "url(" in the return value for elemStyle.background 556 | 557 | return (/(url\s*\(.*?){3}/).test(mStyle.background); 558 | }; 559 | 560 | 561 | 562 | // this will false positive in Opera Mini 563 | // github.com/Modernizr/Modernizr/issues/396 564 | 565 | tests['backgroundsize'] = function() { 566 | return testPropsAll('backgroundSize'); 567 | }; 568 | 569 | tests['borderimage'] = function() { 570 | return testPropsAll('borderImage'); 571 | }; 572 | 573 | 574 | // Super comprehensive table about all the unique implementations of 575 | // border-radius: muddledramblings.com/table-of-css3-border-radius-compliance 576 | 577 | tests['borderradius'] = function() { 578 | return testPropsAll('borderRadius'); 579 | }; 580 | 581 | // WebOS unfortunately false positives on this test. 582 | tests['boxshadow'] = function() { 583 | return testPropsAll('boxShadow'); 584 | }; 585 | 586 | // FF3.0 will false positive on this test 587 | tests['textshadow'] = function() { 588 | return document.createElement('div').style.textShadow === ''; 589 | }; 590 | 591 | 592 | tests['opacity'] = function() { 593 | // Browsers that actually have CSS Opacity implemented have done so 594 | // according to spec, which means their return values are within the 595 | // range of [0.0,1.0] - including the leading zero. 596 | 597 | setCssAll('opacity:.55'); 598 | 599 | // The non-literal . in this regex is intentional: 600 | // German Chrome returns this value as 0,55 601 | // github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632 602 | return (/^0.55$/).test(mStyle.opacity); 603 | }; 604 | 605 | 606 | // Note, Android < 4 will pass this test, but can only animate 607 | // a single property at a time 608 | // goo.gl/v3V4Gp 609 | tests['cssanimations'] = function() { 610 | return testPropsAll('animationName'); 611 | }; 612 | 613 | 614 | tests['csscolumns'] = function() { 615 | return testPropsAll('columnCount'); 616 | }; 617 | 618 | 619 | tests['cssgradients'] = function() { 620 | /** 621 | * For CSS Gradients syntax, please see: 622 | * webkit.org/blog/175/introducing-css-gradients/ 623 | * developer.mozilla.org/en/CSS/-moz-linear-gradient 624 | * developer.mozilla.org/en/CSS/-moz-radial-gradient 625 | * dev.w3.org/csswg/css3-images/#gradients- 626 | */ 627 | 628 | var str1 = 'background-image:', 629 | str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));', 630 | str3 = 'linear-gradient(left top,#9f9, white);'; 631 | 632 | setCss( 633 | // legacy webkit syntax (FIXME: remove when syntax not in use anymore) 634 | (str1 + '-webkit- '.split(' ').join(str2 + str1) + 635 | // standard syntax // trailing 'background-image:' 636 | prefixes.join(str3 + str1)).slice(0, -str1.length) 637 | ); 638 | 639 | return contains(mStyle.backgroundImage, 'gradient'); 640 | }; 641 | 642 | 643 | tests['cssreflections'] = function() { 644 | return testPropsAll('boxReflect'); 645 | }; 646 | 647 | 648 | tests['csstransforms'] = function() { 649 | return !!testPropsAll('transform'); 650 | }; 651 | 652 | 653 | tests['csstransforms3d'] = function() { 654 | 655 | var ret = !!testPropsAll('perspective'); 656 | 657 | // Webkit's 3D transforms are passed off to the browser's own graphics renderer. 658 | // It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in 659 | // some conditions. As a result, Webkit typically recognizes the syntax but 660 | // will sometimes throw a false positive, thus we must do a more thorough check: 661 | if ( ret && 'webkitPerspective' in docElement.style ) { 662 | 663 | // Webkit allows this media query to succeed only if the feature is enabled. 664 | // `@media (transform-3d),(-webkit-transform-3d){ ... }` 665 | injectElementWithStyles('@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}', function( node, rule ) { 666 | ret = node.offsetLeft === 9 && node.offsetHeight === 3; 667 | }); 668 | } 669 | return ret; 670 | }; 671 | 672 | 673 | tests['csstransitions'] = function() { 674 | return testPropsAll('transition'); 675 | }; 676 | 677 | 678 | /*>>fontface*/ 679 | // @font-face detection routine by Diego Perini 680 | // javascript.nwbox.com/CSSSupport/ 681 | 682 | // false positives: 683 | // WebOS github.com/Modernizr/Modernizr/issues/342 684 | // WP7 github.com/Modernizr/Modernizr/issues/538 685 | tests['fontface'] = function() { 686 | var bool; 687 | 688 | injectElementWithStyles('@font-face {font-family:"font";src:url("https://")}', function( node, rule ) { 689 | var style = document.getElementById('smodernizr'), 690 | sheet = style.sheet || style.styleSheet, 691 | cssText = sheet ? (sheet.cssRules && sheet.cssRules[0] ? sheet.cssRules[0].cssText : sheet.cssText || '') : ''; 692 | 693 | bool = /src/i.test(cssText) && cssText.indexOf(rule.split(' ')[0]) === 0; 694 | }); 695 | 696 | return bool; 697 | }; 698 | /*>>fontface*/ 699 | 700 | // CSS generated content detection 701 | tests['generatedcontent'] = function() { 702 | var bool; 703 | 704 | injectElementWithStyles(['#',mod,'{font:0/0 a}#',mod,':after{content:"',smile,'";visibility:hidden;font:3px/1 a}'].join(''), function( node ) { 705 | bool = node.offsetHeight >= 3; 706 | }); 707 | 708 | return bool; 709 | }; 710 | 711 | 712 | 713 | // These tests evaluate support of the video/audio elements, as well as 714 | // testing what types of content they support. 715 | // 716 | // We're using the Boolean constructor here, so that we can extend the value 717 | // e.g. Modernizr.video // true 718 | // Modernizr.video.ogg // 'probably' 719 | // 720 | // Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845 721 | // thx to NielsLeenheer and zcorpan 722 | 723 | // Note: in some older browsers, "no" was a return value instead of empty string. 724 | // It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2 725 | // It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5 726 | 727 | tests['video'] = function() { 728 | var elem = document.createElement('video'), 729 | bool = false; 730 | 731 | // IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224 732 | try { 733 | if ( bool = !!elem.canPlayType ) { 734 | bool = new Boolean(bool); 735 | bool.ogg = elem.canPlayType('video/ogg; codecs="theora"') .replace(/^no$/,''); 736 | 737 | // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546 738 | bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"') .replace(/^no$/,''); 739 | 740 | bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,''); 741 | } 742 | 743 | } catch(e) { } 744 | 745 | return bool; 746 | }; 747 | 748 | tests['audio'] = function() { 749 | var elem = document.createElement('audio'), 750 | bool = false; 751 | 752 | try { 753 | if ( bool = !!elem.canPlayType ) { 754 | bool = new Boolean(bool); 755 | bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,''); 756 | bool.mp3 = elem.canPlayType('audio/mpeg;') .replace(/^no$/,''); 757 | 758 | // Mimetypes accepted: 759 | // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements 760 | // bit.ly/iphoneoscodecs 761 | bool.wav = elem.canPlayType('audio/wav; codecs="1"') .replace(/^no$/,''); 762 | bool.m4a = ( elem.canPlayType('audio/x-m4a;') || 763 | elem.canPlayType('audio/aac;')) .replace(/^no$/,''); 764 | } 765 | } catch(e) { } 766 | 767 | return bool; 768 | }; 769 | 770 | 771 | // In FF4, if disabled, window.localStorage should === null. 772 | 773 | // Normally, we could not test that directly and need to do a 774 | // `('localStorage' in window) && ` test first because otherwise Firefox will 775 | // throw bugzil.la/365772 if cookies are disabled 776 | 777 | // Also in iOS5 Private Browsing mode, attempting to use localStorage.setItem 778 | // will throw the exception: 779 | // QUOTA_EXCEEDED_ERRROR DOM Exception 22. 780 | // Peculiarly, getItem and removeItem calls do not throw. 781 | 782 | // Because we are forced to try/catch this, we'll go aggressive. 783 | 784 | // Just FWIW: IE8 Compat mode supports these features completely: 785 | // www.quirksmode.org/dom/html5.html 786 | // But IE8 doesn't support either with local files 787 | 788 | tests['localstorage'] = function() { 789 | try { 790 | localStorage.setItem(mod, mod); 791 | localStorage.removeItem(mod); 792 | return true; 793 | } catch(e) { 794 | return false; 795 | } 796 | }; 797 | 798 | tests['sessionstorage'] = function() { 799 | try { 800 | sessionStorage.setItem(mod, mod); 801 | sessionStorage.removeItem(mod); 802 | return true; 803 | } catch(e) { 804 | return false; 805 | } 806 | }; 807 | 808 | 809 | tests['webworkers'] = function() { 810 | return !!window.Worker; 811 | }; 812 | 813 | 814 | tests['applicationcache'] = function() { 815 | return !!window.applicationCache; 816 | }; 817 | 818 | 819 | // Thanks to Erik Dahlstrom 820 | tests['svg'] = function() { 821 | return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect; 822 | }; 823 | 824 | // specifically for SVG inline in HTML, not within XHTML 825 | // test page: paulirish.com/demo/inline-svg 826 | tests['inlinesvg'] = function() { 827 | var div = document.createElement('div'); 828 | div.innerHTML = ''; 829 | return (div.firstChild && div.firstChild.namespaceURI) == ns.svg; 830 | }; 831 | 832 | // SVG SMIL animation 833 | tests['smil'] = function() { 834 | return !!document.createElementNS && /SVGAnimate/.test(toString.call(document.createElementNS(ns.svg, 'animate'))); 835 | }; 836 | 837 | // This test is only for clip paths in SVG proper, not clip paths on HTML content 838 | // demo: srufaculty.sru.edu/david.dailey/svg/newstuff/clipPath4.svg 839 | 840 | // However read the comments to dig into applying SVG clippaths to HTML content here: 841 | // github.com/Modernizr/Modernizr/issues/213#issuecomment-1149491 842 | tests['svgclippaths'] = function() { 843 | return !!document.createElementNS && /SVGClipPath/.test(toString.call(document.createElementNS(ns.svg, 'clipPath'))); 844 | }; 845 | 846 | /*>>webforms*/ 847 | // input features and input types go directly onto the ret object, bypassing the tests loop. 848 | // Hold this guy to execute in a moment. 849 | function webforms() { 850 | /*>>input*/ 851 | // Run through HTML5's new input attributes to see if the UA understands any. 852 | // We're using f which is the element created early on 853 | // Mike Taylr has created a comprehensive resource for testing these attributes 854 | // when applied to all input types: 855 | // miketaylr.com/code/input-type-attr.html 856 | // spec: www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary 857 | 858 | // Only input placeholder is tested while textarea's placeholder is not. 859 | // Currently Safari 4 and Opera 11 have support only for the input placeholder 860 | // Both tests are available in feature-detects/forms-placeholder.js 861 | Modernizr['input'] = (function( props ) { 862 | for ( var i = 0, len = props.length; i < len; i++ ) { 863 | attrs[ props[i] ] = !!(props[i] in inputElem); 864 | } 865 | if (attrs.list){ 866 | // safari false positive's on datalist: webk.it/74252 867 | // see also github.com/Modernizr/Modernizr/issues/146 868 | attrs.list = !!(document.createElement('datalist') && window.HTMLDataListElement); 869 | } 870 | return attrs; 871 | })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' ')); 872 | /*>>input*/ 873 | 874 | /*>>inputtypes*/ 875 | // Run through HTML5's new input types to see if the UA understands any. 876 | // This is put behind the tests runloop because it doesn't return a 877 | // true/false like all the other tests; instead, it returns an object 878 | // containing each input type with its corresponding true/false value 879 | 880 | // Big thanks to @miketaylr for the html5 forms expertise. miketaylr.com/ 881 | Modernizr['inputtypes'] = (function(props) { 882 | 883 | for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) { 884 | 885 | inputElem.setAttribute('type', inputElemType = props[i]); 886 | bool = inputElem.type !== 'text'; 887 | 888 | // We first check to see if the type we give it sticks.. 889 | // If the type does, we feed it a textual value, which shouldn't be valid. 890 | // If the value doesn't stick, we know there's input sanitization which infers a custom UI 891 | if ( bool ) { 892 | 893 | inputElem.value = smile; 894 | inputElem.style.cssText = 'position:absolute;visibility:hidden;'; 895 | 896 | if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) { 897 | 898 | docElement.appendChild(inputElem); 899 | defaultView = document.defaultView; 900 | 901 | // Safari 2-4 allows the smiley as a value, despite making a slider 902 | bool = defaultView.getComputedStyle && 903 | defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' && 904 | // Mobile android web browser has false positive, so must 905 | // check the height to see if the widget is actually there. 906 | (inputElem.offsetHeight !== 0); 907 | 908 | docElement.removeChild(inputElem); 909 | 910 | } else if ( /^(search|tel)$/.test(inputElemType) ){ 911 | // Spec doesn't define any special parsing or detectable UI 912 | // behaviors so we pass these through as true 913 | 914 | // Interestingly, opera fails the earlier test, so it doesn't 915 | // even make it here. 916 | 917 | } else if ( /^(url|email)$/.test(inputElemType) ) { 918 | // Real url and email support comes with prebaked validation. 919 | bool = inputElem.checkValidity && inputElem.checkValidity() === false; 920 | 921 | } else { 922 | // If the upgraded input compontent rejects the :) text, we got a winner 923 | bool = inputElem.value != smile; 924 | } 925 | } 926 | 927 | inputs[ props[i] ] = !!bool; 928 | } 929 | return inputs; 930 | })('search tel url email datetime date month week time datetime-local number range color'.split(' ')); 931 | /*>>inputtypes*/ 932 | } 933 | /*>>webforms*/ 934 | 935 | 936 | // End of test definitions 937 | // ----------------------- 938 | 939 | 940 | 941 | // Run through all tests and detect their support in the current UA. 942 | // todo: hypothetically we could be doing an array of tests and use a basic loop here. 943 | for ( var feature in tests ) { 944 | if ( hasOwnProp(tests, feature) ) { 945 | // run the test, throw the return value into the Modernizr, 946 | // then based on that boolean, define an appropriate className 947 | // and push it into an array of classes we'll join later. 948 | featureName = feature.toLowerCase(); 949 | Modernizr[featureName] = tests[feature](); 950 | 951 | classes.push((Modernizr[featureName] ? '' : 'no-') + featureName); 952 | } 953 | } 954 | 955 | /*>>webforms*/ 956 | // input tests need to run. 957 | Modernizr.input || webforms(); 958 | /*>>webforms*/ 959 | 960 | 961 | /** 962 | * addTest allows the user to define their own feature tests 963 | * the result will be added onto the Modernizr object, 964 | * as well as an appropriate className set on the html element 965 | * 966 | * @param feature - String naming the feature 967 | * @param test - Function returning true if feature is supported, false if not 968 | */ 969 | Modernizr.addTest = function ( feature, test ) { 970 | if ( typeof feature == 'object' ) { 971 | for ( var key in feature ) { 972 | if ( hasOwnProp( feature, key ) ) { 973 | Modernizr.addTest( key, feature[ key ] ); 974 | } 975 | } 976 | } else { 977 | 978 | feature = feature.toLowerCase(); 979 | 980 | if ( Modernizr[feature] !== undefined ) { 981 | // we're going to quit if you're trying to overwrite an existing test 982 | // if we were to allow it, we'd do this: 983 | // var re = new RegExp("\\b(no-)?" + feature + "\\b"); 984 | // docElement.className = docElement.className.replace( re, '' ); 985 | // but, no rly, stuff 'em. 986 | return Modernizr; 987 | } 988 | 989 | test = typeof test == 'function' ? test() : test; 990 | 991 | if (typeof enableClasses !== "undefined" && enableClasses) { 992 | docElement.className += ' ' + (test ? '' : 'no-') + feature; 993 | } 994 | Modernizr[feature] = test; 995 | 996 | } 997 | 998 | return Modernizr; // allow chaining. 999 | }; 1000 | 1001 | 1002 | // Reset modElem.cssText to nothing to reduce memory footprint. 1003 | setCss(''); 1004 | modElem = inputElem = null; 1005 | 1006 | /*>>shiv*/ 1007 | /** 1008 | * @preserve HTML5 Shiv prev3.7.1 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed 1009 | */ 1010 | ;(function(window, document) { 1011 | /*jshint evil:true */ 1012 | /** version */ 1013 | var version = '3.7.0'; 1014 | 1015 | /** Preset options */ 1016 | var options = window.html5 || {}; 1017 | 1018 | /** Used to skip problem elements */ 1019 | var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i; 1020 | 1021 | /** Not all elements can be cloned in IE **/ 1022 | var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i; 1023 | 1024 | /** Detect whether the browser supports default html5 styles */ 1025 | var supportsHtml5Styles; 1026 | 1027 | /** Name of the expando, to work with multiple documents or to re-shiv one document */ 1028 | var expando = '_html5shiv'; 1029 | 1030 | /** The id for the the documents expando */ 1031 | var expanID = 0; 1032 | 1033 | /** Cached data for each document */ 1034 | var expandoData = {}; 1035 | 1036 | /** Detect whether the browser supports unknown elements */ 1037 | var supportsUnknownElements; 1038 | 1039 | (function() { 1040 | try { 1041 | var a = document.createElement('a'); 1042 | a.innerHTML = ''; 1043 | //if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles 1044 | supportsHtml5Styles = ('hidden' in a); 1045 | 1046 | supportsUnknownElements = a.childNodes.length == 1 || (function() { 1047 | // assign a false positive if unable to shiv 1048 | (document.createElement)('a'); 1049 | var frag = document.createDocumentFragment(); 1050 | return ( 1051 | typeof frag.cloneNode == 'undefined' || 1052 | typeof frag.createDocumentFragment == 'undefined' || 1053 | typeof frag.createElement == 'undefined' 1054 | ); 1055 | }()); 1056 | } catch(e) { 1057 | // assign a false positive if detection fails => unable to shiv 1058 | supportsHtml5Styles = true; 1059 | supportsUnknownElements = true; 1060 | } 1061 | 1062 | }()); 1063 | 1064 | /*--------------------------------------------------------------------------*/ 1065 | 1066 | /** 1067 | * Creates a style sheet with the given CSS text and adds it to the document. 1068 | * @private 1069 | * @param {Document} ownerDocument The document. 1070 | * @param {String} cssText The CSS text. 1071 | * @returns {StyleSheet} The style element. 1072 | */ 1073 | function addStyleSheet(ownerDocument, cssText) { 1074 | var p = ownerDocument.createElement('p'), 1075 | parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement; 1076 | 1077 | p.innerHTML = 'x'; 1078 | return parent.insertBefore(p.lastChild, parent.firstChild); 1079 | } 1080 | 1081 | /** 1082 | * Returns the value of `html5.elements` as an array. 1083 | * @private 1084 | * @returns {Array} An array of shived element node names. 1085 | */ 1086 | function getElements() { 1087 | var elements = html5.elements; 1088 | return typeof elements == 'string' ? elements.split(' ') : elements; 1089 | } 1090 | 1091 | /** 1092 | * Returns the data associated to the given document 1093 | * @private 1094 | * @param {Document} ownerDocument The document. 1095 | * @returns {Object} An object of data. 1096 | */ 1097 | function getExpandoData(ownerDocument) { 1098 | var data = expandoData[ownerDocument[expando]]; 1099 | if (!data) { 1100 | data = {}; 1101 | expanID++; 1102 | ownerDocument[expando] = expanID; 1103 | expandoData[expanID] = data; 1104 | } 1105 | return data; 1106 | } 1107 | 1108 | /** 1109 | * returns a shived element for the given nodeName and document 1110 | * @memberOf html5 1111 | * @param {String} nodeName name of the element 1112 | * @param {Document} ownerDocument The context document. 1113 | * @returns {Object} The shived element. 1114 | */ 1115 | function createElement(nodeName, ownerDocument, data){ 1116 | if (!ownerDocument) { 1117 | ownerDocument = document; 1118 | } 1119 | if(supportsUnknownElements){ 1120 | return ownerDocument.createElement(nodeName); 1121 | } 1122 | if (!data) { 1123 | data = getExpandoData(ownerDocument); 1124 | } 1125 | var node; 1126 | 1127 | if (data.cache[nodeName]) { 1128 | node = data.cache[nodeName].cloneNode(); 1129 | } else if (saveClones.test(nodeName)) { 1130 | node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode(); 1131 | } else { 1132 | node = data.createElem(nodeName); 1133 | } 1134 | 1135 | // Avoid adding some elements to fragments in IE < 9 because 1136 | // * Attributes like `name` or `type` cannot be set/changed once an element 1137 | // is inserted into a document/fragment 1138 | // * Link elements with `src` attributes that are inaccessible, as with 1139 | // a 403 response, will cause the tab/window to crash 1140 | // * Script elements appended to fragments will execute when their `src` 1141 | // or `text` property is set 1142 | return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node; 1143 | } 1144 | 1145 | /** 1146 | * returns a shived DocumentFragment for the given document 1147 | * @memberOf html5 1148 | * @param {Document} ownerDocument The context document. 1149 | * @returns {Object} The shived DocumentFragment. 1150 | */ 1151 | function createDocumentFragment(ownerDocument, data){ 1152 | if (!ownerDocument) { 1153 | ownerDocument = document; 1154 | } 1155 | if(supportsUnknownElements){ 1156 | return ownerDocument.createDocumentFragment(); 1157 | } 1158 | data = data || getExpandoData(ownerDocument); 1159 | var clone = data.frag.cloneNode(), 1160 | i = 0, 1161 | elems = getElements(), 1162 | l = elems.length; 1163 | for(;i>shiv*/ 1309 | 1310 | // Assign private properties to the return object with prefix 1311 | Modernizr._version = version; 1312 | 1313 | // expose these for the plugin API. Look in the source for how to join() them against your input 1314 | /*>>prefixes*/ 1315 | Modernizr._prefixes = prefixes; 1316 | /*>>prefixes*/ 1317 | /*>>domprefixes*/ 1318 | Modernizr._domPrefixes = domPrefixes; 1319 | Modernizr._cssomPrefixes = cssomPrefixes; 1320 | /*>>domprefixes*/ 1321 | 1322 | /*>>mq*/ 1323 | // Modernizr.mq tests a given media query, live against the current state of the window 1324 | // A few important notes: 1325 | // * If a browser does not support media queries at all (eg. oldIE) the mq() will always return false 1326 | // * A max-width or orientation query will be evaluated against the current state, which may change later. 1327 | // * You must specify values. Eg. If you are testing support for the min-width media query use: 1328 | // Modernizr.mq('(min-width:0)') 1329 | // usage: 1330 | // Modernizr.mq('only screen and (max-width:768)') 1331 | Modernizr.mq = testMediaQuery; 1332 | /*>>mq*/ 1333 | 1334 | /*>>hasevent*/ 1335 | // Modernizr.hasEvent() detects support for a given event, with an optional element to test on 1336 | // Modernizr.hasEvent('gesturestart', elem) 1337 | Modernizr.hasEvent = isEventSupported; 1338 | /*>>hasevent*/ 1339 | 1340 | /*>>testprop*/ 1341 | // Modernizr.testProp() investigates whether a given style property is recognized 1342 | // Note that the property names must be provided in the camelCase variant. 1343 | // Modernizr.testProp('pointerEvents') 1344 | Modernizr.testProp = function(prop){ 1345 | return testProps([prop]); 1346 | }; 1347 | /*>>testprop*/ 1348 | 1349 | /*>>testallprops*/ 1350 | // Modernizr.testAllProps() investigates whether a given style property, 1351 | // or any of its vendor-prefixed variants, is recognized 1352 | // Note that the property names must be provided in the camelCase variant. 1353 | // Modernizr.testAllProps('boxSizing') 1354 | Modernizr.testAllProps = testPropsAll; 1355 | /*>>testallprops*/ 1356 | 1357 | 1358 | /*>>teststyles*/ 1359 | // Modernizr.testStyles() allows you to add custom styles to the document and test an element afterwards 1360 | // Modernizr.testStyles('#modernizr { position:absolute }', function(elem, rule){ ... }) 1361 | Modernizr.testStyles = injectElementWithStyles; 1362 | /*>>teststyles*/ 1363 | 1364 | 1365 | /*>>prefixed*/ 1366 | // Modernizr.prefixed() returns the prefixed or nonprefixed property name variant of your input 1367 | // Modernizr.prefixed('boxSizing') // 'MozBoxSizing' 1368 | 1369 | // Properties must be passed as dom-style camelcase, rather than `box-sizing` hypentated style. 1370 | // Return values will also be the camelCase variant, if you need to translate that to hypenated style use: 1371 | // 1372 | // str.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-'); 1373 | 1374 | // If you're trying to ascertain which transition end event to bind to, you might do something like... 1375 | // 1376 | // var transEndEventNames = { 1377 | // 'WebkitTransition' : 'webkitTransitionEnd', 1378 | // 'MozTransition' : 'transitionend', 1379 | // 'OTransition' : 'oTransitionEnd', 1380 | // 'msTransition' : 'MSTransitionEnd', 1381 | // 'transition' : 'transitionend' 1382 | // }, 1383 | // transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ]; 1384 | 1385 | Modernizr.prefixed = function(prop, obj, elem){ 1386 | if(!obj) { 1387 | return testPropsAll(prop, 'pfx'); 1388 | } else { 1389 | // Testing DOM property e.g. Modernizr.prefixed('requestAnimationFrame', window) // 'mozRequestAnimationFrame' 1390 | return testPropsAll(prop, obj, elem); 1391 | } 1392 | }; 1393 | /*>>prefixed*/ 1394 | 1395 | 1396 | /*>>cssclasses*/ 1397 | // Remove "no-js" class from element, if it exists: 1398 | docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') + 1399 | 1400 | // Add the new classes to the element. 1401 | (enableClasses ? ' js ' + classes.join(' ') : ''); 1402 | /*>>cssclasses*/ 1403 | 1404 | return Modernizr; 1405 | 1406 | })(this, this.document); 1407 | -------------------------------------------------------------------------------- /examples/module.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var universe = require('./universe'); 3 | universe.start(); 4 | console.log('The answer is ' + universe.answer); 5 | phantom.exit(); 6 | -------------------------------------------------------------------------------- /examples/netlog.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var page = require('webpage').create(), 3 | system = require('system'), 4 | address; 5 | 6 | if (system.args.length === 1) { 7 | console.log('Usage: netlog.js '); 8 | phantom.exit(1); 9 | } else { 10 | address = system.args[1]; 11 | 12 | page.onResourceRequested = function (req) { 13 | console.log('requested: ' + JSON.stringify(req, undefined, 4)); 14 | }; 15 | 16 | page.onResourceReceived = function (res) { 17 | console.log('received: ' + JSON.stringify(res, undefined, 4)); 18 | }; 19 | 20 | page.open(address, function (status) { 21 | if (status !== 'success') { 22 | console.log('FAIL to load the address'); 23 | } 24 | phantom.exit(); 25 | }); 26 | } 27 | -------------------------------------------------------------------------------- /examples/netsniff.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | if (!Date.prototype.toISOString) { 3 | Date.prototype.toISOString = function () { 4 | function pad(n) { return n < 10 ? '0' + n : n; } 5 | function ms(n) { return n < 10 ? '00'+ n : n < 100 ? '0' + n : n } 6 | return this.getFullYear() + '-' + 7 | pad(this.getMonth() + 1) + '-' + 8 | pad(this.getDate()) + 'T' + 9 | pad(this.getHours()) + ':' + 10 | pad(this.getMinutes()) + ':' + 11 | pad(this.getSeconds()) + '.' + 12 | ms(this.getMilliseconds()) + 'Z'; 13 | } 14 | } 15 | 16 | function createHAR(address, title, startTime, resources) 17 | { 18 | var entries = []; 19 | 20 | resources.forEach(function (resource) { 21 | var request = resource.request, 22 | startReply = resource.startReply, 23 | endReply = resource.endReply; 24 | 25 | if (!request || !startReply || !endReply) { 26 | return; 27 | } 28 | 29 | // Exclude Data URI from HAR file because 30 | // they aren't included in specification 31 | if (request.url.match(/(^data:image\/.*)/i)) { 32 | return; 33 | } 34 | 35 | entries.push({ 36 | startedDateTime: request.time.toISOString(), 37 | time: endReply.time - request.time, 38 | request: { 39 | method: request.method, 40 | url: request.url, 41 | httpVersion: "HTTP/1.1", 42 | cookies: [], 43 | headers: request.headers, 44 | queryString: [], 45 | headersSize: -1, 46 | bodySize: -1 47 | }, 48 | response: { 49 | status: endReply.status, 50 | statusText: endReply.statusText, 51 | httpVersion: "HTTP/1.1", 52 | cookies: [], 53 | headers: endReply.headers, 54 | redirectURL: "", 55 | headersSize: -1, 56 | bodySize: startReply.bodySize, 57 | content: { 58 | size: startReply.bodySize, 59 | mimeType: endReply.contentType 60 | } 61 | }, 62 | cache: {}, 63 | timings: { 64 | blocked: 0, 65 | dns: -1, 66 | connect: -1, 67 | send: 0, 68 | wait: startReply.time - request.time, 69 | receive: endReply.time - startReply.time, 70 | ssl: -1 71 | }, 72 | pageref: address 73 | }); 74 | }); 75 | 76 | return { 77 | log: { 78 | version: '1.2', 79 | creator: { 80 | name: "PhantomJS", 81 | version: phantom.version.major + '.' + phantom.version.minor + 82 | '.' + phantom.version.patch 83 | }, 84 | pages: [{ 85 | startedDateTime: startTime.toISOString(), 86 | id: address, 87 | title: title, 88 | pageTimings: { 89 | onLoad: page.endTime - page.startTime 90 | } 91 | }], 92 | entries: entries 93 | } 94 | }; 95 | } 96 | 97 | var page = require('webpage').create(), 98 | system = require('system'); 99 | 100 | if (system.args.length === 1) { 101 | console.log('Usage: netsniff.js '); 102 | phantom.exit(1); 103 | } else { 104 | 105 | page.address = system.args[1]; 106 | page.resources = []; 107 | 108 | page.onLoadStarted = function () { 109 | page.startTime = new Date(); 110 | }; 111 | 112 | page.onResourceRequested = function (req) { 113 | page.resources[req.id] = { 114 | request: req, 115 | startReply: null, 116 | endReply: null 117 | }; 118 | }; 119 | 120 | page.onResourceReceived = function (res) { 121 | if (res.stage === 'start') { 122 | page.resources[res.id].startReply = res; 123 | } 124 | if (res.stage === 'end') { 125 | page.resources[res.id].endReply = res; 126 | } 127 | }; 128 | 129 | page.open(page.address, function (status) { 130 | var har; 131 | if (status !== 'success') { 132 | console.log('FAIL to load the address'); 133 | phantom.exit(1); 134 | } else { 135 | page.endTime = new Date(); 136 | page.title = page.evaluate(function () { 137 | return document.title; 138 | }); 139 | har = createHAR(page.address, page.title, page.startTime, page.resources); 140 | console.log(JSON.stringify(har, undefined, 4)); 141 | phantom.exit(); 142 | } 143 | }); 144 | } 145 | -------------------------------------------------------------------------------- /examples/openurlwithproxy.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var page = require('webpage').create(), 3 | system = require('system'), 4 | host, port, address; 5 | 6 | if (system.args.length < 4) { 7 | console.log('Usage: openurlwithproxy.js '); 8 | phantom.exit(1); 9 | } else { 10 | host = system.args[1]; 11 | port = system.args[2]; 12 | address = system.args[3]; 13 | phantom.setProxy(host, port, 'manual', '', ''); 14 | page.open(address, function (status) { 15 | if (status !== 'success') { 16 | console.log('FAIL to load the address "' + 17 | address + '" using proxy "' + host + ':' + port + '"'); 18 | } else { 19 | console.log('Page title is ' + page.evaluate(function () { 20 | return document.title; 21 | })); 22 | } 23 | phantom.exit(); 24 | }); 25 | } 26 | -------------------------------------------------------------------------------- /examples/outputEncoding.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | function helloWorld() { 3 | console.log(phantom.outputEncoding + ": こんにちは、世界!"); 4 | } 5 | 6 | console.log("Using default encoding..."); 7 | helloWorld(); 8 | 9 | console.log("\nUsing other encodings..."); 10 | 11 | var encodings = ["euc-jp", "sjis", "utf8", "System"]; 12 | for (var i = 0; i < encodings.length; i++) { 13 | phantom.outputEncoding = encodings[i]; 14 | helloWorld(); 15 | } 16 | 17 | phantom.exit() 18 | -------------------------------------------------------------------------------- /examples/page_events.js: -------------------------------------------------------------------------------- 1 | // The purpose of this is to show how and when events fire, considering 5 steps 2 | // happening as follows: 3 | // 4 | // 1. Load URL 5 | // 2. Load same URL, but adding an internal FRAGMENT to it 6 | // 3. Click on an internal Link, that points to another internal FRAGMENT 7 | // 4. Click on an external Link, that will send the page somewhere else 8 | // 5. Close page 9 | // 10 | // Take particular care when going through the output, to understand when 11 | // things happen (and in which order). Particularly, notice what DOESN'T 12 | // happen during step 3. 13 | // 14 | // If invoked with "-v" it will print out the Page Resources as they are 15 | // Requested and Received. 16 | // 17 | // NOTE.1: The "onConsoleMessage/onAlert/onPrompt/onConfirm" events are 18 | // registered but not used here. This is left for you to have fun with. 19 | // NOTE.2: This script is not here to teach you ANY JavaScript. It's aweful! 20 | // NOTE.3: Main audience for this are people new to PhantomJS. 21 | 22 | "use strict"; 23 | var sys = require("system"), 24 | page = require("webpage").create(), 25 | logResources = false, 26 | step1url = "http://en.wikipedia.org/wiki/DOM_events", 27 | step2url = "http://en.wikipedia.org/wiki/DOM_events#Event_flow"; 28 | 29 | if (sys.args.length > 1 && sys.args[1] === "-v") { 30 | logResources = true; 31 | } 32 | 33 | function printArgs() { 34 | var i, ilen; 35 | for (i = 0, ilen = arguments.length; i < ilen; ++i) { 36 | console.log(" arguments[" + i + "] = " + JSON.stringify(arguments[i])); 37 | } 38 | console.log(""); 39 | } 40 | 41 | //////////////////////////////////////////////////////////////////////////////// 42 | 43 | page.onInitialized = function() { 44 | console.log("page.onInitialized"); 45 | printArgs.apply(this, arguments); 46 | }; 47 | page.onLoadStarted = function() { 48 | console.log("page.onLoadStarted"); 49 | printArgs.apply(this, arguments); 50 | }; 51 | page.onLoadFinished = function() { 52 | console.log("page.onLoadFinished"); 53 | printArgs.apply(this, arguments); 54 | }; 55 | page.onUrlChanged = function() { 56 | console.log("page.onUrlChanged"); 57 | printArgs.apply(this, arguments); 58 | }; 59 | page.onNavigationRequested = function() { 60 | console.log("page.onNavigationRequested"); 61 | printArgs.apply(this, arguments); 62 | }; 63 | page.onRepaintRequested = function() { 64 | console.log("page.onRepaintRequested"); 65 | printArgs.apply(this, arguments); 66 | }; 67 | 68 | if (logResources === true) { 69 | page.onResourceRequested = function() { 70 | console.log("page.onResourceRequested"); 71 | printArgs.apply(this, arguments); 72 | }; 73 | page.onResourceReceived = function() { 74 | console.log("page.onResourceReceived"); 75 | printArgs.apply(this, arguments); 76 | }; 77 | } 78 | 79 | page.onClosing = function() { 80 | console.log("page.onClosing"); 81 | printArgs.apply(this, arguments); 82 | }; 83 | 84 | // window.console.log(msg); 85 | page.onConsoleMessage = function() { 86 | console.log("page.onConsoleMessage"); 87 | printArgs.apply(this, arguments); 88 | }; 89 | 90 | // window.alert(msg); 91 | page.onAlert = function() { 92 | console.log("page.onAlert"); 93 | printArgs.apply(this, arguments); 94 | }; 95 | // var confirmed = window.confirm(msg); 96 | page.onConfirm = function() { 97 | console.log("page.onConfirm"); 98 | printArgs.apply(this, arguments); 99 | }; 100 | // var user_value = window.prompt(msg, default_value); 101 | page.onPrompt = function() { 102 | console.log("page.onPrompt"); 103 | printArgs.apply(this, arguments); 104 | }; 105 | 106 | //////////////////////////////////////////////////////////////////////////////// 107 | 108 | setTimeout(function() { 109 | console.log(""); 110 | console.log("### STEP 1: Load '" + step1url + "'"); 111 | page.open(step1url); 112 | }, 0); 113 | 114 | setTimeout(function() { 115 | console.log(""); 116 | console.log("### STEP 2: Load '" + step2url + "' (load same URL plus FRAGMENT)"); 117 | page.open(step2url); 118 | }, 5000); 119 | 120 | setTimeout(function() { 121 | console.log(""); 122 | console.log("### STEP 3: Click on page internal link (aka FRAGMENT)"); 123 | page.evaluate(function() { 124 | var ev = document.createEvent("MouseEvents"); 125 | ev.initEvent("click", true, true); 126 | document.querySelector("a[href='#Event_object']").dispatchEvent(ev); 127 | }); 128 | }, 10000); 129 | 130 | setTimeout(function() { 131 | console.log(""); 132 | console.log("### STEP 4: Click on page external link"); 133 | page.evaluate(function() { 134 | var ev = document.createEvent("MouseEvents"); 135 | ev.initEvent("click", true, true); 136 | document.querySelector("a[title='JavaScript']").dispatchEvent(ev); 137 | }); 138 | }, 15000); 139 | 140 | setTimeout(function() { 141 | console.log(""); 142 | console.log("### STEP 5: Close page and shutdown (with a delay)"); 143 | page.close(); 144 | setTimeout(function(){ 145 | phantom.exit(); 146 | }, 100); 147 | }, 20000); 148 | -------------------------------------------------------------------------------- /examples/pagecallback.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var p = require("webpage").create(); 3 | 4 | p.onConsoleMessage = function(msg) { console.log(msg); }; 5 | 6 | // Calls to "callPhantom" within the page 'p' arrive here 7 | p.onCallback = function(msg) { 8 | console.log("Received by the 'phantom' main context: "+msg); 9 | return "Hello there, I'm coming to you from the 'phantom' context instead"; 10 | }; 11 | 12 | p.evaluate(function() { 13 | // Return-value of the "onCallback" handler arrive here 14 | var callbackResponse = window.callPhantom("Hello, I'm coming to you from the 'page' context"); 15 | console.log("Received by the 'page' context: "+callbackResponse); 16 | }); 17 | 18 | phantom.exit(); 19 | -------------------------------------------------------------------------------- /examples/phantomwebintro.js: -------------------------------------------------------------------------------- 1 | // Read the Phantom webpage '#intro' element text using jQuery and "includeJs" 2 | 3 | "use strict"; 4 | var page = require('webpage').create(); 5 | 6 | page.onConsoleMessage = function(msg) { 7 | console.log(msg); 8 | }; 9 | 10 | page.open("http://phantomjs.org/", function(status) { 11 | if (status === "success") { 12 | page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() { 13 | page.evaluate(function() { 14 | console.log("$(\".explanation\").text() -> " + $(".explanation").text()); 15 | }); 16 | phantom.exit(0); 17 | }); 18 | } else { 19 | phantom.exit(1); 20 | } 21 | }); 22 | -------------------------------------------------------------------------------- /examples/post.js: -------------------------------------------------------------------------------- 1 | // Example using HTTP POST operation 2 | 3 | "use strict"; 4 | var page = require('webpage').create(), 5 | server = 'http://posttestserver.com/post.php?dump', 6 | data = 'universe=expanding&answer=42'; 7 | 8 | page.open(server, 'post', data, function (status) { 9 | if (status !== 'success') { 10 | console.log('Unable to post!'); 11 | } else { 12 | console.log(page.content); 13 | } 14 | phantom.exit(); 15 | }); 16 | -------------------------------------------------------------------------------- /examples/postjson.js: -------------------------------------------------------------------------------- 1 | // Example using HTTP POST operation 2 | 3 | "use strict"; 4 | var page = require('webpage').create(), 5 | server = 'http://posttestserver.com/post.php?dump', 6 | data = '{"universe": "expanding", "answer": 42}'; 7 | 8 | var headers = { 9 | "Content-Type": "application/json" 10 | } 11 | 12 | page.open(server, 'post', data, headers, function (status) { 13 | if (status !== 'success') { 14 | console.log('Unable to post!'); 15 | } else { 16 | console.log(page.content); 17 | } 18 | phantom.exit(); 19 | }); 20 | -------------------------------------------------------------------------------- /examples/postserver.js: -------------------------------------------------------------------------------- 1 | // Example using HTTP POST operation 2 | 3 | "use strict"; 4 | var page = require('webpage').create(), 5 | server = require('webserver').create(), 6 | system = require('system'), 7 | data = 'universe=expanding&answer=42'; 8 | 9 | if (system.args.length !== 2) { 10 | console.log('Usage: postserver.js '); 11 | phantom.exit(1); 12 | } 13 | 14 | var port = system.args[1]; 15 | 16 | service = server.listen(port, function (request, response) { 17 | console.log('Request received at ' + new Date()); 18 | 19 | response.statusCode = 200; 20 | response.headers = { 21 | 'Cache': 'no-cache', 22 | 'Content-Type': 'text/plain;charset=utf-8' 23 | }; 24 | response.write(JSON.stringify(request, null, 4)); 25 | response.close(); 26 | }); 27 | 28 | page.open('http://localhost:' + port + '/', 'post', data, function (status) { 29 | if (status !== 'success') { 30 | console.log('Unable to post!'); 31 | } else { 32 | console.log(page.plainText); 33 | } 34 | phantom.exit(); 35 | }); 36 | -------------------------------------------------------------------------------- /examples/printenv.js: -------------------------------------------------------------------------------- 1 | var system = require('system'), 2 | env = system.env, 3 | key; 4 | 5 | for (key in env) { 6 | if (env.hasOwnProperty(key)) { 7 | console.log(key + '=' + env[key]); 8 | } 9 | } 10 | phantom.exit(); 11 | -------------------------------------------------------------------------------- /examples/printheaderfooter.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var page = require('webpage').create(), 3 | system = require('system'); 4 | 5 | function someCallback(pageNum, numPages) { 6 | return "

someCallback: " + pageNum + " / " + numPages + "

"; 7 | } 8 | 9 | if (system.args.length < 3) { 10 | console.log('Usage: printheaderfooter.js URL filename'); 11 | phantom.exit(1); 12 | } else { 13 | var address = system.args[1]; 14 | var output = system.args[2]; 15 | page.viewportSize = { width: 600, height: 600 }; 16 | page.paperSize = { 17 | format: 'A4', 18 | margin: "1cm", 19 | /* default header/footer for pages that don't have custom overwrites (see below) */ 20 | header: { 21 | height: "1cm", 22 | contents: phantom.callback(function(pageNum, numPages) { 23 | if (pageNum == 1) { 24 | return ""; 25 | } 26 | return "

Header " + pageNum + " / " + numPages + "

"; 27 | }) 28 | }, 29 | footer: { 30 | height: "1cm", 31 | contents: phantom.callback(function(pageNum, numPages) { 32 | if (pageNum == numPages) { 33 | return ""; 34 | } 35 | return "

Footer " + pageNum + " / " + numPages + "

"; 36 | }) 37 | } 38 | }; 39 | page.open(address, function (status) { 40 | if (status !== 'success') { 41 | console.log('Unable to load the address!'); 42 | } else { 43 | /* check whether the loaded page overwrites the header/footer setting, 44 | i.e. whether a PhantomJSPriting object exists. Use that then instead 45 | of our defaults above. 46 | 47 | example: 48 | 49 | 50 | 62 | 63 |

asdfadsf

asdfadsfycvx

64 | 65 | */ 66 | if (page.evaluate(function(){return typeof PhantomJSPrinting == "object";})) { 67 | paperSize = page.paperSize; 68 | paperSize.header.height = page.evaluate(function() { 69 | return PhantomJSPrinting.header.height; 70 | }); 71 | paperSize.header.contents = phantom.callback(function(pageNum, numPages) { 72 | return page.evaluate(function(pageNum, numPages){return PhantomJSPrinting.header.contents(pageNum, numPages);}, pageNum, numPages); 73 | }); 74 | paperSize.footer.height = page.evaluate(function() { 75 | return PhantomJSPrinting.footer.height; 76 | }); 77 | paperSize.footer.contents = phantom.callback(function(pageNum, numPages) { 78 | return page.evaluate(function(pageNum, numPages){return PhantomJSPrinting.footer.contents(pageNum, numPages);}, pageNum, numPages); 79 | }); 80 | page.paperSize = paperSize; 81 | console.log(page.paperSize.header.height); 82 | console.log(page.paperSize.footer.height); 83 | } 84 | window.setTimeout(function () { 85 | page.render(output); 86 | phantom.exit(); 87 | }, 200); 88 | } 89 | }); 90 | } 91 | -------------------------------------------------------------------------------- /examples/printmargins.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var page = require('webpage').create(), 3 | system = require('system'); 4 | 5 | if (system.args.length < 7) { 6 | console.log('Usage: printmargins.js URL filename LEFT TOP RIGHT BOTTOM'); 7 | console.log(' margin examples: "1cm", "10px", "7mm", "5in"'); 8 | phantom.exit(1); 9 | } else { 10 | var address = system.args[1]; 11 | var output = system.args[2]; 12 | var marginLeft = system.args[3]; 13 | var marginTop = system.args[4]; 14 | var marginRight = system.args[5]; 15 | var marginBottom = system.args[6]; 16 | page.viewportSize = { width: 600, height: 600 }; 17 | page.paperSize = { 18 | format: 'A4', 19 | margin: { 20 | left: marginLeft, 21 | top: marginTop, 22 | right: marginRight, 23 | bottom: marginBottom 24 | } 25 | }; 26 | page.open(address, function (status) { 27 | if (status !== 'success') { 28 | console.log('Unable to load the address!'); 29 | } else { 30 | window.setTimeout(function () { 31 | page.render(output); 32 | phantom.exit(); 33 | }, 200); 34 | } 35 | }); 36 | } 37 | -------------------------------------------------------------------------------- /examples/rasterize.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var page = require('webpage').create(), 3 | system = require('system'), 4 | address, output, size; 5 | 6 | if (system.args.length < 3 || system.args.length > 5) { 7 | console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]'); 8 | console.log(' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"'); 9 | console.log(' image (png/jpg output) examples: "1920px" entire page, window width 1920px'); 10 | console.log(' "800px*600px" window, clipped to 800x600'); 11 | phantom.exit(1); 12 | } else { 13 | address = system.args[1]; 14 | output = system.args[2]; 15 | page.viewportSize = { width: 600, height: 600 }; 16 | if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") { 17 | size = system.args[3].split('*'); 18 | page.paperSize = size.length === 2 ? { width: size[0], height: size[1], margin: '0px' } 19 | : { format: system.args[3], orientation: 'portrait', margin: '1cm' }; 20 | } else if (system.args.length > 3 && system.args[3].substr(-2) === "px") { 21 | size = system.args[3].split('*'); 22 | if (size.length === 2) { 23 | pageWidth = parseInt(size[0], 10); 24 | pageHeight = parseInt(size[1], 10); 25 | page.viewportSize = { width: pageWidth, height: pageHeight }; 26 | page.clipRect = { top: 0, left: 0, width: pageWidth, height: pageHeight }; 27 | } else { 28 | console.log("size:", system.args[3]); 29 | pageWidth = parseInt(system.args[3], 10); 30 | pageHeight = parseInt(pageWidth * 3/4, 10); // it's as good an assumption as any 31 | console.log ("pageHeight:",pageHeight); 32 | page.viewportSize = { width: pageWidth, height: pageHeight }; 33 | } 34 | } 35 | if (system.args.length > 4) { 36 | page.zoomFactor = system.args[4]; 37 | } 38 | page.open(address, function (status) { 39 | if (status !== 'success') { 40 | console.log('Unable to load the address!'); 41 | phantom.exit(1); 42 | } else { 43 | window.setTimeout(function () { 44 | page.render(output); 45 | phantom.exit(); 46 | }, 200); 47 | } 48 | }); 49 | } 50 | -------------------------------------------------------------------------------- /examples/render_multi_url.js: -------------------------------------------------------------------------------- 1 | // Render Multiple URLs to file 2 | 3 | "use strict"; 4 | var RenderUrlsToFile, arrayOfUrls, system; 5 | 6 | system = require("system"); 7 | 8 | /* 9 | Render given urls 10 | @param array of URLs to render 11 | @param callbackPerUrl Function called after finishing each URL, including the last URL 12 | @param callbackFinal Function called after finishing everything 13 | */ 14 | RenderUrlsToFile = function(urls, callbackPerUrl, callbackFinal) { 15 | var getFilename, next, page, retrieve, urlIndex, webpage; 16 | urlIndex = 0; 17 | webpage = require("webpage"); 18 | page = null; 19 | getFilename = function() { 20 | return "rendermulti-" + urlIndex + ".png"; 21 | }; 22 | next = function(status, url, file) { 23 | page.close(); 24 | callbackPerUrl(status, url, file); 25 | return retrieve(); 26 | }; 27 | retrieve = function() { 28 | var url; 29 | if (urls.length > 0) { 30 | url = urls.shift(); 31 | urlIndex++; 32 | page = webpage.create(); 33 | page.viewportSize = { 34 | width: 800, 35 | height: 600 36 | }; 37 | page.settings.userAgent = "Phantom.js bot"; 38 | return page.open("http://" + url, function(status) { 39 | var file; 40 | file = getFilename(); 41 | if (status === "success") { 42 | return window.setTimeout((function() { 43 | page.render(file); 44 | return next(status, url, file); 45 | }), 200); 46 | } else { 47 | return next(status, url, file); 48 | } 49 | }); 50 | } else { 51 | return callbackFinal(); 52 | } 53 | }; 54 | return retrieve(); 55 | }; 56 | 57 | arrayOfUrls = null; 58 | 59 | if (system.args.length > 1) { 60 | arrayOfUrls = Array.prototype.slice.call(system.args, 1); 61 | } else { 62 | console.log("Usage: phantomjs render_multi_url.js [domain.name1, domain.name2, ...]"); 63 | arrayOfUrls = ["www.google.com", "www.bbc.co.uk", "phantomjs.org"]; 64 | } 65 | 66 | RenderUrlsToFile(arrayOfUrls, (function(status, url, file) { 67 | if (status !== "success") { 68 | return console.log("Unable to render '" + url + "'"); 69 | } else { 70 | return console.log("Rendered '" + url + "' at '" + file + "'"); 71 | } 72 | }), function() { 73 | return phantom.exit(); 74 | }); 75 | -------------------------------------------------------------------------------- /examples/responsive-screenshot.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Captures the full height document even if it's not showing on the screen or captures with the provided range of screen sizes. 3 | * 4 | * A basic example for taking a screen shot using phantomjs which is sampled for https://nodejs-dersleri.github.io/ 5 | * 6 | * usage : phantomjs responsive-screenshot.js {url} [output format] [doClipping] 7 | * 8 | * examples > 9 | * phantomjs responsive-screenshot.js https://nodejs-dersleri.github.io/ 10 | * phantomjs responsive-screenshot.js https://nodejs-dersleri.github.io/ pdf 11 | * phantomjs responsive-screenshot.js https://nodejs-dersleri.github.io/ true 12 | * phantomjs responsive-screenshot.js https://nodejs-dersleri.github.io/ png true 13 | * 14 | * @author Salih sagdilek 15 | */ 16 | 17 | /** 18 | * http://phantomjs.org/api/system/property/args.html 19 | * 20 | * Queries and returns a list of the command-line arguments. 21 | * The first one is always the script name, which is then followed by the subsequent arguments. 22 | */ 23 | var args = require('system').args; 24 | /** 25 | * http://phantomjs.org/api/fs/ 26 | * 27 | * file system api 28 | */ 29 | var fs = require('fs'); 30 | 31 | /** 32 | * http://phantomjs.org/api/webpage/ 33 | * 34 | * Web page api 35 | */ 36 | var page = new WebPage(); 37 | 38 | /** 39 | * if url address does not exist, exit phantom 40 | */ 41 | if ( 1 === args.length ) { 42 | console.log('Url address is required'); 43 | phantom.exit(); 44 | } 45 | 46 | /** 47 | * setup url address (second argument); 48 | */ 49 | var urlAddress = args[1].toLowerCase(); 50 | 51 | 52 | /** 53 | * set output extension format 54 | * @type {*} 55 | */ 56 | var ext = getFileExtension(); 57 | 58 | /** 59 | * set if clipping ? 60 | * @type {boolean} 61 | */ 62 | var clipping = getClipping(); 63 | 64 | /** 65 | * setup viewports 66 | */ 67 | var viewports = [ 68 | { 69 | width : 1200, 70 | height : 800 71 | }, 72 | { 73 | width : 1024, 74 | height : 768 75 | }, 76 | { 77 | width : 768, 78 | height : 1024 79 | }, 80 | { 81 | width : 480, 82 | height : 640 83 | }, 84 | { 85 | width : 320, 86 | height : 480 87 | } 88 | ]; 89 | 90 | page.open(urlAddress, function (status) { 91 | if ( 'success' !== status ) { 92 | console.log('Unable to load the url address!'); 93 | } else { 94 | var folder = urlToDir(urlAddress); 95 | var output, key; 96 | 97 | function render(n) { 98 | if ( !!n ) { 99 | key = n - 1; 100 | page.viewportSize = viewports[key]; 101 | if ( clipping ) { 102 | page.clipRect = viewports[key]; 103 | } 104 | output = folder + "/" + getFileName(viewports[key]); 105 | console.log('Saving ' + output); 106 | page.render(output); 107 | render(key); 108 | } 109 | } 110 | 111 | render(viewports.length); 112 | } 113 | phantom.exit(); 114 | }); 115 | 116 | /** 117 | * filename generator helper 118 | * @param viewport 119 | * @returns {string} 120 | */ 121 | function getFileName(viewport) { 122 | var d = new Date(); 123 | var date = [ 124 | d.getUTCFullYear(), 125 | d.getUTCMonth() + 1, 126 | d.getUTCDate() 127 | ]; 128 | var time = [ 129 | d.getHours() <= 9 ? '0' + d.getHours() : d.getHours(), 130 | d.getMinutes() <= 9 ? '0' + d.getMinutes() : d.getMinutes(), 131 | d.getSeconds() <= 9 ? '0' + d.getSeconds() : d.getSeconds(), 132 | d.getMilliseconds() 133 | ]; 134 | var resolution = viewport.width + (clipping ? "x" + viewport.height : ''); 135 | 136 | return date.join('-') + '_' + time.join('-') + "_" + resolution + ext; 137 | } 138 | 139 | /** 140 | * output extension format helper 141 | * 142 | * @returns {*} 143 | */ 144 | function getFileExtension() { 145 | if ( 'true' != args[2] && !!args[2] ) { 146 | return '.' + args[2]; 147 | } 148 | return '.png'; 149 | } 150 | 151 | /** 152 | * check if clipping 153 | * 154 | * @returns {boolean} 155 | */ 156 | function getClipping() { 157 | if ( 'true' == args[3] ) { 158 | return !!args[3]; 159 | } else if ( 'true' == args[2] ) { 160 | return !!args[2]; 161 | } 162 | return false; 163 | } 164 | 165 | /** 166 | * url to directory helper 167 | * 168 | * @param url 169 | * @returns {string} 170 | */ 171 | function urlToDir(url) { 172 | var dir = url 173 | .replace(/^(http|https):\/\//, '') 174 | .replace(/\/$/, ''); 175 | 176 | if ( !fs.makeTree(dir) ) { 177 | console.log('"' + dir + '" is NOT created.'); 178 | phantom.exit(); 179 | } 180 | return dir; 181 | } 182 | -------------------------------------------------------------------------------- /examples/run-jasmine.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var system = require('system'); 3 | 4 | /** 5 | * Wait until the test condition is true or a timeout occurs. Useful for waiting 6 | * on a server response or for a ui change (fadeIn, etc.) to occur. 7 | * 8 | * @param testFx javascript condition that evaluates to a boolean, 9 | * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or 10 | * as a callback function. 11 | * @param onReady what to do when testFx condition is fulfilled, 12 | * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or 13 | * as a callback function. 14 | * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used. 15 | */ 16 | function waitFor(testFx, onReady, timeOutMillis) { 17 | var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3001, //< Default Max Timeout is 3s 18 | start = new Date().getTime(), 19 | condition = false, 20 | interval = setInterval(function() { 21 | if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) { 22 | // If not time-out yet and condition not yet fulfilled 23 | condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code 24 | } else { 25 | if(!condition) { 26 | // If condition still not fulfilled (timeout but condition is 'false') 27 | console.log("'waitFor()' timeout"); 28 | phantom.exit(1); 29 | } else { 30 | // Condition fulfilled (timeout and/or condition is 'true') 31 | console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms."); 32 | typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled 33 | clearInterval(interval); //< Stop this interval 34 | } 35 | } 36 | }, 100); //< repeat check every 100ms 37 | }; 38 | 39 | 40 | if (system.args.length !== 2) { 41 | console.log('Usage: run-jasmine.js URL'); 42 | phantom.exit(1); 43 | } 44 | 45 | var page = require('webpage').create(); 46 | 47 | // Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this") 48 | page.onConsoleMessage = function(msg) { 49 | console.log(msg); 50 | }; 51 | 52 | page.open(system.args[1], function(status){ 53 | if (status !== "success") { 54 | console.log("Unable to open " + system.args[1]); 55 | phantom.exit(1); 56 | } else { 57 | waitFor(function(){ 58 | return page.evaluate(function(){ 59 | return document.body.querySelector('.symbolSummary .pending') === null 60 | }); 61 | }, function(){ 62 | var exitCode = page.evaluate(function(){ 63 | try { 64 | console.log(''); 65 | console.log(document.body.querySelector('.description').innerText); 66 | var list = document.body.querySelectorAll('.results > #details > .specDetail.failed'); 67 | if (list && list.length > 0) { 68 | console.log(''); 69 | console.log(list.length + ' test(s) FAILED:'); 70 | for (i = 0; i < list.length; ++i) { 71 | var el = list[i], 72 | desc = el.querySelector('.description'), 73 | msg = el.querySelector('.resultMessage.fail'); 74 | console.log(''); 75 | console.log(desc.innerText); 76 | console.log(msg.innerText); 77 | console.log(''); 78 | } 79 | return 1; 80 | } else { 81 | console.log(document.body.querySelector('.alert > .passingAlert.bar').innerText); 82 | return 0; 83 | } 84 | } catch (ex) { 85 | console.log(ex); 86 | return 1; 87 | } 88 | }); 89 | phantom.exit(exitCode); 90 | }); 91 | } 92 | }); 93 | -------------------------------------------------------------------------------- /examples/run-jasmine2.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var system = require('system'); 3 | 4 | /** 5 | * Wait until the test condition is true or a timeout occurs. Useful for waiting 6 | * on a server response or for a ui change (fadeIn, etc.) to occur. 7 | * 8 | * @param testFx javascript condition that evaluates to a boolean, 9 | * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or 10 | * as a callback function. 11 | * @param onReady what to do when testFx condition is fulfilled, 12 | * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or 13 | * as a callback function. 14 | * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used. 15 | */ 16 | function waitFor(testFx, onReady, timeOutMillis) { 17 | var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3001, //< Default Max Timeout is 3s 18 | start = new Date().getTime(), 19 | condition = false, 20 | interval = setInterval(function() { 21 | if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) { 22 | // If not time-out yet and condition not yet fulfilled 23 | condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code 24 | } else { 25 | if(!condition) { 26 | // If condition still not fulfilled (timeout but condition is 'false') 27 | console.log("'waitFor()' timeout"); 28 | phantom.exit(1); 29 | } else { 30 | // Condition fulfilled (timeout and/or condition is 'true') 31 | console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms."); 32 | typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled 33 | clearInterval(interval); //< Stop this interval 34 | } 35 | } 36 | }, 100); //< repeat check every 100ms 37 | }; 38 | 39 | 40 | if (system.args.length !== 2) { 41 | console.log('Usage: run-jasmine2.js URL'); 42 | phantom.exit(1); 43 | } 44 | 45 | var page = require('webpage').create(); 46 | 47 | // Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this") 48 | page.onConsoleMessage = function(msg) { 49 | console.log(msg); 50 | }; 51 | 52 | page.open(system.args[1], function(status){ 53 | if (status !== "success") { 54 | console.log("Unable to access network"); 55 | phantom.exit(); 56 | } else { 57 | waitFor(function(){ 58 | return page.evaluate(function(){ 59 | return (document.body.querySelector('.symbolSummary .pending') === null && 60 | document.body.querySelector('.duration') !== null); 61 | }); 62 | }, function(){ 63 | var exitCode = page.evaluate(function(){ 64 | console.log(''); 65 | 66 | var title = 'Jasmine'; 67 | var version = document.body.querySelector('.version').innerText; 68 | var duration = document.body.querySelector('.duration').innerText; 69 | var banner = title + ' ' + version + ' ' + duration; 70 | console.log(banner); 71 | 72 | var list = document.body.querySelectorAll('.results > .failures > .spec-detail.failed'); 73 | if (list && list.length > 0) { 74 | console.log(''); 75 | console.log(list.length + ' test(s) FAILED:'); 76 | for (i = 0; i < list.length; ++i) { 77 | var el = list[i], 78 | desc = el.querySelector('.description'), 79 | msg = el.querySelector('.messages > .result-message'); 80 | console.log(''); 81 | console.log(desc.innerText); 82 | console.log(msg.innerText); 83 | console.log(''); 84 | } 85 | return 1; 86 | } else { 87 | console.log(document.body.querySelector('.alert > .bar.passed,.alert > .bar.skipped').innerText); 88 | return 0; 89 | } 90 | }); 91 | phantom.exit(exitCode); 92 | }); 93 | } 94 | }); 95 | -------------------------------------------------------------------------------- /examples/run-qunit.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var system = require('system'); 3 | 4 | /** 5 | * Wait until the test condition is true or a timeout occurs. Useful for waiting 6 | * on a server response or for a ui change (fadeIn, etc.) to occur. 7 | * 8 | * @param testFx javascript condition that evaluates to a boolean, 9 | * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or 10 | * as a callback function. 11 | * @param onReady what to do when testFx condition is fulfilled, 12 | * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or 13 | * as a callback function. 14 | * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used. 15 | */ 16 | function waitFor(testFx, onReady, timeOutMillis) { 17 | var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3001, //< Default Max Timout is 3s 18 | start = new Date().getTime(), 19 | condition = false, 20 | interval = setInterval(function() { 21 | if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) { 22 | // If not time-out yet and condition not yet fulfilled 23 | condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code 24 | } else { 25 | if(!condition) { 26 | // If condition still not fulfilled (timeout but condition is 'false') 27 | console.log("'waitFor()' timeout"); 28 | phantom.exit(1); 29 | } else { 30 | // Condition fulfilled (timeout and/or condition is 'true') 31 | console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms."); 32 | typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled 33 | clearInterval(interval); //< Stop this interval 34 | } 35 | } 36 | }, 100); //< repeat check every 250ms 37 | }; 38 | 39 | 40 | if (system.args.length !== 2) { 41 | console.log('Usage: run-qunit.js URL'); 42 | phantom.exit(1); 43 | } 44 | 45 | var page = require('webpage').create(); 46 | 47 | // Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this") 48 | page.onConsoleMessage = function(msg) { 49 | console.log(msg); 50 | }; 51 | 52 | page.open(system.args[1], function(status){ 53 | if (status !== "success") { 54 | console.log("Unable to access network"); 55 | phantom.exit(1); 56 | } else { 57 | waitFor(function(){ 58 | return page.evaluate(function(){ 59 | var el = document.getElementById('qunit-testresult'); 60 | if (el && el.innerText.match('completed')) { 61 | return true; 62 | } 63 | return false; 64 | }); 65 | }, function(){ 66 | var failedNum = page.evaluate(function(){ 67 | var el = document.getElementById('qunit-testresult'); 68 | console.log(el.innerText); 69 | try { 70 | return el.getElementsByClassName('failed')[0].innerHTML; 71 | } catch (e) { } 72 | return 10000; 73 | }); 74 | phantom.exit((parseInt(failedNum, 10) > 0) ? 1 : 0); 75 | }); 76 | } 77 | }); 78 | -------------------------------------------------------------------------------- /examples/scandir.js: -------------------------------------------------------------------------------- 1 | // List all the files in a Tree of Directories 2 | 3 | "use strict"; 4 | var system = require('system'); 5 | 6 | if (system.args.length !== 2) { 7 | console.log("Usage: phantomjs scandir.js DIRECTORY_TO_SCAN"); 8 | phantom.exit(1); 9 | } 10 | 11 | var scanDirectory = function (path) { 12 | var fs = require('fs'); 13 | if (fs.exists(path) && fs.isFile(path)) { 14 | console.log(path); 15 | } else if (fs.isDirectory(path)) { 16 | fs.list(path).forEach(function (e) { 17 | if ( e !== "." && e !== ".." ) { //< Avoid loops 18 | scanDirectory(path + '/' + e); 19 | } 20 | }); 21 | } 22 | }; 23 | scanDirectory(system.args[1]); 24 | phantom.exit(); 25 | -------------------------------------------------------------------------------- /examples/server.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var page = require('webpage').create(); 3 | var server = require('webserver').create(); 4 | var system = require('system'); 5 | var host, port; 6 | 7 | if (system.args.length !== 2) { 8 | console.log('Usage: server.js '); 9 | phantom.exit(1); 10 | } else { 11 | port = system.args[1]; 12 | var listening = server.listen(port, function (request, response) { 13 | console.log("GOT HTTP REQUEST"); 14 | console.log(JSON.stringify(request, null, 4)); 15 | 16 | // we set the headers here 17 | response.statusCode = 200; 18 | response.headers = {"Cache": "no-cache", "Content-Type": "text/html"}; 19 | // this is also possible: 20 | response.setHeader("foo", "bar"); 21 | // now we write the body 22 | // note: the headers above will now be sent implictly 23 | response.write("YES!"); 24 | // note: writeBody can be called multiple times 25 | response.write("

pretty cool :)"); 26 | response.close(); 27 | }); 28 | if (!listening) { 29 | console.log("could not create web server listening on port " + port); 30 | phantom.exit(); 31 | } 32 | var url = "http://localhost:" + port + "/foo/bar.php?asdf=true"; 33 | console.log("SENDING REQUEST TO:"); 34 | console.log(url); 35 | page.open(url, function (status) { 36 | if (status !== 'success') { 37 | console.log('FAIL to load the address'); 38 | } else { 39 | console.log("GOT REPLY FROM SERVER:"); 40 | console.log(page.content); 41 | } 42 | phantom.exit(); 43 | }); 44 | } 45 | -------------------------------------------------------------------------------- /examples/serverkeepalive.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var port, server, service, 3 | system = require('system'); 4 | 5 | if (system.args.length !== 2) { 6 | console.log('Usage: serverkeepalive.js '); 7 | phantom.exit(1); 8 | } else { 9 | port = system.args[1]; 10 | server = require('webserver').create(); 11 | 12 | service = server.listen(port, { keepAlive: true }, function (request, response) { 13 | console.log('Request at ' + new Date()); 14 | console.log(JSON.stringify(request, null, 4)); 15 | 16 | var body = JSON.stringify(request, null, 4); 17 | response.statusCode = 200; 18 | response.headers = { 19 | 'Cache': 'no-cache', 20 | 'Content-Type': 'text/plain', 21 | 'Connection': 'Keep-Alive', 22 | 'Keep-Alive': 'timeout=5, max=100', 23 | 'Content-Length': body.length 24 | }; 25 | response.write(body); 26 | response.close(); 27 | }); 28 | 29 | if (service) { 30 | console.log('Web server running on port ' + port); 31 | } else { 32 | console.log('Error: Could not create web server listening on port ' + port); 33 | phantom.exit(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /examples/simpleserver.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var port, server, service, 3 | system = require('system'); 4 | 5 | if (system.args.length !== 2) { 6 | console.log('Usage: simpleserver.js '); 7 | phantom.exit(1); 8 | } else { 9 | port = system.args[1]; 10 | server = require('webserver').create(); 11 | 12 | service = server.listen(port, function (request, response) { 13 | 14 | console.log('Request at ' + new Date()); 15 | console.log(JSON.stringify(request, null, 4)); 16 | 17 | response.statusCode = 200; 18 | response.headers = { 19 | 'Cache': 'no-cache', 20 | 'Content-Type': 'text/html' 21 | }; 22 | response.write(''); 23 | response.write(''); 24 | response.write('Hello, world!'); 25 | response.write(''); 26 | response.write(''); 27 | response.write('

This is from PhantomJS web server.

'); 28 | response.write('

Request data:

'); 29 | response.write('
');
30 |         response.write(JSON.stringify(request, null, 4));
31 |         response.write('
'); 32 | response.write(''); 33 | response.write(''); 34 | response.close(); 35 | }); 36 | 37 | if (service) { 38 | console.log('Web server running on port ' + port); 39 | } else { 40 | console.log('Error: Could not create web server listening on port ' + port); 41 | phantom.exit(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /examples/sleepsort.js: -------------------------------------------------------------------------------- 1 | // sleepsort.js - Sort integers from the commandline in a very ridiculous way: leveraging timeouts :P 2 | 3 | "use strict"; 4 | var system = require('system'); 5 | 6 | function sleepSort(array, callback) { 7 | var sortedCount = 0, 8 | i, len; 9 | for ( i = 0, len = array.length; i < len; ++i ) { 10 | setTimeout((function(j){ 11 | return function() { 12 | console.log(array[j]); 13 | ++sortedCount; 14 | (len === sortedCount) && callback(); 15 | }; 16 | }(i)), array[i]); 17 | } 18 | } 19 | 20 | if ( system.args.length < 2 ) { 21 | console.log("Usage: phantomjs sleepsort.js PUT YOUR INTEGERS HERE SEPARATED BY SPACES"); 22 | phantom.exit(1); 23 | } else { 24 | sleepSort(system.args.slice(1), function() { 25 | phantom.exit(); 26 | }); 27 | } 28 | -------------------------------------------------------------------------------- /examples/stdin-stdout-stderr.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var system = require('system'); 3 | 4 | system.stdout.write('Hello, system.stdout.write!'); 5 | system.stdout.writeLine('\nHello, system.stdout.writeLine!'); 6 | 7 | system.stderr.write('Hello, system.stderr.write!'); 8 | system.stderr.writeLine('\nHello, system.stderr.writeLine!'); 9 | 10 | system.stdout.writeLine('system.stdin.readLine(): '); 11 | var line = system.stdin.readLine(); 12 | system.stdout.writeLine(JSON.stringify(line)); 13 | 14 | // This is essentially a `readAll` 15 | system.stdout.writeLine('system.stdin.read(5): (ctrl+D to end)'); 16 | var input = system.stdin.read(5); 17 | system.stdout.writeLine(JSON.stringify(input)); 18 | 19 | phantom.exit(0); 20 | -------------------------------------------------------------------------------- /examples/universe.js: -------------------------------------------------------------------------------- 1 | // This is to be used by "module.js" (and "module.coffee") example(s). 2 | // There should NOT be a "universe.coffee" as only 1 of the 2 would 3 | // ever be loaded unless the file extension was specified. 4 | 5 | "use strict"; 6 | exports.answer = 42; 7 | 8 | exports.start = function () { 9 | console.log('Starting the universe....'); 10 | } 11 | -------------------------------------------------------------------------------- /examples/unrandomize.js: -------------------------------------------------------------------------------- 1 | // Modify global object at the page initialization. 2 | // In this example, effectively Math.random() always returns 0.42. 3 | 4 | "use strict"; 5 | var page = require('webpage').create(); 6 | 7 | page.onInitialized = function () { 8 | page.evaluate(function () { 9 | Math.random = function() { 10 | return 42 / 100; 11 | }; 12 | }); 13 | }; 14 | 15 | page.open('http://ariya.github.com/js/random/', function (status) { 16 | var result; 17 | if (status !== 'success') { 18 | console.log('Network error.'); 19 | } else { 20 | console.log(page.evaluate(function () { 21 | return document.getElementById('numbers').textContent; 22 | })); 23 | } 24 | phantom.exit(); 25 | }); 26 | -------------------------------------------------------------------------------- /examples/useragent.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var page = require('webpage').create(); 3 | console.log('The default user agent is ' + page.settings.userAgent); 4 | page.settings.userAgent = 'SpecialAgent'; 5 | page.open('http://www.httpuseragent.org', function (status) { 6 | if (status !== 'success') { 7 | console.log('Unable to access network'); 8 | } else { 9 | var ua = page.evaluate(function () { 10 | return document.getElementById('myagent').innerText; 11 | }); 12 | console.log(ua); 13 | } 14 | phantom.exit(); 15 | }); 16 | -------------------------------------------------------------------------------- /examples/version.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | console.log('using PhantomJS version ' + 3 | phantom.version.major + '.' + 4 | phantom.version.minor + '.' + 5 | phantom.version.patch); 6 | phantom.exit(); 7 | -------------------------------------------------------------------------------- /examples/waitfor.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Wait until the test condition is true or a timeout occurs. Useful for waiting 3 | * on a server response or for a ui change (fadeIn, etc.) to occur. 4 | * 5 | * @param testFx javascript condition that evaluates to a boolean, 6 | * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or 7 | * as a callback function. 8 | * @param onReady what to do when testFx condition is fulfilled, 9 | * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or 10 | * as a callback function. 11 | * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used. 12 | */ 13 | 14 | "use strict"; 15 | function waitFor(testFx, onReady, timeOutMillis) { 16 | var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s 17 | start = new Date().getTime(), 18 | condition = false, 19 | interval = setInterval(function() { 20 | if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) { 21 | // If not time-out yet and condition not yet fulfilled 22 | condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code 23 | } else { 24 | if(!condition) { 25 | // If condition still not fulfilled (timeout but condition is 'false') 26 | console.log("'waitFor()' timeout"); 27 | phantom.exit(1); 28 | } else { 29 | // Condition fulfilled (timeout and/or condition is 'true') 30 | console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms."); 31 | typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled 32 | clearInterval(interval); //< Stop this interval 33 | } 34 | } 35 | }, 250); //< repeat check every 250ms 36 | }; 37 | 38 | 39 | var page = require('webpage').create(); 40 | 41 | // Open Twitter on 'sencha' profile and, onPageLoad, do... 42 | page.open("http://twitter.com/#!/sencha", function (status) { 43 | // Check for page load success 44 | if (status !== "success") { 45 | console.log("Unable to access network"); 46 | } else { 47 | // Wait for 'signin-dropdown' to be visible 48 | waitFor(function() { 49 | // Check in the page if a specific element is now visible 50 | return page.evaluate(function() { 51 | return $("#signin-dropdown").is(":visible"); 52 | }); 53 | }, function() { 54 | console.log("The sign-in dialog should be visible now."); 55 | phantom.exit(); 56 | }); 57 | } 58 | }); 59 | -------------------------------------------------------------------------------- /examples/walk_through_frames.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var p = require("webpage").create(); 3 | 4 | function pageTitle(page) { 5 | return page.evaluate(function(){ 6 | return window.document.title; 7 | }); 8 | } 9 | 10 | function setPageTitle(page, newTitle) { 11 | page.evaluate(function(newTitle){ 12 | window.document.title = newTitle; 13 | }, newTitle); 14 | } 15 | 16 | p.open("../test/webpage-spec-frames/index.html", function(status) { 17 | console.log("pageTitle(): " + pageTitle(p)); 18 | console.log("currentFrameName(): "+p.currentFrameName()); 19 | console.log("childFramesCount(): "+p.childFramesCount()); 20 | console.log("childFramesName(): "+p.childFramesName()); 21 | console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited"); 22 | console.log(""); 23 | 24 | console.log("p.switchToChildFrame(\"frame1\"): "+p.switchToChildFrame("frame1")); 25 | console.log("pageTitle(): " + pageTitle(p)); 26 | console.log("currentFrameName(): "+p.currentFrameName()); 27 | console.log("childFramesCount(): "+p.childFramesCount()); 28 | console.log("childFramesName(): "+p.childFramesName()); 29 | console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited"); 30 | console.log(""); 31 | 32 | console.log("p.switchToChildFrame(\"frame1-2\"): "+p.switchToChildFrame("frame1-2")); 33 | console.log("pageTitle(): " + pageTitle(p)); 34 | console.log("currentFrameName(): "+p.currentFrameName()); 35 | console.log("childFramesCount(): "+p.childFramesCount()); 36 | console.log("childFramesName(): "+p.childFramesName()); 37 | console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited"); 38 | console.log(""); 39 | 40 | console.log("p.switchToParentFrame(): "+p.switchToParentFrame()); 41 | console.log("pageTitle(): " + pageTitle(p)); 42 | console.log("currentFrameName(): "+p.currentFrameName()); 43 | console.log("childFramesCount(): "+p.childFramesCount()); 44 | console.log("childFramesName(): "+p.childFramesName()); 45 | console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited"); 46 | console.log(""); 47 | 48 | console.log("p.switchToChildFrame(0): "+p.switchToChildFrame(0)); 49 | console.log("pageTitle(): " + pageTitle(p)); 50 | console.log("currentFrameName(): "+p.currentFrameName()); 51 | console.log("childFramesCount(): "+p.childFramesCount()); 52 | console.log("childFramesName(): "+p.childFramesName()); 53 | console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited"); 54 | console.log(""); 55 | 56 | console.log("p.switchToMainFrame()"); p.switchToMainFrame(); 57 | console.log("pageTitle(): " + pageTitle(p)); 58 | console.log("currentFrameName(): "+p.currentFrameName()); 59 | console.log("childFramesCount(): "+p.childFramesCount()); 60 | console.log("childFramesName(): "+p.childFramesName()); 61 | console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited"); 62 | console.log(""); 63 | 64 | console.log("p.switchToChildFrame(\"frame2\"): "+p.switchToChildFrame("frame2")); 65 | console.log("pageTitle(): " + pageTitle(p)); 66 | console.log("currentFrameName(): "+p.currentFrameName()); 67 | console.log("childFramesCount(): "+p.childFramesCount()); 68 | console.log("childFramesName(): "+p.childFramesName()); 69 | console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited"); 70 | console.log(""); 71 | 72 | phantom.exit(); 73 | }); 74 | -------------------------------------------------------------------------------- /phantomjs.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andrewsyc/PhantomJS-Raspberry-Pi-3-/81ccd705cca08f2bed8078ee5ef1f190b6aebbfe/phantomjs.zip --------------------------------------------------------------------------------