Returning from WebScriptObject evaluateWebScript:

I don’t know if this is common knowledge, but it took me a while to figure out and I didn’t find anything obvious about it online.

I’ve been writing an Objective-C (Cocoa) front end for a Javascript API and it involved a lot of two-way communication and passing WebScriptObjects around. (A WebScriptObject just being an Objective-C instance of a Javascript object.)

Anyway, my “discovery” is how to properly return a useful value using evaluateWebScript: instead of always using callWebScriptMethod:withArguments: with pre-made Javascript functions.

The simplest example is if I want to call evaluateWebScript: to return a WebScriptObject representation of a new Javascript object literal:

NSString *myObjectDef = @”{ property1: 10; property2: 12 }”;
NSString *script = [NSString stringWithFormat:@”var newObj = %@; newObj;”, myObjectDef];

Passing that script to evaluateWebScript: will return the value of “newObj” as a WebScriptObject that can be passed to other Javascript functions or inspected with valueForKey:.