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
|
||||
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)) + "),"
|
||||
break;
|
||||
case "string": //< for type "string"
|
||||
str += '"' + arg +'",';
|
||||
break;
|
||||
default: // for types: "null", "number", "function", "regexp", "undefined"
|
||||
str += arg + ',';
|
||||
break;
|
||||
}
|
||||
}
|
||||
str = str.replace(/,$/, '') + '); }';
|
||||
|
|
Loading…
Reference in New Issue