Permalink
Browse files

Provide "detectType" inspired by D. Crockford

  • Loading branch information...
1 parent 3f87406 commit 60ced2ccb6649526dd1e2bb6967b417503e903de @detro detro committed Sep 26, 2012
Showing with 31 additions and 4 deletions.
  1. +19 −0 src/bootstrap.js
  2. +12 −4 src/modules/webpage.js
View
@@ -291,3 +291,22 @@ phantom.onError = phantom.defaultErrorHandler;
// Legacy way to use WebPage
window.WebPage = require('webpage').create;
+
+// Remedy to fauly "typeof": "typeOf" by Douglas Crockford
+// NOTE: Renamed to "detectType" and added support for RegExp
+// @see http://javascript.crockford.com/remedial.html
+window.detectType = function (value) {
+ var s = typeof value;
+ if (s === 'object') {
+ if (value) {
+ if (value instanceof Array) {
+ s = 'array';
+ } else if (value instanceof RegExp) {
+ s = 'regexp';
+ }
+ } else {
+ s = 'null';
+ }
+ }
+ return s;
+};
@@ -238,17 +238,25 @@ function decorateNewPage(opts, page) {
* @return {*} the function call result
*/
page.evaluate = function (func, args) {
- var str, arg, i, l;
+ var str, arg, argType, i, l;
if (!(func instanceof Function || typeof func === 'string' || func instanceof String)) {
throw "Wrong use of WebPage#evaluate";
}
str = 'function() { return (' + func.toString() + ')(';
for (i = 1, l = arguments.length; i < l; i++) {
arg = arguments[i];
- if (/object|string/.test(typeof arg) && !(arg instanceof RegExp)) {
- str += 'JSON.parse(' + JSON.stringify(JSON.stringify(arg)) + '),';
- } else {
+ argType = detectType(arg);
+
+ switch (argType) {
+ case "object": case "array": //< for type "object" and "array"
+ str += "JSON.parse(" + JSON.stringify(JSON.stringify(arg)) + "),"
@melletron
melletron Apr 2, 2014

The JSON.parse that gets evaluated on the client side, breaks the web-driver capabilities if a web developer decides to overwrite the browser native JSON with his/her own implementation. This is often the case with old obsoleted CMS. Nevertheless, we would like to use PhantomJS as a headless browser on those kind of pages.

Is there a way we can remove the client sided JSON reference?

+ break;
+ case "string": //< for type "string"
+ str += '"' + arg +'",';
+ break;
+ default: // for types: "null", "number", "function", "regexp", "undefined"
str += arg + ',';
+ break;
}
}
str = str.replace(/,$/, '') + '); }';

0 comments on commit 60ced2c

Please sign in to comment.