From 60ced2ccb6649526dd1e2bb6967b417503e903de Mon Sep 17 00:00:00 2001 From: Ivan De Marino Date: Wed, 26 Sep 2012 01:13:38 +0100 Subject: [PATCH] Provide "detectType" inspired by D. Crockford Addresses [Issue #800](http://code.google.com/p/phantomjs/issues/detail?id=800) --- src/bootstrap.js | 19 +++++++++++++++++++ src/modules/webpage.js | 16 ++++++++++++---- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/bootstrap.js b/src/bootstrap.js index 9910a745..ca491857 100644 --- a/src/bootstrap.js +++ b/src/bootstrap.js @@ -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; +}; diff --git a/src/modules/webpage.js b/src/modules/webpage.js index 1fd8d8a9..082d00d4 100644 --- a/src/modules/webpage.js +++ b/src/modules/webpage.js @@ -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)) + ")," + break; + case "string": //< for type "string" + str += '"' + arg +'",'; + break; + default: // for types: "null", "number", "function", "regexp", "undefined" str += arg + ','; + break; } } str = str.replace(/,$/, '') + '); }';