iOS 7 - Xamarin Recipe for JavascriptCore Framework - Part 2

0 Comments

As promised, I will show you how to call Javascript functions and how to pass parameters item them. This could be pretty useful if you wanted to make your application scriptable. Business logic can be written in Javascript, and then called with your custom parameters from C#! It's pretty simple actually.

The Script

First, lets define some Javascript function:

string script = "var square = function (x) { return x * x; }";

Easy enough. Evaluate the script using JSContext like this:

context.EvaluateScript (script);

This should all look pretty familiar if you looked at Part 1. The next step is to grab just the function from the script we want to use. Keep in mind that our Javascript is simple, but you could load in a file that has many functions like this in it.

Calling the Function

JSValue function = context [(NSString)"square"];
JSValue input = JSValue.From (3, context);
JSValue result = function.Call (input);
Console.WriteLine (result);

Thats all it takes! So what's going on here? First, we grab the square variable out of the Javascript, which is what we assigned our function to. Then we create the input for the method as a JSValue. Finally, we Call the function with our input and we log the result.

Wrapping Up

You can create any type of parameter, even custom class objects using the overrides of JSValue.From(). This is pretty powerful if you want to add some scripting capabilites to your app, all built into the Frameworks; cool!

The updated project to include this code is here.

Notes

There is an awesome blog post here, which is where I have been learning about this framework. The code is obj-c, but it is still really useful! Also, thanks to Sebastien Pouliot from Xamarin for helping me learn how to call these functions in Xamarin.iOS. You can find his blog here.

Comments