mirror of https://github.com/vitalif/phantomjs
Provide "detectType" inspired by D. Crockford
Addresses [Issue #800](http://code.google.com/p/phantomjs/issues/detail?id=800)1.8
parent
3f874067f5
commit
60ced2ccb6
|
@ -291,3 +291,22 @@ phantom.onError = phantom.defaultErrorHandler;
|
||||||
|
|
||||||
// Legacy way to use WebPage
|
// Legacy way to use WebPage
|
||||||
window.WebPage = require('webpage').create;
|
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
|
* @return {*} the function call result
|
||||||
*/
|
*/
|
||||||
page.evaluate = function (func, args) {
|
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)) {
|
if (!(func instanceof Function || typeof func === 'string' || func instanceof String)) {
|
||||||
throw "Wrong use of WebPage#evaluate";
|
throw "Wrong use of WebPage#evaluate";
|
||||||
}
|
}
|
||||||
str = 'function() { return (' + func.toString() + ')(';
|
str = 'function() { return (' + func.toString() + ')(';
|
||||||
for (i = 1, l = arguments.length; i < l; i++) {
|
for (i = 1, l = arguments.length; i < l; i++) {
|
||||||
arg = arguments[i];
|
arg = arguments[i];
|
||||||
if (/object|string/.test(typeof arg) && !(arg instanceof RegExp)) {
|
argType = detectType(arg);
|
||||||
str += 'JSON.parse(' + JSON.stringify(JSON.stringify(arg)) + '),';
|
|
||||||
} else {
|
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 + ',';
|
str += arg + ',';
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
str = str.replace(/,$/, '') + '); }';
|
str = str.replace(/,$/, '') + '); }';
|
||||||
|
|
Loading…
Reference in New Issue